@prismshadow/penguin-server 0.2.15 → 0.2.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 (101) hide show
  1. package/dist/api/types.d.ts +86 -40
  2. package/dist/api/types.js +1 -1
  3. package/dist/auth-token.d.ts +1 -1
  4. package/dist/auth-token.js +2 -2
  5. package/dist/{chunk-NVWAYYRX.js → chunk-3SFJKLQU.js} +38 -3
  6. package/dist/{chunk-NVWAYYRX.js.map → chunk-3SFJKLQU.js.map} +1 -1
  7. package/dist/{chunk-5Z4UCHDB.js → chunk-D3JNA6ZI.js} +69 -6
  8. package/dist/chunk-D3JNA6ZI.js.map +1 -0
  9. package/dist/{chunk-TOOTEEM4.js → chunk-G7GY7PJU.js} +1 -1
  10. package/dist/chunk-G7GY7PJU.js.map +1 -0
  11. package/dist/{chunk-JKJXQTHH.js → chunk-W7JNIJ25.js} +1 -1
  12. package/dist/chunk-W7JNIJ25.js.map +1 -0
  13. package/dist/index.js +3413 -2500
  14. package/dist/index.js.map +1 -1
  15. package/dist/machine-status.js +1 -1
  16. package/dist/plugin/index.d.ts +28 -20
  17. package/dist/reset-admin-password.js +3 -4
  18. package/dist/reset-admin-password.js.map +1 -1
  19. package/package.json +5 -9
  20. package/web-dist/assets/{abnfDiagram-VCTEODGH-CKWh4hoA.js → abnfDiagram-VCTEODGH-0AKFiyig.js} +1 -1
  21. package/web-dist/assets/{addon-clipboard-DxLqat7q.js → addon-clipboard-BovFnNVg.js} +1 -1
  22. package/web-dist/assets/{addon-fit-B8oPGPkW.js → addon-fit-B1npgxQk.js} +1 -1
  23. package/web-dist/assets/{addon-web-links-C0W5TcK0.js → addon-web-links-D88QHj7A.js} +1 -1
  24. package/web-dist/assets/{arc-Dp9EkaAH.js → arc-Beox1Cgf.js} +1 -1
  25. package/web-dist/assets/{architectureDiagram-5GKGNRK7-BQ3LUcle.js → architectureDiagram-5GKGNRK7-CC1sLMY1.js} +1 -1
  26. package/web-dist/assets/{blockDiagram-I7D4REHJ-CZzyU0Jj.js → blockDiagram-I7D4REHJ-B8BY1PkZ.js} +1 -1
  27. package/web-dist/assets/{c4Diagram-7LVT6UL2-Qps3jeAu.js → c4Diagram-7LVT6UL2-yjY0BkxQ.js} +1 -1
  28. package/web-dist/assets/channel-mfsAVJLE.js +1 -0
  29. package/web-dist/assets/{chunk-2Q5K7J3B-CQMntzuX.js → chunk-2Q5K7J3B-DdgIvETg.js} +1 -1
  30. package/web-dist/assets/{chunk-5VM5RSS4-2H2ZJAte.js → chunk-5VM5RSS4-BE38k1Rs.js} +1 -1
  31. package/web-dist/assets/{chunk-F27PBJKO-B30xCNBv.js → chunk-F27PBJKO-D4YXmaqQ.js} +1 -1
  32. package/web-dist/assets/{chunk-IMKFNOWR-Cyfx4zDs.js → chunk-IMKFNOWR-CyJFdThc.js} +1 -1
  33. package/web-dist/assets/{chunk-JWPE2WC7-DADUytTh.js → chunk-JWPE2WC7-BAM_oEUU.js} +1 -1
  34. package/web-dist/assets/{chunk-POPQ4Y6H-9bjsAxLS.js → chunk-POPQ4Y6H-BP3D0FVi.js} +1 -1
  35. package/web-dist/assets/{chunk-SVP7TREG-B9xO1VpN.js → chunk-SVP7TREG-Clk8PdKZ.js} +1 -1
  36. package/web-dist/assets/{chunk-TICWLB2K-B6oDkrep.js → chunk-TICWLB2K-EvWPnEGg.js} +1 -1
  37. package/web-dist/assets/{chunk-XXDRQBXY-BbU8DR4B.js → chunk-XXDRQBXY-6p5D0UB1.js} +1 -1
  38. package/web-dist/assets/classDiagram-ZZMXUADV-BPVO1m8i.js +1 -0
  39. package/web-dist/assets/classDiagram-v2-VYDZK3BY-BPVO1m8i.js +1 -0
  40. package/web-dist/assets/{cose-bilkent-JH36ORCC-pkbuyec-.js → cose-bilkent-JH36ORCC-bpkI-tLJ.js} +1 -1
  41. package/web-dist/assets/{cynefin-OW5HDTMX-DU9YQQnc.js → cynefin-OW5HDTMX-srLaqJ4e.js} +1 -1
  42. package/web-dist/assets/{cynefinDiagram-5FMLGOSQ-3a3XuhQq.js → cynefinDiagram-5FMLGOSQ-BPfpHSPc.js} +1 -1
  43. package/web-dist/assets/{dagre-GXQ25YYZ-BfZ9C5CZ.js → dagre-GXQ25YYZ-C4fF5-j7.js} +1 -1
  44. package/web-dist/assets/{diagram-S7CK7UJ4-BoGhVBMn.js → diagram-S7CK7UJ4-BzBLb_9-.js} +1 -1
  45. package/web-dist/assets/{diagram-UQ7AKVKN-zE67quty.js → diagram-UQ7AKVKN-BJuJ1o_T.js} +1 -1
  46. package/web-dist/assets/{diagram-VSXAHHWV-NihoXeXm.js → diagram-VSXAHHWV-DFelN9i9.js} +1 -1
  47. package/web-dist/assets/{diagram-VX7I27RA-1627np0S.js → diagram-VX7I27RA-BgrEoPyp.js} +1 -1
  48. package/web-dist/assets/{diagram-Z3DM3KII-Ddg_bUan.js → diagram-Z3DM3KII-C71KiMiX.js} +1 -1
  49. package/web-dist/assets/{ebnfDiagram-PWID7BFC-CmPUOM4j.js → ebnfDiagram-PWID7BFC-EYteyp1b.js} +1 -1
  50. package/web-dist/assets/{erDiagram-RLTQ6QDP-DiTnEK72.js → erDiagram-RLTQ6QDP-B6n6-sz6.js} +1 -1
  51. package/web-dist/assets/{flowDiagram-HODETNUW-mGQ38tRM.js → flowDiagram-HODETNUW-BtoMTdyT.js} +1 -1
  52. package/web-dist/assets/{ganttDiagram-EL5Y4UJY-DU7MlzpW.js → ganttDiagram-EL5Y4UJY-CbOAa3vS.js} +1 -1
  53. package/web-dist/assets/{gitGraphDiagram-WWUBYQGX-CRE_3vjl.js → gitGraphDiagram-WWUBYQGX-B7-8sszH.js} +1 -1
  54. package/web-dist/assets/{highlighter-CzfXQ6yd.js → highlighter-Bj5l2XH_.js} +2 -2
  55. package/web-dist/assets/{highlighter-core-B5CvXcEK.js → highlighter-core-CMXoD8ze.js} +1 -1
  56. package/web-dist/assets/index-BOCqRT4e.css +1 -0
  57. package/web-dist/assets/index-BrMpjp2s.js +1286 -0
  58. package/web-dist/assets/{infoDiagram-27XIBGKW-Cdo6Ar-a.js → infoDiagram-27XIBGKW-BBjf6pkP.js} +1 -1
  59. package/web-dist/assets/{ishikawaDiagram-5VMMS53U-C27pgect.js → ishikawaDiagram-5VMMS53U-BBSvCv45.js} +1 -1
  60. package/web-dist/assets/{journeyDiagram-3NMN7TZE-CVxtKpLG.js → journeyDiagram-3NMN7TZE-CuHHl5zk.js} +1 -1
  61. package/web-dist/assets/{kanban-definition-UXKFOSKX-DWA31Da7.js → kanban-definition-UXKFOSKX-DJyP4Myw.js} +1 -1
  62. package/web-dist/assets/{layout-DWKCU9PO.js → layout-Bqqhdwtt.js} +1 -1
  63. package/web-dist/assets/{linear-BwCthj_k.js → linear-BZfUSIf8.js} +1 -1
  64. package/web-dist/assets/{mermaid.core-BcTrmPOv.js → mermaid.core-BlUspEsI.js} +6 -6
  65. package/web-dist/assets/{mindmap-definition-YA3MSWOX-BLEDhbn1.js → mindmap-definition-YA3MSWOX-BtyMD4wz.js} +1 -1
  66. package/web-dist/assets/{pegDiagram-XKGWAZYB-CLEM1SDU.js → pegDiagram-XKGWAZYB-BUF_GJ0B.js} +1 -1
  67. package/web-dist/assets/{pieDiagram-E7YTZNPT-B__g6eF0.js → pieDiagram-E7YTZNPT-nweubbsU.js} +1 -1
  68. package/web-dist/assets/{quadrantDiagram-AXDQQJYC-C7VQ2LMY.js → quadrantDiagram-AXDQQJYC-B_r4Wkxy.js} +1 -1
  69. package/web-dist/assets/{railroadDiagram-O6MQD6OU-eWNnzjwS.js → railroadDiagram-O6MQD6OU-Dn7nm0MX.js} +1 -1
  70. package/web-dist/assets/{requirementDiagram-BXWQKSXE-Bi5qeD4b.js → requirementDiagram-BXWQKSXE-DaagYJ49.js} +1 -1
  71. package/web-dist/assets/{sankeyDiagram-P5KCCOFB-DG1VOpXX.js → sankeyDiagram-P5KCCOFB-CqEX6H-B.js} +1 -1
  72. package/web-dist/assets/{sequenceDiagram-WJ2MYXX4-Fhkw73Th.js → sequenceDiagram-WJ2MYXX4-BzLfQO55.js} +1 -1
  73. package/web-dist/assets/{sizeCapture-INFHLROL-D9E_17SF.js → sizeCapture-INFHLROL-BcUuVH2L.js} +1 -1
  74. package/web-dist/assets/{stateDiagram-D77RDMKH-Cs5Y0xhW.js → stateDiagram-D77RDMKH-BO3LWLvT.js} +1 -1
  75. package/web-dist/assets/stateDiagram-v2-MP3YSRHH-B-EuucjM.js +1 -0
  76. package/web-dist/assets/{swimlanes-42K2YHIH-t-EocvKZ.js → swimlanes-42K2YHIH-etP_hkIB.js} +1 -1
  77. package/web-dist/assets/swimlanesDiagram-VR7AAH4N-0JbFdDbQ.js +8 -0
  78. package/web-dist/assets/{timeline-definition-24CTP7MA-CozGCxuA.js → timeline-definition-24CTP7MA-CTLt2XCT.js} +1 -1
  79. package/web-dist/assets/{vennDiagram-4TSXK5OY-ewU8ycSa.js → vennDiagram-4TSXK5OY-DPO6ZSvH.js} +1 -1
  80. package/web-dist/assets/{wardleyDiagram-VM6X3IG4-DuAhDu-0.js → wardleyDiagram-VM6X3IG4-DFofGg8b.js} +1 -1
  81. package/web-dist/assets/{xterm-v5e56GC9.js → xterm-RdyTuaAH.js} +1 -1
  82. package/web-dist/assets/{xychartDiagram-S5SC5T6Z-BxGuZO23.js → xychartDiagram-S5SC5T6Z-Bgtb34Gu.js} +1 -1
  83. package/web-dist/index.html +8 -3
  84. package/web-dist/{workflow-ui.css → workbench-ui.css} +72 -67
  85. package/dist/benchmark-package.d.ts +0 -39
  86. package/dist/benchmark-package.js +0 -97
  87. package/dist/benchmark-package.js.map +0 -1
  88. package/dist/chunk-54E64LWB.js +0 -63
  89. package/dist/chunk-54E64LWB.js.map +0 -1
  90. package/dist/chunk-5Z4UCHDB.js.map +0 -1
  91. package/dist/chunk-JKJXQTHH.js.map +0 -1
  92. package/dist/chunk-Q4ON2L6E.js +0 -52
  93. package/dist/chunk-Q4ON2L6E.js.map +0 -1
  94. package/dist/chunk-TOOTEEM4.js.map +0 -1
  95. package/web-dist/assets/channel--PblgLlC.js +0 -1
  96. package/web-dist/assets/classDiagram-ZZMXUADV-mn8tbuqa.js +0 -1
  97. package/web-dist/assets/classDiagram-v2-VYDZK3BY-mn8tbuqa.js +0 -1
  98. package/web-dist/assets/index-BdG4qRyI.js +0 -1275
  99. package/web-dist/assets/index-W-xYFoIm.css +0 -1
  100. package/web-dist/assets/stateDiagram-v2-MP3YSRHH-CEM51fAf.js +0 -1
  101. package/web-dist/assets/swimlanesDiagram-VR7AAH4N-BrR66vrK.js +0 -8
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/db/database.ts","../src/db/migrations.ts","../src/db/schema.ts"],"sourcesContent":["/**\n * SQLite connection & initialization (node:sqlite DatabaseSync).\n *\n * Single process, single writer: a synchronous API is sufficient and avoids a connection\n * pool; WAL mode and foreign key constraints are enabled. Table-creation SQL runs on open\n * (idempotent), with no migration branches (product not yet released).\n */\nimport { mkdirSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type { DatabaseSync } from \"node:sqlite\";\nimport { migrate } from \"./migrations.js\";\nimport { SCHEMA_SQL } from \"./schema.js\";\n\n// Fetch the runtime module via process.getBuiltinModule (node >=22.3): avoids static\n// resolution of `node:sqlite` by bundlers/vite (some tools' builtin lists don't yet\n// recognize this experimental module).\nconst sqlite = process.getBuiltinModule(\"node:sqlite\");\n\n/**\n * Opens an EXISTING database for a narrow write, without running any schema work.\n *\n * `openDatabase` migrates — CREATE TABLE, several ensureColumn calls, a DROP INDEX and a backfill.\n * That is right for the process that owns the database and wrong for a short-lived CLI writing\n * one row (`penguin auth token`): after `penguin update` the CLI on disk can be NEWER than the\n * running server, and migrating under a live server's prepared statements is not something a\n * token mint should do. The caller has already established that the file exists.\n */\nexport function openExistingDatabase(dbPath: string): DatabaseSync {\n const db = new sqlite.DatabaseSync(dbPath);\n db.exec(\"PRAGMA foreign_keys = ON;\");\n // Wait for the live server's write lock instead of failing SQLITE_BUSY at once.\n db.exec(\"PRAGMA busy_timeout = 5000;\");\n return db;\n}\n\n/**\n * Opens an EXISTING database for reading only — SQLite refuses every write on the connection,\n * so a reader cannot change the file even by mistake. For a question asked of a database some\n * other process owns (`penguin server status`, run over ssh by a controller): the answer must\n * not reshape that server's schema, and must not be able to. The caller has established that\n * the file exists; a read-only open of a missing file is an error, not a creation.\n */\nexport function openDatabaseReadOnly(dbPath: string): DatabaseSync {\n const db = new sqlite.DatabaseSync(dbPath, { readOnly: true });\n db.exec(\"PRAGMA busy_timeout = 5000;\");\n return db;\n}\n\n/** Open (creating if necessary) the database: ensure the parent directory exists, set PRAGMAs, run table creation. */\nexport function openDatabase(dbPath: string): DatabaseSync {\n if (dbPath !== \":memory:\") {\n mkdirSync(path.dirname(dbPath), { recursive: true });\n }\n const db = new sqlite.DatabaseSync(dbPath);\n db.exec(\"PRAGMA journal_mode = WAL;\");\n // A second connection (the CLI minting a token while the server runs) waits for the write\n // lock rather than failing SQLITE_BUSY at once.\n db.exec(\"PRAGMA busy_timeout = 5000;\");\n db.exec(\"PRAGMA foreign_keys = ON;\");\n db.exec(SCHEMA_SQL);\n // Columns added to the schema after a web.db was formed: CREATE TABLE IF NOT EXISTS never\n // touches an existing table, so they are ALTERed in here. Keep the list in sync with\n // schema.ts; drop entries only in a release allowed to break existing web.db files.\n ensureColumn(db, \"sessions\", \"client\", \"TEXT\");\n ensureColumn(db, \"sessions\", \"has_trace\", \"INTEGER NOT NULL DEFAULT 0\");\n ensureColumn(db, \"sessions\", \"fork_count\", \"INTEGER NOT NULL DEFAULT 0\");\n ensureColumn(db, \"sessions\", \"thinking_level\", \"TEXT\");\n ensureColumn(db, \"sessions\", \"sandbox\", \"TEXT\");\n // A v0.2.0 web.db has auth_sessions without `via`; CREATE TABLE IF NOT EXISTS never adds a\n // column, so every INSERT would fail \"no column named via\" until this runs.\n ensureColumn(db, \"auth_sessions\", \"via\", \"TEXT\");\n ensureColumn(db, \"trace_files\", \"page_stats\", \"TEXT\");\n ensureColumn(db, \"messaging_bindings\", \"line_per_message\", \"INTEGER NOT NULL DEFAULT 0\");\n ensureColumn(db, \"messaging_bindings\", \"final_reply_only\", \"INTEGER NOT NULL DEFAULT 0\");\n // DEFAULT 1, unlike every other added flag here: this one's default is the CORRECTED\n // behaviour, not the previous one. Sending the model's Markdown as characters was the\n // defect, so an existing binding starts rendering it — a visible change to every relayed\n // message, recorded in the release's backward-compatibility entry.\n ensureColumn(db, \"messaging_bindings\", \"render_markdown\", \"INTEGER NOT NULL DEFAULT 1\");\n ensureColumn(db, \"messaging_bindings\", \"last_inbound_message_id\", \"TEXT\");\n // Superseded by idx_usage_session_ts (session_id, ts), which SCHEMA_SQL just created on\n // this database: the old index is a strict prefix of it, so every query it served is\n // served identically. Dropping is safe — an index is derived, never data.\n db.exec(\"DROP INDEX IF EXISTS idx_usage_session\");\n // The uniqueness index of the old binding model, where a bot account belonged to one\n // Session forever and a second Session could not even SAVE its credentials. Enabling a\n // connection is the binding now, so exclusivity is checked per enable (the state route's\n // 409 account_enabled_elsewhere) and the same account may sit saved on many Sessions —\n // which this index would reject. SCHEMA_SQL has just created idx_messaging_by_account\n // over the same columns, so the by-account lookup stays indexed. Dropping is safe: an\n // index is derived, never data. It is however ONE-WAY — an older build recreates the\n // unique index on open, which fails outright once duplicate (channel, account_id) rows\n // exist, so a downgrade after two Sessions saved the same bot needs those rows removed.\n db.exec(\"DROP INDEX IF EXISTS idx_messaging_account\");\n upgradeLastActiveAt(db);\n // The runtime's own open is the ONLY place a restart-only migration may be applied: it\n // owns the process, so there is no boot to roll back out from under it.\n migrate(db);\n return db;\n}\n\n/**\n * One-time `sessions.last_active_at` upgrade, ALTER + backfill in a single transaction.\n *\n * The backfill runs **only in the open that actually adds the column** (SQLite's ALTER\n * TABLE ADD COLUMN is transactional, so a crash mid-upgrade rolls back to \"no column\" and\n * the next open redoes both halves — never a half-migrated table, and never a full\n * `sessions` scan on the millions of opens that follow). Legacy rows take the session's\n * most recent request timestamp — usage_records, covered by idx_usage_session_ts, the\n * closest persisted proxy for \"last Trace activity\" — else their own created_at.\n */\nfunction upgradeLastActiveAt(db: DatabaseSync): void {\n db.exec(\"BEGIN\");\n try {\n if (ensureColumn(db, \"sessions\", \"last_active_at\", \"TEXT\")) {\n db.exec(\n `UPDATE sessions SET last_active_at = COALESCE(\n (SELECT MAX(ts) FROM usage_records WHERE usage_records.session_id = sessions.session_id),\n created_at\n )`,\n );\n }\n db.exec(\"COMMIT\");\n } catch (err) {\n db.exec(\"ROLLBACK\");\n throw err;\n }\n}\n\n/**\n * Idempotent per-column upgrade for databases formed before the column existed.\n * Returns whether this call actually ALTERed the table (false = the column was already\n * there), so a caller can gate one-time backfill work on it.\n */\nexport function ensureColumn(\n db: DatabaseSync,\n table: string,\n column: string,\n ddl: string,\n): boolean {\n const cols = db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[];\n if (cols.some((c) => c.name === column)) return false;\n db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${ddl}`);\n return true;\n}\n","/**\n * Ordered, versioned schema migrations.\n *\n * `schema.ts` declares the shape a FRESH database is created with. It cannot express a\n * CHANGE — `CREATE TABLE IF NOT EXISTS` only ever says \"should exist\", so re-running it\n * converges a database toward the current declaration without ever knowing, or recording,\n * which state it came from. That is why a build could not tell a 0.2.4 database from a\n * 0.2.7 one, and why the only safe change was an additive one.\n *\n * A migration says what CHANGED, runs once, and leaves the database stamped with how far\n * it has come (`PRAGMA user_version`). Two rules make that stamp trustworthy:\n *\n * FROZEN DDL. A migration spells out its own SQL and never imports SCHEMA_SQL. Referring\n * to the live declaration would make an old migration silently mean something new every\n * time the schema moves, which is the property that makes migrations auditable at all.\n *\n * ONE WAY, IN ORDER. Versions are contiguous from 1 and never renumbered or rewritten\n * once released — a database that already stamped version N will never run N again, so\n * editing N only changes what NEW databases get, and silently forks the two.\n *\n * `swapSafe` is this codebase's extra axis, and it exists because of hot updates. A\n * pushed platform boots against a live database and is ROLLED BACK to its predecessor if\n * it fails; the predecessor then runs on whatever the migration already did. Additive\n * work survives that (the older build does not know the new table, so it never touches\n * it) — narrowing work does not. Anything that drops, retypes, constrains, or reshapes\n * is `swapSafe: false` and must be refused on the swap path rather than half-applied\n * (see `migrate`'s `swapPath` option).\n *\n * DOWN, AND WHO DOES NOT CALL IT. Every migration declares an undo — or declares `null`\n * to say it has none, which is a decision the author has to make rather than omit. What\n * `down` is NOT is the hot-update rollback mechanism. When a pushed platform fails to boot\n * the runtime reverts to its PREDECESSOR and the schema stays where the migration left it:\n * undoing DDL inside a process whose boot just failed would run destructive statements\n * against a half-known state, and `swapSafe` exists precisely so that not undoing is safe —\n * the predecessor does not know the new table or column, so it never touches it. `down` is\n * an operator's tool, called deliberately (`rollbackTo`), never by the swap.\n *\n * It is also LOSSY by nature: undoing \"add a table\" drops that table with its rows in it.\n * Each `down` below names what its rows were.\n *\n * ADOPTION. Databases created before this file existed are all stamped 0 while sitting in\n * genuinely different shapes, so a migration must tolerate finding its work already done.\n * That is not only a version-1 concern: `schema.ts` still DECLARES the current shape in\n * full and `openDatabase` still runs its ensureColumn list, so a database can arrive at a\n * migration with that migration's work already applied by the declarative track. Until\n * SCHEMA_SQL is frozen to a baseline and every later change is a migration, every\n * migration here stays idempotent — `IF NOT EXISTS`, or the same `ensureColumn` guard the\n * declarative track uses. Once that double track is gone, a bare `CREATE TABLE` that\n * fails loudly becomes the point.\n */\nimport type { DatabaseSync } from \"node:sqlite\";\nimport { ensureColumn } from \"./database.js\";\n\nexport interface Migration {\n /** Contiguous from 1. Never renumbered, never edited once released. */\n version: number;\n /** Kebab-case, names the change — read in logs and in the stamp's history. */\n name: string;\n /**\n * May this run while a pushed platform boots? True only for strictly additive work,\n * which a rollback to the previous platform survives. See the module doc.\n */\n swapSafe: boolean;\n /** Applied inside a transaction; throw to abort and leave the version unchanged. */\n up: (db: DatabaseSync) => void;\n /**\n * Undoes `up`, or null when this migration cannot be undone — required, not optional, so\n * \"there is no undo\" is something the author states rather than forgets.\n *\n * Never called by the swap path (see the module doc): a failed boot reverts the platform,\n * not the schema. Reached only through `rollbackTo`, and destructive by nature — dropping\n * a table takes its rows with it.\n */\n down: ((db: DatabaseSync) => void) | null;\n}\n\nexport const MIGRATIONS: readonly Migration[] = [\n {\n version: 1,\n name: \"messaging-bindings\",\n // Purely additive: one new table plus three indexes, no column of any existing table\n // touched. A platform that rolls back to a predecessor without messaging simply never\n // queries them.\n swapSafe: true,\n up(db) {\n // 0.2.4 → 0.2.7. Frozen copy of the DDL as of 0.2.7; do not re-derive from schema.ts.\n // IF NOT EXISTS only because version 1 adopts unstamped databases, which may already\n // be at 0.2.7 (see the module doc's ADOPTION note).\n db.exec(`\n CREATE TABLE IF NOT EXISTS messaging_bindings (\n session_id TEXT NOT NULL,\n channel TEXT NOT NULL,\n account_id TEXT NOT NULL,\n config_json TEXT NOT NULL,\n enabled INTEGER NOT NULL DEFAULT 0,\n line_per_message INTEGER NOT NULL DEFAULT 0,\n last_chat_id TEXT,\n last_chat_is_direct INTEGER NOT NULL DEFAULT 1,\n last_inbound_message_id TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (session_id, channel)\n );\n CREATE INDEX IF NOT EXISTS idx_messaging_by_account ON messaging_bindings(channel, account_id);\n CREATE INDEX IF NOT EXISTS idx_auth_sessions_expires ON auth_sessions(expires_at);\n CREATE INDEX IF NOT EXISTS idx_auth_sessions_user ON auth_sessions(user_id);\n `);\n },\n // LOSES every messaging binding: the channel credentials, the enabled flag and the\n // last-chat memory all live in the table this drops. The auth_sessions indexes are\n // derived and cost nothing to lose.\n down(db) {\n db.exec(`\n DROP INDEX IF EXISTS idx_auth_sessions_user;\n DROP INDEX IF EXISTS idx_auth_sessions_expires;\n DROP INDEX IF EXISTS idx_messaging_by_account;\n DROP TABLE IF EXISTS messaging_bindings;\n `);\n },\n },\n {\n version: 2,\n name: \"messaging-delivery-flags\",\n // Two columns with defaults on an existing table: a rollback to a predecessor that\n // does not know them leaves them at their defaults and reads nothing.\n swapSafe: true,\n up(db) {\n // 0.2.7 → 0.2.8. ensureColumn rather than a bare ALTER because the declarative\n // track may already have added these (see the module doc's ADOPTION note).\n ensureColumn(db, \"messaging_bindings\", \"final_reply_only\", \"INTEGER NOT NULL DEFAULT 0\");\n ensureColumn(db, \"messaging_bindings\", \"render_markdown\", \"INTEGER NOT NULL DEFAULT 1\");\n },\n // LOSES both delivery preferences on every binding; the bindings themselves survive.\n // Dropped in reverse order for symmetry with `up`. Neither column is indexed, which is\n // what lets SQLite drop them at all.\n down(db) {\n db.exec(\"ALTER TABLE messaging_bindings DROP COLUMN render_markdown\");\n db.exec(\"ALTER TABLE messaging_bindings DROP COLUMN final_reply_only\");\n },\n },\n {\n version: 3,\n name: \"drop-goal-state\",\n // Narrowing: drops a table. A pushed platform rolled back to 0.2.9 mid-process would\n // prepare its goal statements against a table that is gone (its declarative track only\n // runs at the runtime's own open, never at a platform boot), so this is the first\n // restart-only migration: refused on the swap path, applied by the runtime's open.\n swapSafe: false,\n up(db) {\n // 0.2.9 → 0.2.10. goal_state held goal mode's run state, one row per goal run, read\n // back only for the chat page's goal banner; the goal plugin's GOAL.json in the\n // Session scratchpad is that record now (see runtime/goal-events.ts). IF EXISTS only\n // because a database this build created never had the table.\n db.exec(`\n DROP INDEX IF EXISTS idx_goal_session;\n DROP TABLE IF EXISTS goal_state;\n `);\n },\n // Recreates the table exactly as 0.2.9 declared it — EMPTY. LOSES every goal run ever\n // recorded (objective, status, budget, used, rounds per run): the rows only ever fed the\n // banner of a finished goal, and a build with this migration reads the goal file instead.\n down(db) {\n db.exec(`\n CREATE TABLE IF NOT EXISTS goal_state (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n session_id TEXT NOT NULL,\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n objective TEXT NOT NULL,\n status TEXT NOT NULL,\n budget INTEGER NOT NULL,\n used INTEGER NOT NULL DEFAULT 0,\n rounds INTEGER NOT NULL DEFAULT 0,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_goal_session ON goal_state(session_id);\n `);\n },\n },\n {\n version: 4,\n name: \"machines\",\n // Three new tables, nothing existing touched: a platform rolled back to one without\n // machines never queries them. Swap-safe on its own; a database still behind\n // drop-goal-state is refused whole by that one first, which is the rule.\n swapSafe: true,\n up(db) {\n // Frozen copy of the DDL as of the machines feature; do not re-derive from schema.ts.\n // IF NOT EXISTS because the declarative track may already have created them (ADOPTION).\n db.exec(`\n CREATE TABLE IF NOT EXISTS machine (\n singleton INTEGER PRIMARY KEY CHECK (singleton = 1),\n machine_id TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS machines (\n address TEXT PRIMARY KEY,\n machine_id TEXT,\n version TEXT,\n installed_at TEXT,\n session_pid INTEGER,\n remote_port INTEGER,\n platform TEXT\n );\n CREATE TABLE IF NOT EXISTS machine_project (\n project_id TEXT PRIMARY KEY REFERENCES projects(project_id) ON DELETE CASCADE,\n addresses TEXT NOT NULL\n );\n `);\n },\n // LOSES this server's own machine id (every stored reference to it on other machines\n // then points at nothing), what was installed where, the sessions held, and which\n // machines each Project used.\n down(db) {\n db.exec(`\n DROP TABLE IF EXISTS machine_project;\n DROP TABLE IF EXISTS machines;\n DROP TABLE IF EXISTS machine;\n `);\n },\n },\n {\n version: 5,\n name: \"user-profile\",\n // Two nullable columns on `users`, no default and nothing existing rewritten: a platform\n // rolled back to a predecessor that does not know them never selects or writes them, and\n // every existing account simply reads NULL — no profile yet.\n swapSafe: true,\n up(db) {\n // Frozen copy of the DDL as of the user-profile feature; do not re-derive from schema.ts.\n // SQLite has no ADD COLUMN IF NOT EXISTS, and the declarative track may already have\n // added both (ADOPTION), so each one goes through the same table_info guard the\n // declarative track uses.\n ensureColumn(db, \"users\", \"display_name\", \"TEXT\");\n ensureColumn(db, \"users\", \"avatar\", \"TEXT\");\n },\n // LOSES every stored nickname and avatar: both live entirely in the two columns this\n // drops, and nothing else on disk holds a copy. Dropped in reverse order for symmetry\n // with `up`; neither column is indexed, which is what lets SQLite drop them at all.\n down(db) {\n const cols = db.prepare(\"PRAGMA table_info(users)\").all() as { name: string }[];\n const has = (name: string): boolean => cols.some((c) => c.name === name);\n if (has(\"avatar\")) db.exec(\"ALTER TABLE users DROP COLUMN avatar\");\n if (has(\"display_name\")) db.exec(\"ALTER TABLE users DROP COLUMN display_name\");\n },\n },\n {\n version: 6,\n name: \"company-mode-org-caches\",\n // Additive: seven new tables for company mode (organizations of Agents), no change to any\n // existing table. Every row is either rebuildable from the organization's files (desks.toml,\n // the tickets' Sessions headers, the calendar files, usage records) or a user's own read\n // cursor; a predecessor build never touches them.\n swapSafe: true,\n up(db) {\n db.exec(`\n CREATE TABLE IF NOT EXISTS org_sessions ( -- DERIVED CACHE (company mode): desk sessions, rebuilt from each organization's desks.toml (current + previous); trigger_hop is chat-chain accounting and reads 0 after a rebuild\n session_id TEXT PRIMARY KEY,\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n current INTEGER NOT NULL DEFAULT 1,\n trigger_hop INTEGER NOT NULL DEFAULT 0\n );\n CREATE INDEX IF NOT EXISTS idx_org_sessions_org ON org_sessions(project_id, org_id);\n CREATE TABLE IF NOT EXISTS org_ticket_sessions ( -- DERIVED CACHE (company mode): ticket <-> contributing session, rebuilt from each ticket's Sessions header\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n ticket_id TEXT NOT NULL,\n session_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n trigger_hop INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (project_id, org_id, ticket_id, session_id)\n );\n CREATE INDEX IF NOT EXISTS idx_org_ticket_sessions_session ON org_ticket_sessions(session_id);\n CREATE TABLE IF NOT EXISTS org_calendar_state ( -- calendar run state (company mode; the files are declarative intent), same rules as schedule_state\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n name TEXT NOT NULL,\n start_at_ms INTEGER NOT NULL,\n def_hash TEXT NOT NULL,\n last_slot_ms INTEGER,\n last_fired_at TEXT,\n fired_once INTEGER NOT NULL DEFAULT 0,\n missed INTEGER NOT NULL DEFAULT 0,\n invalid_reason TEXT,\n last_outcome TEXT,\n PRIMARY KEY (project_id, org_id, agent_id, name)\n );\n CREATE TABLE IF NOT EXISTS org_ticket_state ( -- DERIVED CACHE (company mode): the last (status, owner, blocked) seen per ticket, so a change is notified once; rebuilt silently from the ticket files\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n ticket_id TEXT NOT NULL,\n status TEXT NOT NULL,\n owner TEXT NOT NULL DEFAULT '',\n blocked TEXT NOT NULL DEFAULT '',\n blocked_by TEXT NOT NULL DEFAULT '',\n PRIMARY KEY (project_id, org_id, ticket_id)\n );\n CREATE TABLE IF NOT EXISTS org_chat_state ( -- DERIVED CACHE (company mode): tail-scan byte cursor per chat day file\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n date TEXT NOT NULL,\n offset_bytes INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (project_id, org_id, date)\n );\n CREATE TABLE IF NOT EXISTS org_chat_reads ( -- user data (company mode): each user's read cursor in an organization's chat\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n user_id TEXT NOT NULL,\n last_read_id TEXT NOT NULL,\n PRIMARY KEY (project_id, org_id, user_id)\n );\n CREATE TABLE IF NOT EXISTS org_budget_state ( -- DERIVED CACHE (company mode): warn / pause marks per employee and period, recomputed from usage and the chart's budgets\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n period TEXT NOT NULL,\n warned_at TEXT,\n paused_at TEXT,\n PRIMARY KEY (project_id, org_id, agent_id, period)\n );\n `);\n },\n // Drops the seven tables. LOSES: chat read cursors (each user's \"read up to here\" marks) and\n // the run marks that stop a calendar slot, a ticket change or a budget alert from firing\n // twice — a build with this migration re-registers everything from the files, without\n // backfilling missed slots, and users see every chat message as unread once.\n down(db) {\n db.exec(`\n DROP INDEX IF EXISTS idx_org_ticket_sessions_session;\n DROP INDEX IF EXISTS idx_org_sessions_org;\n DROP TABLE IF EXISTS org_budget_state;\n DROP TABLE IF EXISTS org_chat_reads;\n DROP TABLE IF EXISTS org_chat_state;\n DROP TABLE IF EXISTS org_ticket_state;\n DROP TABLE IF EXISTS org_calendar_state;\n DROP TABLE IF EXISTS org_ticket_sessions;\n DROP TABLE IF EXISTS org_sessions;\n `);\n },\n },\n {\n version: 7,\n name: \"company-mode-channels\",\n // The organization's single group chat became channels: a message lives in\n // `channels/<channel_id>/<date>.jsonl`, so the tail-scan cursor and each user's read\n // cursor are per channel. `org_chat_state` / `org_chat_reads` are dropped for\n // `org_channel_state` / `org_channel_reads`: the tables are renamed and the channel\n // belongs in the primary key, neither of which SQLite does in place. Nothing is carried\n // over: company mode is unreleased, and every row was either rebuildable from the files\n // (the scan cursor) or one pass of \"everything looks unread\" (the read cursor). A\n // predecessor build reads neither table's shape, only its own writes, so this is\n // swap-safe.\n swapSafe: true,\n up(db) {\n db.exec(`\n DROP TABLE IF EXISTS org_chat_state;\n DROP TABLE IF EXISTS org_chat_reads;\n CREATE TABLE IF NOT EXISTS org_channel_state ( -- DERIVED CACHE (company mode): tail-scan byte cursor per channel and day file\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n channel_id TEXT NOT NULL,\n date TEXT NOT NULL,\n offset_bytes INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (project_id, org_id, channel_id, date)\n );\n CREATE TABLE IF NOT EXISTS org_channel_reads ( -- user data (company mode): each user's read cursor in one channel\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n channel_id TEXT NOT NULL,\n user_id TEXT NOT NULL,\n last_read_id TEXT NOT NULL,\n PRIMARY KEY (project_id, org_id, channel_id, user_id)\n );\n `);\n },\n // Recreates the two tables under their old names, exactly as migration 6 declared them —\n // EMPTY. LOSES every scan cursor (re-derived by the next pass, which republishes the\n // messages it re-reads) and every read cursor (users see the recent days as unread once).\n down(db) {\n db.exec(`\n DROP TABLE IF EXISTS org_channel_state;\n DROP TABLE IF EXISTS org_channel_reads;\n CREATE TABLE IF NOT EXISTS org_chat_state ( -- DERIVED CACHE (company mode): tail-scan byte cursor per chat day file\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n date TEXT NOT NULL,\n offset_bytes INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (project_id, org_id, date)\n );\n CREATE TABLE IF NOT EXISTS org_chat_reads ( -- user data (company mode): each user's read cursor in an organization's chat\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n user_id TEXT NOT NULL,\n last_read_id TEXT NOT NULL,\n PRIMARY KEY (project_id, org_id, user_id)\n );\n `);\n },\n },\n {\n version: 8,\n name: \"company-mode-desk-notices\",\n // Additive: one new table and its index. A ticket change no longer starts a work run at\n // the owner's desk; it is queued here and delivered inside the body of that employee's\n // next calendar sweep. A predecessor build never reads the table, so a rollback survives\n // it — with whatever rows are in it left undelivered.\n swapSafe: true,\n up(db) {\n db.exec(`\n CREATE TABLE IF NOT EXISTS org_desk_notices ( -- DERIVED CACHE (company mode): ticket changes waiting for an employee's next calendar sweep; dropping it loses only the digests not delivered yet\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n ticket_id TEXT NOT NULL,\n change TEXT NOT NULL,\n at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_org_desk_notices_agent ON org_desk_notices(project_id, org_id, agent_id);\n `);\n },\n // LOSES every queued notice: the ticket changes an employee has not been told about yet.\n // The change itself is in the ticket file and its history either way; what\n // goes is the \"Since your last sweep\" line that would have named it.\n down(db) {\n db.exec(`\n DROP INDEX IF EXISTS idx_org_desk_notices_agent;\n DROP TABLE IF EXISTS org_desk_notices;\n `);\n },\n },\n {\n version: 9,\n name: \"model-promotions\",\n // Additive: one new table, nothing existing touched. A predecessor build never reads it\n // and prices every row at the number in its Project file, so a rollback survives it.\n swapSafe: true,\n up(db) {\n // Frozen copy of the DDL as of the model-promotions feature; do not re-derive from\n // schema.ts. IF NOT EXISTS because the declarative track may already have created it\n // (ADOPTION).\n db.exec(`\n CREATE TABLE IF NOT EXISTS model_promotions ( -- NOT a cache rebuildable from files: the only record of a Project row's running promotion (.project_config.toml keeps the list price), written by preset seeding at Project creation, \"sync presets\" and Penguin Go authorization / sync, and read by cost; lost rows price usage at list until the next sync writes them back\n project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,\n provider TEXT NOT NULL,\n model_id TEXT NOT NULL,\n discount REAL NOT NULL CHECK (discount > 0 AND discount < 1),\n updated_at TEXT NOT NULL,\n PRIMARY KEY (project_id, provider, model_id)\n );\n `);\n },\n // LOSES every stored promotion: no file holds a copy of the fractions, so usage is priced\n // at the Project files' list prices until the next \"sync presets\" or Penguin Go sync\n // writes them back.\n down(db) {\n db.exec(\"DROP TABLE IF EXISTS model_promotions\");\n },\n },\n {\n version: 10,\n name: \"model-provider-auth-tokens\",\n // Additive: one new table, nothing existing touched. A predecessor build never reads it;\n // the access token already written into .project_config.toml keeps working until it\n // expires, so rollback only loses silent refresh state.\n // KEEP until every supported upgrade starts from schema 10 or newer. The release that\n // raises the minimum database baseline past 9 owns removing this migration block and its\n // version-9 fixture; the table itself remains while provider token refresh uses it.\n swapSafe: true,\n up(db) {\n // Frozen copy of the DDL as of the provider-auth-token feature; do not re-derive from\n // schema.ts. IF NOT EXISTS because the declarative track may already have created it\n // (ADOPTION).\n db.exec(`\n CREATE TABLE IF NOT EXISTS model_provider_auth_tokens ( -- Server-side OAuth refresh metadata for provider groups. The current request token remains in .project_config.toml as api_key; this table holds only the refresh material that must never be returned to the frontend or written into Project files.\n project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,\n provider TEXT NOT NULL,\n refresh_token TEXT NOT NULL,\n access_token_expires_at TEXT,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (project_id, provider)\n );\n `);\n },\n // LOSES every stored refresh token and access-token expiry. Existing access tokens in\n // Project files remain until they expire; users re-authorize to restore silent refresh.\n down(db) {\n db.exec(\"DROP TABLE IF EXISTS model_provider_auth_tokens\");\n },\n },\n {\n version: 11,\n name: \"sessions-sandbox\",\n // The Session's own sandbox policy (JSON), snapshotted from the server's settings when\n // the Session is created, so a later settings change leaves running Sessions alone.\n // NULL = a row from before this column: it takes the settings in force at its next\n // command and keeps them from then on. Swap-safe: a pushed platform boots against the\n // runtime's already-open database, so the column has to arrive by a migration.\n swapSafe: true,\n up(db) {\n ensureColumn(db, \"sessions\", \"sandbox\", \"TEXT\");\n },\n // Not a DROP: schema.ts declares the column, and dropping it would put every Session\n // back under whatever the settings say.\n down() {},\n },\n {\n version: 12,\n name: \"machines-columns\",\n // A machines table can predate migration 4 — a data root that ran the machines line\n // before it was released kept forwards, not sessions — and that migration's IF NOT\n // EXISTS adopted it whatever its columns were, so the first connect failed on the row's\n // insert. Adds what is missing, nullable; a platform rolled back to 4 declared these\n // columns itself, so there is nothing for it to mind.\n swapSafe: true,\n up(db) {\n ensureColumn(db, \"machines\", \"session_pid\", \"INTEGER\");\n ensureColumn(db, \"machines\", \"platform\", \"TEXT\");\n },\n // Nothing to undo: what this added, 4 already declares, and a column it found in place\n // was never this migration's to take away.\n down() {},\n },\n {\n version: 13,\n name: \"browser-extensions\",\n // Additive: one new table and its index. The Chrome backend's pairings — one row per\n // PenguinHarness Browser extension a user paired, its token stored hashed. A predecessor\n // build never reads the table, so a rollback survives it; the paired extensions then simply\n // fail to connect until a build that knows them is back.\n swapSafe: true,\n up(db) {\n // Frozen copy of the DDL as of the system-Chrome feature; do not re-derive from schema.ts.\n // IF NOT EXISTS because the declarative track may already have created it (ADOPTION).\n db.exec(`\n CREATE TABLE IF NOT EXISTS browser_extensions ( -- one row per Chrome paired to a user (builtin-browser/extension-pairing.ts): the PenguinHarness Browser extension's long-lived credential, stored only hashed; NOT rebuildable — a lost row means pairing that Chrome again\n extension_id TEXT PRIMARY KEY,\n user_id TEXT NOT NULL REFERENCES users(user_id) ON DELETE CASCADE,\n token_hash TEXT NOT NULL UNIQUE,\n name TEXT NOT NULL,\n version TEXT NOT NULL,\n created_at TEXT NOT NULL,\n last_seen_at TEXT,\n revoked_at TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_browser_extensions_user ON browser_extensions(user_id);\n `);\n },\n // LOSES every pairing: each user's Chrome has to be paired again (a new code from the\n // Browser panel) before agents can drive it.\n down(db) {\n db.exec(`\n DROP INDEX IF EXISTS idx_browser_extensions_user;\n DROP TABLE IF EXISTS browser_extensions;\n `);\n },\n },\n {\n version: 14,\n name: \"agent-api\",\n // Additive: two new tables and an index. The Agent API's per-Agent settings (the switch,\n // keyless access, the approval mode API Sessions are created with) and its keys, stored\n // hashed. A predecessor build never reads them and serves no /api/amsp route, so a\n // rollback survives it: callers get 404 until a build that knows the tables is back.\n swapSafe: true,\n up(db) {\n // Frozen copy of the DDL as of the Agent API feature; do not re-derive from schema.ts.\n // IF NOT EXISTS because the declarative track may already have created them (ADOPTION).\n db.exec(`\n CREATE TABLE IF NOT EXISTS agent_api ( -- per-Agent public API settings (amsp/routes.ts); NOT rebuildable from files\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n enabled INTEGER NOT NULL DEFAULT 0,\n open INTEGER NOT NULL DEFAULT 0,\n approval_mode TEXT NOT NULL DEFAULT 'allow-all',\n updated_at TEXT NOT NULL,\n PRIMARY KEY (project_id, agent_id)\n );\n CREATE TABLE IF NOT EXISTS agent_api_keys ( -- one row per key the API tab or the CLI minted; the caller alone holds the key\n key_id TEXT PRIMARY KEY,\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n token_hash TEXT NOT NULL UNIQUE,\n prefix TEXT NOT NULL,\n name TEXT NOT NULL,\n created_by TEXT NOT NULL REFERENCES users(user_id),\n created_at TEXT NOT NULL,\n last_used_at TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_agent_api_keys_agent ON agent_api_keys(project_id, agent_id);\n `);\n },\n // LOSES every Agent's API settings and every key: each exposed Agent reads as disabled\n // again (404 to its callers), and every caller needs a newly created key once it is back\n // on — no file holds a copy of either.\n down(db) {\n db.exec(`\n DROP INDEX IF EXISTS idx_agent_api_keys_agent;\n DROP TABLE IF EXISTS agent_api_keys;\n DROP TABLE IF EXISTS agent_api;\n `);\n },\n },\n {\n version: 15,\n name: \"messaging-conversations\",\n // Additive: one new table. The WeChat connector's per-(bot, user) delivery state — the\n // context token every send must echo, how many sends it has funded, and replies held for\n // the user's next message. A predecessor build never reads it and keeps its tokens in\n // memory as it always did, so a rollback survives it.\n swapSafe: true,\n up(db) {\n // Frozen copy of the DDL as of the WeChat delivery fix; do not re-derive from schema.ts.\n // IF NOT EXISTS because the declarative track may already have created it (ADOPTION).\n db.exec(`\n CREATE TABLE IF NOT EXISTS messaging_conversations ( -- per-(bot, chat) delivery state a connector must keep across reconnects and restarts (WeChat: the context token, its send count, held replies); deleted once no messaging_bindings row references (channel, account_id) — see MessagingBindingsRepo\n channel TEXT NOT NULL,\n account_id TEXT NOT NULL,\n chat_id TEXT NOT NULL,\n state_json TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (channel, account_id, chat_id)\n );\n `);\n },\n // LOSES every stored context token and every held reply: replies sent before each user's\n // next message are refused again, and what was held never arrives.\n down(db) {\n db.exec(\"DROP TABLE IF EXISTS messaging_conversations\");\n },\n },\n {\n version: 16,\n name: \"sessions-kept-at\",\n // The \"keep in sidebar\" mark: written when the user unarchives a Session, cleared when they\n // archive it. The listing rule files a background Session (api / schedule / cli) away unless\n // it carries the mark, so existing rows are listed by the rule as they stand and nothing is\n // rewritten. Swap-safe: a pushed platform boots against the runtime's already-open database,\n // so the column has to arrive by a migration.\n swapSafe: true,\n up(db) {\n ensureColumn(db, \"sessions\", \"kept_at\", \"TEXT\");\n },\n // Not a DROP: schema.ts declares the column, and dropping it would file every kept\n // background Session away again.\n down() {},\n },\n];\n\n/** The highest version this build knows how to reach. */\nexport const LATEST_VERSION: number = MIGRATIONS.reduce((n, m) => Math.max(n, m.version), 0);\n\n/** How far this database has been migrated. Unstamped (pre-migrations) databases read 0. */\nexport function schemaVersion(db: DatabaseSync): number {\n const row = db.prepare(\"PRAGMA user_version\").get() as { user_version: number } | undefined;\n return row?.user_version ?? 0;\n}\n\nexport class IrreversibleMigrationError extends Error {\n constructor(readonly migration: Migration) {\n super(\n `migration ${migration.version} (${migration.name}) declares no down and cannot be rolled back. ` +\n `Restore the database from a backup taken before it was applied.`,\n );\n this.name = \"IrreversibleMigrationError\";\n }\n}\n\nexport class RestartRequiredError extends Error {\n constructor(readonly migration: Migration) {\n super(\n `migration ${migration.version} (${migration.name}) is restart-only and cannot be applied ` +\n `while a pushed platform boots: it is not safe to leave behind if this boot is rolled back. ` +\n `Restart the runtime on a build that carries it, then push again.`,\n );\n this.name = \"RestartRequiredError\";\n }\n}\n\n/**\n * Applies every migration this database has not reached yet, in order.\n *\n * Each migration and its version stamp commit together, so an interrupted run leaves the\n * database at the last version that fully applied — never half-migrated. Already-current\n * databases do no work and touch nothing.\n *\n * `swapPath` marks the caller as a booting pushed platform: the first pending migration\n * that is not `swapSafe` throws RestartRequiredError BEFORE anything is applied, so the\n * push is refused whole rather than partially landed.\n */\nexport function migrate(\n db: DatabaseSync,\n { swapPath = false }: { swapPath?: boolean } = {},\n): { from: number; to: number; applied: readonly string[] } {\n const from = schemaVersion(db);\n const pending = [...MIGRATIONS]\n .sort((a, b) => a.version - b.version)\n .filter((m) => m.version > from);\n if (swapPath) {\n const blocked = pending.find((m) => !m.swapSafe);\n if (blocked) throw new RestartRequiredError(blocked);\n }\n const applied: string[] = [];\n for (const m of pending) {\n db.exec(\"BEGIN\");\n try {\n m.up(db);\n // PRAGMA takes no bound parameter; the value is this file's own integer literal.\n db.exec(`PRAGMA user_version = ${m.version}`);\n db.exec(\"COMMIT\");\n } catch (err) {\n db.exec(\"ROLLBACK\");\n throw new Error(`migration ${m.version} (${m.name}) failed: ${String(err)}`, { cause: err });\n }\n applied.push(m.name);\n }\n return { from, to: schemaVersion(db), applied };\n}\n\n/**\n * Reverts the database DOWN to `targetVersion`, newest migration first.\n *\n * An operator's tool, and a destructive one — see each migration's `down` for what its rows\n * were. Deliberately not reachable from the swap path: a failed platform boot reverts the\n * PLATFORM, never the schema (module doc).\n *\n * Refused whole, before anything runs, if any migration in range declares no `down`: a\n * partial rollback would leave the database at a version whose meaning nobody wrote down.\n * Each `down` commits with its version stamp, so an interrupted run stops at a real version.\n */\nexport function rollbackTo(\n db: DatabaseSync,\n targetVersion: number,\n): { from: number; to: number; reverted: readonly string[] } {\n const from = schemaVersion(db);\n if (targetVersion < 0) throw new Error(`target version ${targetVersion} is negative`);\n if (targetVersion > from) {\n throw new Error(`database is at version ${from}, which is already below ${targetVersion}`);\n }\n const toRevert = [...MIGRATIONS]\n .filter((m) => m.version > targetVersion && m.version <= from)\n .sort((a, b) => b.version - a.version);\n const blocked = toRevert.find((m) => m.down === null);\n if (blocked) throw new IrreversibleMigrationError(blocked);\n\n const reverted: string[] = [];\n for (const m of toRevert) {\n db.exec(\"BEGIN\");\n try {\n m.down!(db);\n // Versions are contiguous, so the predecessor of `m` is exactly m.version - 1.\n db.exec(`PRAGMA user_version = ${m.version - 1}`);\n db.exec(\"COMMIT\");\n } catch (err) {\n db.exec(\"ROLLBACK\");\n throw new Error(`rollback of migration ${m.version} (${m.name}) failed: ${String(err)}`, {\n cause: err,\n });\n }\n reverted.push(m.name);\n }\n return { from, to: schemaVersion(db), reverted };\n}\n","/**\n * SQLite table-creation SQL.\n *\n * SQLite stores only indexes and aggregates: users / login sessions / Project authorization /\n * Agent & Session indexes / usage summaries / error records / UI preferences. Agent State,\n * Trace, and Workspace still follow the local directory-based storage rules.\n * Product not yet released: no migration branches — everything is CREATE IF NOT EXISTS, formed\n * once. The one exception: columns added to an existing table after release of a web.db are\n * ALTERed in by the idempotent per-column guard in database.ts (ensureColumn), since CREATE\n * TABLE IF NOT EXISTS never touches an existing table. A *reshaped* index follows the same\n * rule under a new name, with the superseded one dropped on open (idx_usage_session →\n * idx_usage_session_ts): CREATE INDEX IF NOT EXISTS never rebuilds an existing index either.\n */\n\nexport const MODEL_PROMOTIONS_SQL = `\nCREATE TABLE IF NOT EXISTS model_promotions ( -- NOT a cache rebuildable from files: the only record of a Project row's running promotion (.project_config.toml keeps the list price), written by preset seeding at Project creation, \"sync presets\" and Penguin Go authorization / sync, and read by cost; lost rows price usage at list until the next sync writes them back\n project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,\n provider TEXT NOT NULL,\n model_id TEXT NOT NULL,\n discount REAL NOT NULL CHECK (discount > 0 AND discount < 1), -- fraction off the row's list price: billed = list × (1 − discount)\n updated_at TEXT NOT NULL,\n PRIMARY KEY (project_id, provider, model_id)\n);`;\n\nexport const MODEL_PROVIDER_AUTH_TOKENS_SQL = `\nCREATE TABLE IF NOT EXISTS model_provider_auth_tokens ( -- Server-side OAuth refresh metadata for provider groups. The current request token remains in .project_config.toml as api_key; this table holds only the refresh material that must never be returned to the frontend or written into Project files.\n project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,\n provider TEXT NOT NULL,\n refresh_token TEXT NOT NULL,\n access_token_expires_at TEXT,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (project_id, provider)\n);`;\n\nexport const SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS users (\n user_id TEXT PRIMARY KEY, -- semantic id doubles as login name: ^[a-z][a-z0-9_-]{1,31}$\n password_hash TEXT NOT NULL, -- scrypt$N$r$p$salt$hash(base64)\n is_admin INTEGER NOT NULL DEFAULT 0, -- 1 for the built-in admin (seeded at startup)\n password_is_initial INTEGER NOT NULL DEFAULT 0, -- 1=initial password (seeded/admin-set); cleared once the user changes it\n display_name TEXT, -- nickname shown in place of user_id (1-32 characters); NULL = never set, surfaces show the id\n avatar TEXT, -- avatar as a data URL (image/png|jpeg|webp, <= 131072 characters); NULL = never set, surfaces draw the letter placeholder\n created_at TEXT NOT NULL\n);\n-- Server-side sessions backing the HttpOnly cookie: the cookie carries a 32-byte random\n-- token, the row stores only its sha256. A session outlives a restart (it is on disk), which\n-- is why the model is a row and not a signed statement.\nCREATE TABLE IF NOT EXISTS auth_sessions (\n token_hash TEXT PRIMARY KEY, -- sha256(token) hex; the cookie stores only the raw token\n user_id TEXT NOT NULL REFERENCES users(user_id) ON DELETE CASCADE,\n created_at TEXT NOT NULL,\n expires_at TEXT NOT NULL, -- 30-day sliding renewal, topped up in place when <29 days remain\n via TEXT -- 'password'|'desktop'|'setup'|'cli'; NULL = legacy (password)\n);\n-- deleteExpired runs on every login and mint, deleteByUser on every admin reset; without\n-- these both scan the whole table.\nCREATE INDEX IF NOT EXISTS idx_auth_sessions_expires ON auth_sessions(expires_at);\nCREATE INDEX IF NOT EXISTS idx_auth_sessions_user ON auth_sessions(user_id);\n\nCREATE TABLE IF NOT EXISTS projects (\n project_id TEXT PRIMARY KEY, -- directory name doubles as id; display name lives in project_config.toml\n owner_user_id TEXT NOT NULL REFERENCES users(user_id),\n created_at TEXT NOT NULL\n);\nCREATE TABLE IF NOT EXISTS project_members ( -- member grants only; owners are not stored here\n project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,\n user_id TEXT NOT NULL REFERENCES users(user_id) ON DELETE CASCADE,\n created_at TEXT NOT NULL,\n PRIMARY KEY (project_id, user_id)\n);\n${MODEL_PROMOTIONS_SQL}\n${MODEL_PROVIDER_AUTH_TOKENS_SQL}\nCREATE TABLE IF NOT EXISTS agents ( -- index only; name/description live in system_config.yaml\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n created_at TEXT NOT NULL,\n PRIMARY KEY (project_id, agent_id)\n);\nCREATE TABLE IF NOT EXISTS sessions (\n session_id TEXT PRIMARY KEY,\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n provider TEXT NOT NULL, -- provider group of the session's CURRENT model (paired with model_id as a model reference; moves with each in-session switch)\n model_id TEXT NOT NULL, -- upstream model id of the current model (sent to MMSP as-is; never concatenate <provider>/<id>)\n workspace TEXT NOT NULL,\n approval_mode TEXT NOT NULL DEFAULT 'allow-all', -- allow-all|deny-all|read-only|always-ask\n thinking_level TEXT, -- level pinned for THIS session (none|low|medium|high|xhigh|max); NULL=not pinned, runs follow the Agent config\n title TEXT, -- auto-generated by the model after the first exchange; NULL=not yet (frontend shows \"New chat\")\n archived_at TEXT, -- the user archived it (ISO time); NULL = not archived by hand (the listing rule may still file it away)\n kept_at TEXT, -- \"keep in sidebar\": set when the user unarchives, cleared when they archive; NULL = the listing rule decides (a background source is archived, a user Session is active). Never written by a run.\n client TEXT, -- creating client: 'web' (created via the Web App) | 'cli' (adopted from a CLI Trace) | 'org' (company mode) | 'api' (an Agent API run); NULL = legacy row, treated as web\n has_trace INTEGER NOT NULL DEFAULT 0, -- cache: a Trace record exists (set at task start / adoption / subagent registration; lazily backfilled by list hydration)\n fork_count INTEGER NOT NULL DEFAULT 0, -- monotonically allocated child-fork number for this source Session; never decremented when a fork is deleted\n sandbox TEXT, -- the Session's sandbox policy snapshot (JSON SandboxSettings); NULL = legacy row, snapshotted at its next command\n last_active_at TEXT, -- last activity this server drove for the session (ISO; stamped once when a run starts and once when it ends, initialized to created_at); monotonic, never moves backwards; NULL only before openDatabase's one-time backfill\n created_at TEXT NOT NULL\n); -- the Session's SOURCE (user/api/schedule/subagent/cli/company) is NOT stored: session_meta in the Trace is the single source of truth (see runtime/session-sources.ts); \"client\" is a different, DB-only axis (who created the row), read for the source only where the Trace records none ('org' → company)\nCREATE INDEX IF NOT EXISTS idx_sessions_agent_created ON sessions(project_id, agent_id, created_at DESC);\nCREATE TABLE IF NOT EXISTS usage_records (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n ts TEXT NOT NULL,\n date TEXT NOT NULL, -- local date yyyy-mm-dd (aggregation key; same convention as Trace date directories)\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n session_id TEXT NOT NULL, -- top-level Session (child-session usage counts toward its main Session)\n origin_session_id TEXT, -- immediate source child Session (last of the origin chain); NULL=main session\n provider TEXT NOT NULL, -- provider group: paired with model_id as the attribution key; always GROUP BY provider, model_id\n model_id TEXT NOT NULL, -- upstream model id (paired with provider; same model_id across providers aggregates separately)\n cache_read INTEGER NOT NULL,\n cache_write INTEGER NOT NULL,\n output INTEGER NOT NULL,\n total INTEGER NOT NULL, -- from token_usage.request (one row per Request)\n status TEXT NOT NULL DEFAULT 'completed' -- request outcome: completed=success (with tokens); others=failure (0 tokens, for success rate)\n); -- cost is not stored: computed at query time from current pricing\nCREATE INDEX IF NOT EXISTS idx_usage_project_date ON usage_records(project_id, date);\nCREATE INDEX IF NOT EXISTS idx_usage_session_ts ON usage_records(session_id, ts); -- (session_id) alone was idx_usage_session (dropped on open): ts makes the last_active_at backfill's MAX(ts) a covering index scan instead of a random row lookup per usage record\nCREATE TABLE IF NOT EXISTS error_records ( -- server-side error capture (the Costs page's \"Errors\" tab)\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n ts TEXT NOT NULL,\n date TEXT NOT NULL, -- local date yyyy-mm-dd (same convention as usage_records)\n project_id TEXT, -- nullable: sign-in/registration and process-level errors have no Project context\n agent_id TEXT,\n session_id TEXT,\n source TEXT NOT NULL, -- http | session | usage | title | subagent | process | llm | environment | compaction | schedule | messaging | organization | id_suggest | plugin\n kind TEXT NOT NULL, -- expected (HttpError, business 4xx) | unexpected (500/runtime)\n code TEXT NOT NULL, -- HttpError.code / internal / session_run_failed / ...\n status INTEGER, -- HTTP status code; NULL for non-HTTP sources\n message TEXT NOT NULL -- truncated to 500 chars (no stack stored: stacks go to logs only)\n);\nCREATE INDEX IF NOT EXISTS idx_error_project_date ON error_records(project_id, date);\nCREATE TABLE IF NOT EXISTS schedule_state ( -- schedule runtime state (files are declarative intent; the system never writes back)\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n name TEXT NOT NULL, -- file name (without .toml) doubles as the identifier\n creator_user_id TEXT, -- creator (recorded on API create; hand-edited file reconciliation falls back to the Project owner)\n start_at_ms INTEGER NOT NULL, -- defines identity: a start_at change counts as a new task instance, resetting fire state\n def_hash TEXT NOT NULL, -- file content fingerprint: any change clears the invalid flag (the file takes effect again after edits)\n last_slot_ms INTEGER, -- latest due slot already consumed (advances on fire or skip; no re-fire across restarts)\n last_fired_at TEXT, -- last actual fire time (for display)\n fired_once INTEGER NOT NULL DEFAULT 0, -- one-shot task has fired\n missed INTEGER NOT NULL DEFAULT 0, -- one-shot task was missed (flagged by startup/registration reconciliation; not backfilled)\n invalid_reason TEXT, -- invalidation reason (e.g. the bound Session was deleted); NULL=healthy\n PRIMARY KEY (project_id, agent_id, name)\n);\nCREATE TABLE IF NOT EXISTS messaging_bindings ( -- Session ↔ messaging-channel bot bindings (runtime/messaging/ holds the long connections)\n session_id TEXT NOT NULL, -- a Session keeps at most one saved config PER channel (composite PK below); at most ONE of them is enabled at a time (route-enforced, 409 another_channel_enabled), and enabling is what binds the account to this Session\n channel TEXT NOT NULL, -- messaging channel discriminator ('feishu' | 'telegram' | 'qq' | 'wechat')\n account_id TEXT NOT NULL, -- channel-scoped bot/app identity (feishu: app_id; telegram: the bot token's numeric id; qq: the bot's App ID; wechat: the scanned bot id); NOT unique — any number of Sessions may keep the same account saved side by side, each with its own config and last-chat memory; only ENABLING is exclusive (route-enforced, 409 account_enabled_elsewhere: one account has one event stream, two live connections on it would race)\n config_json TEXT NOT NULL, -- channel-specific credentials/config JSON (feishu: appId/appSecret/baseDomain; telegram: botToken; qq: appId/appSecret; wechat: botId/botToken/baseUrl/userId); secrets plaintext at rest (same trade-off as the proxy address in server_settings), masked at every API surface; a cleared secret is stored as \"\" (the row and its account identity stay)\n enabled INTEGER NOT NULL DEFAULT 0, -- INTENT state (the connection's runtime status stays in memory): new bindings start disabled — saving credentials never opens a connection, the explicit state toggle does\n line_per_message INTEGER NOT NULL DEFAULT 0, -- delivery preference: 1 = every non-blank line of a relayed assistant reply is sent as its own message (a reply written as spoken lines arrives as spoken lines), 0 = one message per reply. Channel-agnostic, so it lives here rather than in config_json, which each connector owns\n final_reply_only INTEGER NOT NULL DEFAULT 0, -- delivery preference: 1 = a run's intermediate assistant messages are held and only its LAST completed one is sent, at the run's end, 0 = every completed assistant message mirrors the moment it completes. Channel-agnostic like the column above and independent of it: with both set, that one final text is the one split per line\n render_markdown INTEGER NOT NULL DEFAULT 1, -- delivery preference: 1 = a relayed reply's Markdown is rendered in the channel's own markup (Telegram HTML, a Feishu card, QQ markdown, the subset WeChat itself reads), 0 = the reply's characters are sent as written. DEFAULT 1 because the model writes Markdown and showing it raw was the defect; the per-channel subsets and the plain-text fallback live in the connectors\n last_chat_id TEXT, -- most recent inbound chat (NULL until the bot is messaged once; replies and test messages target it); CONNECTOR-OPAQUE, not necessarily a bare chat id — telegram appends the forum topic (see telegram-connector.ts chatRefOf), so only that channel's connector may interpret it\n last_chat_is_direct INTEGER NOT NULL DEFAULT 1, -- 1 = direct chat (reply by chat id), 0 = group chat (prefer reply-to-message)\n last_inbound_message_id TEXT, -- channel id of the most recently PROCESSED inbound message (NULL until one arrives); the durable half of the bridge's redelivery guard, so a channel replaying an event this server already turned into a Task after a restart does not run it twice\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (session_id, channel)\n);\nCREATE INDEX IF NOT EXISTS idx_messaging_by_account ON messaging_bindings(channel, account_id); -- serves the enable guard's by-account lookup; deliberately NOT unique, unlike its predecessor idx_messaging_account (dropped on open) which made an account exclusive to one Session forever\nCREATE TABLE IF NOT EXISTS messaging_conversations ( -- per-(bot, chat) delivery state a connector must keep across reconnects and restarts (WeChat: the context token, its send count, held replies); deleted once no messaging_bindings row references (channel, account_id) — see MessagingBindingsRepo\n channel TEXT NOT NULL, -- messaging channel discriminator (only 'wechat' writes rows today)\n account_id TEXT NOT NULL, -- the bot, as messaging_bindings.account_id names it\n chat_id TEXT NOT NULL, -- the connector's own chat id (wechat: the user's ilink_user_id)\n state_json TEXT NOT NULL, -- connector-owned JSON (wechat: {contextToken, tokenAt, spent, held, heldSince}); the token is a conversation handle at rest, same trade-off as config_json's credentials\n updated_at TEXT NOT NULL,\n PRIMARY KEY (channel, account_id, chat_id)\n);\nCREATE TABLE IF NOT EXISTS ui_prefs (\n user_id TEXT PRIMARY KEY REFERENCES users(user_id) ON DELETE CASCADE,\n prefs_json TEXT NOT NULL -- {theme?, lastProjectId?, ...} free-form JSON\n);\nCREATE TABLE IF NOT EXISTS browser_extensions ( -- one row per Chrome paired to a user (builtin-browser/extension-pairing.ts): the PenguinHarness Browser extension's long-lived credential, stored only hashed; NOT rebuildable — a lost row means pairing that Chrome again\n extension_id TEXT PRIMARY KEY, -- random id shown in the Web App's list\n user_id TEXT NOT NULL REFERENCES users(user_id) ON DELETE CASCADE,\n token_hash TEXT NOT NULL UNIQUE, -- sha256(token) hex; the extension alone holds the token\n name TEXT NOT NULL, -- how the extension names this Chrome (\"Chrome 130 on macOS\")\n version TEXT NOT NULL, -- the extension's version, as of its last hello\n created_at TEXT NOT NULL,\n last_seen_at TEXT, -- last connect or disconnect; NULL = never connected\n revoked_at TEXT -- set by Revoke; a revoked token's socket is closed 4003\n);\nCREATE INDEX IF NOT EXISTS idx_browser_extensions_user ON browser_extensions(user_id);\nCREATE TABLE IF NOT EXISTS agent_api ( -- per-Agent public API settings (amsp/routes.ts); NOT rebuildable from files\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n enabled INTEGER NOT NULL DEFAULT 0, -- the API tab's switch; off = every /api/amsp request for it is 404 agent_not_found\n open INTEGER NOT NULL DEFAULT 0, -- keyless access: a request without Authorization is accepted; off = 401 unauthorized\n approval_mode TEXT NOT NULL DEFAULT 'allow-all', -- the approval mode an API Session is CREATED with (allow-all|deny-all|read-only|always-ask); copied onto sessions.approval_mode, never read per decision\n updated_at TEXT NOT NULL,\n PRIMARY KEY (project_id, agent_id)\n);\nCREATE TABLE IF NOT EXISTS agent_api_keys ( -- one row per key the API tab or the CLI minted; the caller alone holds the key\n key_id TEXT PRIMARY KEY, -- 16 base64url chars, shown in the list\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n token_hash TEXT NOT NULL UNIQUE, -- sha256(key) hex\n prefix TEXT NOT NULL, -- the key's first 16 characters (\"penguin_\" + 8), shown in the list\n name TEXT NOT NULL, -- 1-64 characters\n created_by TEXT NOT NULL REFERENCES users(user_id),\n created_at TEXT NOT NULL,\n last_used_at TEXT -- stamped once per run request that authenticated with it; NULL = never\n);\nCREATE INDEX IF NOT EXISTS idx_agent_api_keys_agent ON agent_api_keys(project_id, agent_id);\nCREATE TABLE IF NOT EXISTS server_settings ( -- admin-level server-global settings (GET/PUT /api/admin/settings)\n key TEXT PRIMARY KEY, -- setting name, e.g. 'proxy_for_app'\n value TEXT NOT NULL -- JSON-encoded value; an absent row means the setting's built-in default\n);\nCREATE TABLE IF NOT EXISTS machine ( -- this server's OWN identity, minted here and never assigned from outside (what 'penguin server status' reports)\n singleton INTEGER PRIMARY KEY CHECK (singleton = 1), -- exactly one row, enforced by the schema rather than by convention\n machine_id TEXT NOT NULL -- 16 base64url characters; what every stored reference to this machine points at\n);\nCREATE TABLE IF NOT EXISTS machines ( -- one row per machine this server installed on or reached (machines/service.ts)\n address TEXT PRIMARY KEY, -- 'ssh:<alias>'\n machine_id TEXT, -- that machine's own id, once heard\n version TEXT, -- what this server last installed there; NULL = never\n installed_at TEXT,\n session_pid INTEGER, -- the ssh session this server holds to it; what a successor App closes after a hot swap\n remote_port INTEGER, -- its server's port over there, as of the last connect\n platform TEXT -- linux | darwin | win32, as the install found it: the shell dialect the status probe speaks to it in\n);\nCREATE TABLE IF NOT EXISTS machine_project ( -- which machines a Project uses; no row = none yet. Follows the Project out, like project_members\n project_id TEXT PRIMARY KEY REFERENCES projects(project_id) ON DELETE CASCADE,\n addresses TEXT NOT NULL -- JSON array of 'ssh:<alias>'\n);\nCREATE TABLE IF NOT EXISTS trace_files ( -- DERIVED CACHE of the on-disk Trace tree (services/trace-index.ts): the directories stay the single source of truth, every row is rebuildable from disk, and a row is never authority for absence — consumers reconcile + retry on a miss, so a stale index costs one extra scan, never a false 404\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n session_id TEXT NOT NULL,\n file_index INTEGER NOT NULL, -- shard index NNN of <session_id>_NNN.jsonl (name/path are reconstructed from the row, never stored: the data root may move)\n date TEXT NOT NULL, -- date directory name (local yyyy-mm-dd)\n size_bytes INTEGER NOT NULL, -- last observed size (listings stat-refresh the returned page and write back; an actively-appended shard may lag in between)\n page_stats TEXT, -- cached message-window scan state at this shard's END (services/message-window.ts ShardPrefixRecord JSON); immutable shards only, NULL = not yet computed, nulled whenever size_bytes changes\n PRIMARY KEY (project_id, agent_id, session_id, file_index)\n);\nCREATE INDEX IF NOT EXISTS idx_trace_files_agent_date ON trace_files(project_id, agent_id, date);\nCREATE INDEX IF NOT EXISTS idx_trace_files_session ON trace_files(session_id);\nCREATE TABLE IF NOT EXISTS trace_sessions ( -- per-session facts read ONCE at registration from the earliest shard's head (same derived-cache rules as trace_files; listing needs zero head-reads)\n session_id TEXT PRIMARY KEY,\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n source TEXT, -- session_meta source as the head carried it: 'user' | 'api' | 'schedule' | 'subagent' | 'cli' | 'company'; NULL = the head records none (written before the source was required: read as 'company' for an 'org' row, else 'user' — readRecordedSource); 'benchmark' from older rows reads as 'cli' (normalizeSessionSource; meaningless while meta_read = 0)\n workspace TEXT NOT NULL DEFAULT '',\n title TEXT, -- first-prompt fallback title (sessions.title always wins when present)\n provider TEXT, -- model reference from session_meta: the model the Session was created on (CLI adoption reads it from here, and the runtime's own answer corrects the row at load; NULL = meta unreadable / legacy without provider)\n model_id TEXT,\n first_ts TEXT, -- first record's timestamp (adoption's createdAt fallback when the id embeds no time)\n meta_read INTEGER NOT NULL DEFAULT 0 -- 1 once the head parsed; 0 = facts unknown, retried by the next reconcile that touches the session\n);\nCREATE INDEX IF NOT EXISTS idx_trace_sessions_agent ON trace_sessions(project_id, agent_id);\nCREATE TABLE IF NOT EXISTS org_sessions ( -- DERIVED CACHE (company mode): desk sessions, rebuilt from each organization's desks.toml (current + previous); trigger_hop is mention-chain accounting and reads 0 after a rebuild\n session_id TEXT PRIMARY KEY,\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n current INTEGER NOT NULL DEFAULT 1,\n trigger_hop INTEGER NOT NULL DEFAULT 0\n);\nCREATE INDEX IF NOT EXISTS idx_org_sessions_org ON org_sessions(project_id, org_id);\nCREATE TABLE IF NOT EXISTS org_ticket_sessions ( -- DERIVED CACHE (company mode): ticket <-> contributing session, rebuilt from each ticket's Sessions header\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n ticket_id TEXT NOT NULL,\n session_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n trigger_hop INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (project_id, org_id, ticket_id, session_id)\n);\nCREATE INDEX IF NOT EXISTS idx_org_ticket_sessions_session ON org_ticket_sessions(session_id);\nCREATE TABLE IF NOT EXISTS org_calendar_state ( -- calendar run state (company mode; the files are declarative intent), same rules as schedule_state\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n name TEXT NOT NULL,\n start_at_ms INTEGER NOT NULL,\n def_hash TEXT NOT NULL,\n last_slot_ms INTEGER,\n last_fired_at TEXT,\n fired_once INTEGER NOT NULL DEFAULT 0,\n missed INTEGER NOT NULL DEFAULT 0,\n invalid_reason TEXT,\n last_outcome TEXT,\n PRIMARY KEY (project_id, org_id, agent_id, name)\n);\nCREATE TABLE IF NOT EXISTS org_ticket_state ( -- DERIVED CACHE (company mode): the last (status, owner, blocked) seen per ticket, so a change is notified once; rebuilt silently from the ticket files\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n ticket_id TEXT NOT NULL,\n status TEXT NOT NULL,\n owner TEXT NOT NULL DEFAULT '',\n blocked TEXT NOT NULL DEFAULT '',\n blocked_by TEXT NOT NULL DEFAULT '',\n PRIMARY KEY (project_id, org_id, ticket_id)\n);\nCREATE TABLE IF NOT EXISTS org_channel_state ( -- DERIVED CACHE (company mode): tail-scan byte cursor per channel and day file\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n channel_id TEXT NOT NULL,\n date TEXT NOT NULL,\n offset_bytes INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (project_id, org_id, channel_id, date)\n);\nCREATE TABLE IF NOT EXISTS org_channel_reads ( -- user data (company mode): each user's read cursor in one channel\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n channel_id TEXT NOT NULL,\n user_id TEXT NOT NULL,\n last_read_id TEXT NOT NULL,\n PRIMARY KEY (project_id, org_id, channel_id, user_id)\n);\nCREATE TABLE IF NOT EXISTS org_budget_state ( -- DERIVED CACHE (company mode): warn / pause marks per employee and period, recomputed from usage and the chart's budgets\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n period TEXT NOT NULL,\n warned_at TEXT,\n paused_at TEXT,\n PRIMARY KEY (project_id, org_id, agent_id, period)\n);\nCREATE TABLE IF NOT EXISTS org_desk_notices ( -- DERIVED CACHE (company mode): ticket changes waiting for an employee's next calendar sweep; dropping it loses only the digests not delivered yet\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n ticket_id TEXT NOT NULL,\n change TEXT NOT NULL,\n at TEXT NOT NULL\n);\nCREATE INDEX IF NOT EXISTS idx_org_desk_notices_agent ON org_desk_notices(project_id, org_id, agent_id);\n`;\n"],"mappings":";AAOA,SAAS,iBAAiB;AAC1B,OAAO,UAAU;;;ACoEV,IAAM,aAAmC;AAAA,EAC9C;AAAA,IACE,SAAS;AAAA,IACT,MAAM;AAAA;AAAA;AAAA;A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,SAAO;AACT;AAYA,SAAS,oBAAoB,IAAwB;AACnD,KAAG,KAAK,OAAO;AACf,MAAI;AACF,QAAI,aAAa,IAAI,YAAY,kBAAkB,MAAM,GAAG;AAC1D,SAAG;AAAA,QACD;AAAA;AAAA;AAAA;AAAA,MAIF;AAAA,IACF;AACA,OAAG,KAAK,QAAQ;AAAA,EAClB,SAAS,KAAK;AACZ,OAAG,KAAK,UAAU;AAClB,UAAM;AAAA,EACR;AACF;AAOO,SAAS,aACd,IACA,OACA,QACA,KACS;AACT,QAAM,OAAO,GAAG,QAAQ,qBAAqB,KAAK,GAAG,EAAE,IAAI;AAC3D,MAAI,KAAK,KAAK,CAAC,MAAM,EAAE,SAAS,MAAM,EAAG,QAAO;AAChD,KAAG,KAAK,eAAe,KAAK,eAAe,MAAM,IAAI,GAAG,EAAE;AAC1D,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/db/database.ts","../src/db/migrations.ts","../src/db/schema.ts"],"sourcesContent":["/**\n * SQLite connection & initialization (node:sqlite DatabaseSync).\n *\n * Single process, single writer: a synchronous API is sufficient and avoids a connection\n * pool; WAL mode and foreign key constraints are enabled. Table-creation SQL runs on open\n * (idempotent), with no migration branches (product not yet released).\n */\nimport { mkdirSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type { DatabaseSync } from \"node:sqlite\";\nimport { migrate } from \"./migrations.js\";\nimport { SCHEMA_SQL } from \"./schema.js\";\n\n// Fetch the runtime module via process.getBuiltinModule (node >=22.3): avoids static\n// resolution of `node:sqlite` by bundlers/vite (some tools' builtin lists don't yet\n// recognize this experimental module).\nconst sqlite = process.getBuiltinModule(\"node:sqlite\");\n\n/**\n * Opens an EXISTING database for a narrow write, without running any schema work.\n *\n * `openDatabase` migrates — CREATE TABLE, several ensureColumn calls, a DROP INDEX and a backfill.\n * That is right for the process that owns the database and wrong for a short-lived CLI writing\n * one row (`penguin auth token`): after `penguin update` the CLI on disk can be NEWER than the\n * running server, and migrating under a live server's prepared statements is not something a\n * token mint should do. The caller has already established that the file exists.\n */\nexport function openExistingDatabase(dbPath: string): DatabaseSync {\n const db = new sqlite.DatabaseSync(dbPath);\n db.exec(\"PRAGMA foreign_keys = ON;\");\n // Wait for the live server's write lock instead of failing SQLITE_BUSY at once.\n db.exec(\"PRAGMA busy_timeout = 5000;\");\n return db;\n}\n\n/**\n * Opens an EXISTING database for reading only — SQLite refuses every write on the connection,\n * so a reader cannot change the file even by mistake. For a question asked of a database some\n * other process owns (`penguin server status`, run over ssh by a controller): the answer must\n * not reshape that server's schema, and must not be able to. The caller has established that\n * the file exists; a read-only open of a missing file is an error, not a creation.\n */\nexport function openDatabaseReadOnly(dbPath: string): DatabaseSync {\n const db = new sqlite.DatabaseSync(dbPath, { readOnly: true });\n db.exec(\"PRAGMA busy_timeout = 5000;\");\n return db;\n}\n\n/** Open (creating if necessary) the database: ensure the parent directory exists, set PRAGMAs, run table creation. */\nexport function openDatabase(dbPath: string): DatabaseSync {\n if (dbPath !== \":memory:\") {\n mkdirSync(path.dirname(dbPath), { recursive: true });\n }\n const db = new sqlite.DatabaseSync(dbPath);\n db.exec(\"PRAGMA journal_mode = WAL;\");\n // A second connection (the CLI minting a token while the server runs) waits for the write\n // lock rather than failing SQLITE_BUSY at once.\n db.exec(\"PRAGMA busy_timeout = 5000;\");\n db.exec(\"PRAGMA foreign_keys = ON;\");\n db.exec(SCHEMA_SQL);\n // Columns added to the schema after a web.db was formed: CREATE TABLE IF NOT EXISTS never\n // touches an existing table, so they are ALTERed in here. Keep the list in sync with\n // schema.ts; drop entries only in a release allowed to break existing web.db files.\n ensureColumn(db, \"sessions\", \"client\", \"TEXT\");\n ensureColumn(db, \"sessions\", \"has_trace\", \"INTEGER NOT NULL DEFAULT 0\");\n ensureColumn(db, \"sessions\", \"fork_count\", \"INTEGER NOT NULL DEFAULT 0\");\n ensureColumn(db, \"sessions\", \"thinking_level\", \"TEXT\");\n ensureColumn(db, \"sessions\", \"sandbox\", \"TEXT\");\n // A v0.2.0 web.db has auth_sessions without `via`; CREATE TABLE IF NOT EXISTS never adds a\n // column, so every INSERT would fail \"no column named via\" until this runs.\n ensureColumn(db, \"auth_sessions\", \"via\", \"TEXT\");\n ensureColumn(db, \"trace_files\", \"page_stats\", \"TEXT\");\n ensureColumn(db, \"messaging_bindings\", \"line_per_message\", \"INTEGER NOT NULL DEFAULT 0\");\n ensureColumn(db, \"messaging_bindings\", \"final_reply_only\", \"INTEGER NOT NULL DEFAULT 0\");\n // DEFAULT 1, unlike every other added flag here: this one's default is the CORRECTED\n // behaviour, not the previous one. Sending the model's Markdown as characters was the\n // defect, so an existing binding starts rendering it — a visible change to every relayed\n // message, recorded in the release's backward-compatibility entry.\n ensureColumn(db, \"messaging_bindings\", \"render_markdown\", \"INTEGER NOT NULL DEFAULT 1\");\n ensureColumn(db, \"messaging_bindings\", \"last_inbound_message_id\", \"TEXT\");\n // Superseded by idx_usage_session_ts (session_id, ts), which SCHEMA_SQL just created on\n // this database: the old index is a strict prefix of it, so every query it served is\n // served identically. Dropping is safe — an index is derived, never data.\n db.exec(\"DROP INDEX IF EXISTS idx_usage_session\");\n // The uniqueness index of the old binding model, where a bot account belonged to one\n // Session forever and a second Session could not even SAVE its credentials. Enabling a\n // connection is the binding now, so exclusivity is checked per enable (the state route's\n // 409 account_enabled_elsewhere) and the same account may sit saved on many Sessions —\n // which this index would reject. SCHEMA_SQL has just created idx_messaging_by_account\n // over the same columns, so the by-account lookup stays indexed. Dropping is safe: an\n // index is derived, never data. It is however ONE-WAY — an older build recreates the\n // unique index on open, which fails outright once duplicate (channel, account_id) rows\n // exist, so a downgrade after two Sessions saved the same bot needs those rows removed.\n db.exec(\"DROP INDEX IF EXISTS idx_messaging_account\");\n upgradeLastActiveAt(db);\n // The runtime's own open is the ONLY place a restart-only migration may be applied: it\n // owns the process, so there is no boot to roll back out from under it.\n migrate(db);\n return db;\n}\n\n/**\n * One-time `sessions.last_active_at` upgrade, ALTER + backfill in a single transaction.\n *\n * The backfill runs **only in the open that actually adds the column** (SQLite's ALTER\n * TABLE ADD COLUMN is transactional, so a crash mid-upgrade rolls back to \"no column\" and\n * the next open redoes both halves — never a half-migrated table, and never a full\n * `sessions` scan on the millions of opens that follow). Legacy rows take the session's\n * most recent request timestamp — usage_records, covered by idx_usage_session_ts, the\n * closest persisted proxy for \"last Trace activity\" — else their own created_at.\n */\nfunction upgradeLastActiveAt(db: DatabaseSync): void {\n db.exec(\"BEGIN\");\n try {\n if (ensureColumn(db, \"sessions\", \"last_active_at\", \"TEXT\")) {\n db.exec(\n `UPDATE sessions SET last_active_at = COALESCE(\n (SELECT MAX(ts) FROM usage_records WHERE usage_records.session_id = sessions.session_id),\n created_at\n )`,\n );\n }\n db.exec(\"COMMIT\");\n } catch (err) {\n db.exec(\"ROLLBACK\");\n throw err;\n }\n}\n\n/**\n * Idempotent per-column upgrade for databases formed before the column existed.\n * Returns whether this call actually ALTERed the table (false = the column was already\n * there), so a caller can gate one-time backfill work on it.\n */\nexport function ensureColumn(\n db: DatabaseSync,\n table: string,\n column: string,\n ddl: string,\n): boolean {\n const cols = db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[];\n if (cols.some((c) => c.name === column)) return false;\n db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${ddl}`);\n return true;\n}\n","/**\n * Ordered, versioned schema migrations.\n *\n * `schema.ts` declares the shape a FRESH database is created with. It cannot express a\n * CHANGE — `CREATE TABLE IF NOT EXISTS` only ever says \"should exist\", so re-running it\n * converges a database toward the current declaration without ever knowing, or recording,\n * which state it came from. That is why a build could not tell a 0.2.4 database from a\n * 0.2.7 one, and why the only safe change was an additive one.\n *\n * A migration says what CHANGED, runs once, and leaves the database stamped with how far\n * it has come (`PRAGMA user_version`). Two rules make that stamp trustworthy:\n *\n * FROZEN DDL. A migration spells out its own SQL and never imports SCHEMA_SQL. Referring\n * to the live declaration would make an old migration silently mean something new every\n * time the schema moves, which is the property that makes migrations auditable at all.\n *\n * ONE WAY, IN ORDER. Versions are contiguous from 1 and never renumbered or rewritten\n * once released — a database that already stamped version N will never run N again, so\n * editing N only changes what NEW databases get, and silently forks the two.\n *\n * `swapSafe` is this codebase's extra axis, and it exists because of hot updates. A\n * pushed platform boots against a live database and is ROLLED BACK to its predecessor if\n * it fails; the predecessor then runs on whatever the migration already did. Additive\n * work survives that (the older build does not know the new table, so it never touches\n * it) — narrowing work does not. Anything that drops, retypes, constrains, or reshapes\n * is `swapSafe: false` and must be refused on the swap path rather than half-applied\n * (see `migrate`'s `swapPath` option).\n *\n * DOWN, AND WHO DOES NOT CALL IT. Every migration declares an undo — or declares `null`\n * to say it has none, which is a decision the author has to make rather than omit. What\n * `down` is NOT is the hot-update rollback mechanism. When a pushed platform fails to boot\n * the runtime reverts to its PREDECESSOR and the schema stays where the migration left it:\n * undoing DDL inside a process whose boot just failed would run destructive statements\n * against a half-known state, and `swapSafe` exists precisely so that not undoing is safe —\n * the predecessor does not know the new table or column, so it never touches it. `down` is\n * an operator's tool, called deliberately (`rollbackTo`), never by the swap.\n *\n * It is also LOSSY by nature: undoing \"add a table\" drops that table with its rows in it.\n * Each `down` below names what its rows were.\n *\n * ADOPTION. Databases created before this file existed are all stamped 0 while sitting in\n * genuinely different shapes, so a migration must tolerate finding its work already done.\n * That is not only a version-1 concern: `schema.ts` still DECLARES the current shape in\n * full and `openDatabase` still runs its ensureColumn list, so a database can arrive at a\n * migration with that migration's work already applied by the declarative track. Until\n * SCHEMA_SQL is frozen to a baseline and every later change is a migration, every\n * migration here stays idempotent — `IF NOT EXISTS`, or the same `ensureColumn` guard the\n * declarative track uses. Once that double track is gone, a bare `CREATE TABLE` that\n * fails loudly becomes the point.\n */\nimport type { DatabaseSync } from \"node:sqlite\";\nimport { ensureColumn } from \"./database.js\";\n\nexport interface Migration {\n /** Contiguous from 1. Never renumbered, never edited once released. */\n version: number;\n /** Kebab-case, names the change — read in logs and in the stamp's history. */\n name: string;\n /**\n * May this run while a pushed platform boots? True only for strictly additive work,\n * which a rollback to the previous platform survives. See the module doc.\n */\n swapSafe: boolean;\n /** Applied inside a transaction; throw to abort and leave the version unchanged. */\n up: (db: DatabaseSync) => void;\n /**\n * Undoes `up`, or null when this migration cannot be undone — required, not optional, so\n * \"there is no undo\" is something the author states rather than forgets.\n *\n * Never called by the swap path (see the module doc): a failed boot reverts the platform,\n * not the schema. Reached only through `rollbackTo`, and destructive by nature — dropping\n * a table takes its rows with it.\n */\n down: ((db: DatabaseSync) => void) | null;\n}\n\nexport const MIGRATIONS: readonly Migration[] = [\n {\n version: 1,\n name: \"messaging-bindings\",\n // Purely additive: one new table plus three indexes, no column of any existing table\n // touched. A platform that rolls back to a predecessor without messaging simply never\n // queries them.\n swapSafe: true,\n up(db) {\n // 0.2.4 → 0.2.7. Frozen copy of the DDL as of 0.2.7; do not re-derive from schema.ts.\n // IF NOT EXISTS only because version 1 adopts unstamped databases, which may already\n // be at 0.2.7 (see the module doc's ADOPTION note).\n db.exec(`\n CREATE TABLE IF NOT EXISTS messaging_bindings (\n session_id TEXT NOT NULL,\n channel TEXT NOT NULL,\n account_id TEXT NOT NULL,\n config_json TEXT NOT NULL,\n enabled INTEGER NOT NULL DEFAULT 0,\n line_per_message INTEGER NOT NULL DEFAULT 0,\n last_chat_id TEXT,\n last_chat_is_direct INTEGER NOT NULL DEFAULT 1,\n last_inbound_message_id TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (session_id, channel)\n );\n CREATE INDEX IF NOT EXISTS idx_messaging_by_account ON messaging_bindings(channel, account_id);\n CREATE INDEX IF NOT EXISTS idx_auth_sessions_expires ON auth_sessions(expires_at);\n CREATE INDEX IF NOT EXISTS idx_auth_sessions_user ON auth_sessions(user_id);\n `);\n },\n // LOSES every messaging binding: the channel credentials, the enabled flag and the\n // last-chat memory all live in the table this drops. The auth_sessions indexes are\n // derived and cost nothing to lose.\n down(db) {\n db.exec(`\n DROP INDEX IF EXISTS idx_auth_sessions_user;\n DROP INDEX IF EXISTS idx_auth_sessions_expires;\n DROP INDEX IF EXISTS idx_messaging_by_account;\n DROP TABLE IF EXISTS messaging_bindings;\n `);\n },\n },\n {\n version: 2,\n name: \"messaging-delivery-flags\",\n // Two columns with defaults on an existing table: a rollback to a predecessor that\n // does not know them leaves them at their defaults and reads nothing.\n swapSafe: true,\n up(db) {\n // 0.2.7 → 0.2.8. ensureColumn rather than a bare ALTER because the declarative\n // track may already have added these (see the module doc's ADOPTION note).\n ensureColumn(db, \"messaging_bindings\", \"final_reply_only\", \"INTEGER NOT NULL DEFAULT 0\");\n ensureColumn(db, \"messaging_bindings\", \"render_markdown\", \"INTEGER NOT NULL DEFAULT 1\");\n },\n // LOSES both delivery preferences on every binding; the bindings themselves survive.\n // Dropped in reverse order for symmetry with `up`. Neither column is indexed, which is\n // what lets SQLite drop them at all.\n down(db) {\n db.exec(\"ALTER TABLE messaging_bindings DROP COLUMN render_markdown\");\n db.exec(\"ALTER TABLE messaging_bindings DROP COLUMN final_reply_only\");\n },\n },\n {\n version: 3,\n name: \"drop-goal-state\",\n // Narrowing: drops a table. A pushed platform rolled back to 0.2.9 mid-process would\n // prepare its goal statements against a table that is gone (its declarative track only\n // runs at the runtime's own open, never at a platform boot), so this is the first\n // restart-only migration: refused on the swap path, applied by the runtime's open.\n swapSafe: false,\n up(db) {\n // 0.2.9 → 0.2.10. goal_state held goal mode's run state, one row per goal run, read\n // back only for the chat page's goal banner; the goal plugin's GOAL.json in the\n // Session scratchpad is that record now (see runtime/goal-events.ts). IF EXISTS only\n // because a database this build created never had the table.\n db.exec(`\n DROP INDEX IF EXISTS idx_goal_session;\n DROP TABLE IF EXISTS goal_state;\n `);\n },\n // Recreates the table exactly as 0.2.9 declared it — EMPTY. LOSES every goal run ever\n // recorded (objective, status, budget, used, rounds per run): the rows only ever fed the\n // banner of a finished goal, and a build with this migration reads the goal file instead.\n down(db) {\n db.exec(`\n CREATE TABLE IF NOT EXISTS goal_state (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n session_id TEXT NOT NULL,\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n objective TEXT NOT NULL,\n status TEXT NOT NULL,\n budget INTEGER NOT NULL,\n used INTEGER NOT NULL DEFAULT 0,\n rounds INTEGER NOT NULL DEFAULT 0,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_goal_session ON goal_state(session_id);\n `);\n },\n },\n {\n version: 4,\n name: \"machines\",\n // Three new tables, nothing existing touched: a platform rolled back to one without\n // machines never queries them. Swap-safe on its own; a database still behind\n // drop-goal-state is refused whole by that one first, which is the rule.\n swapSafe: true,\n up(db) {\n // Frozen copy of the DDL as of the machines feature; do not re-derive from schema.ts.\n // IF NOT EXISTS because the declarative track may already have created them (ADOPTION).\n db.exec(`\n CREATE TABLE IF NOT EXISTS machine (\n singleton INTEGER PRIMARY KEY CHECK (singleton = 1),\n machine_id TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS machines (\n address TEXT PRIMARY KEY,\n machine_id TEXT,\n version TEXT,\n installed_at TEXT,\n session_pid INTEGER,\n remote_port INTEGER,\n platform TEXT\n );\n CREATE TABLE IF NOT EXISTS machine_project (\n project_id TEXT PRIMARY KEY REFERENCES projects(project_id) ON DELETE CASCADE,\n addresses TEXT NOT NULL\n );\n `);\n },\n // LOSES this server's own machine id (every stored reference to it on other machines\n // then points at nothing), what was installed where, the sessions held, and which\n // machines each Project used.\n down(db) {\n db.exec(`\n DROP TABLE IF EXISTS machine_project;\n DROP TABLE IF EXISTS machines;\n DROP TABLE IF EXISTS machine;\n `);\n },\n },\n {\n version: 5,\n name: \"user-profile\",\n // Two nullable columns on `users`, no default and nothing existing rewritten: a platform\n // rolled back to a predecessor that does not know them never selects or writes them, and\n // every existing account simply reads NULL — no profile yet.\n swapSafe: true,\n up(db) {\n // Frozen copy of the DDL as of the user-profile feature; do not re-derive from schema.ts.\n // SQLite has no ADD COLUMN IF NOT EXISTS, and the declarative track may already have\n // added both (ADOPTION), so each one goes through the same table_info guard the\n // declarative track uses.\n ensureColumn(db, \"users\", \"display_name\", \"TEXT\");\n ensureColumn(db, \"users\", \"avatar\", \"TEXT\");\n },\n // LOSES every stored nickname and avatar: both live entirely in the two columns this\n // drops, and nothing else on disk holds a copy. Dropped in reverse order for symmetry\n // with `up`; neither column is indexed, which is what lets SQLite drop them at all.\n down(db) {\n const cols = db.prepare(\"PRAGMA table_info(users)\").all() as { name: string }[];\n const has = (name: string): boolean => cols.some((c) => c.name === name);\n if (has(\"avatar\")) db.exec(\"ALTER TABLE users DROP COLUMN avatar\");\n if (has(\"display_name\")) db.exec(\"ALTER TABLE users DROP COLUMN display_name\");\n },\n },\n {\n version: 6,\n name: \"company-mode-org-caches\",\n // Additive: seven new tables for company mode (organizations of Agents), no change to any\n // existing table. Every row is either rebuildable from the organization's files (desks.toml,\n // the tickets' Sessions headers, the calendar files, usage records) or a user's own read\n // cursor; a predecessor build never touches them.\n swapSafe: true,\n up(db) {\n db.exec(`\n CREATE TABLE IF NOT EXISTS org_sessions ( -- DERIVED CACHE (company mode): desk sessions, rebuilt from each organization's desks.toml (current + previous); trigger_hop is chat-chain accounting and reads 0 after a rebuild\n session_id TEXT PRIMARY KEY,\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n current INTEGER NOT NULL DEFAULT 1,\n trigger_hop INTEGER NOT NULL DEFAULT 0\n );\n CREATE INDEX IF NOT EXISTS idx_org_sessions_org ON org_sessions(project_id, org_id);\n CREATE TABLE IF NOT EXISTS org_ticket_sessions ( -- DERIVED CACHE (company mode): ticket <-> contributing session, rebuilt from each ticket's Sessions header\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n ticket_id TEXT NOT NULL,\n session_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n trigger_hop INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (project_id, org_id, ticket_id, session_id)\n );\n CREATE INDEX IF NOT EXISTS idx_org_ticket_sessions_session ON org_ticket_sessions(session_id);\n CREATE TABLE IF NOT EXISTS org_calendar_state ( -- calendar run state (company mode; the files are declarative intent), same rules as schedule_state\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n name TEXT NOT NULL,\n start_at_ms INTEGER NOT NULL,\n def_hash TEXT NOT NULL,\n last_slot_ms INTEGER,\n last_fired_at TEXT,\n fired_once INTEGER NOT NULL DEFAULT 0,\n missed INTEGER NOT NULL DEFAULT 0,\n invalid_reason TEXT,\n last_outcome TEXT,\n PRIMARY KEY (project_id, org_id, agent_id, name)\n );\n CREATE TABLE IF NOT EXISTS org_ticket_state ( -- DERIVED CACHE (company mode): the last (status, owner, blocked) seen per ticket, so a change is notified once; rebuilt silently from the ticket files\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n ticket_id TEXT NOT NULL,\n status TEXT NOT NULL,\n owner TEXT NOT NULL DEFAULT '',\n blocked TEXT NOT NULL DEFAULT '',\n blocked_by TEXT NOT NULL DEFAULT '',\n PRIMARY KEY (project_id, org_id, ticket_id)\n );\n CREATE TABLE IF NOT EXISTS org_chat_state ( -- DERIVED CACHE (company mode): tail-scan byte cursor per chat day file\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n date TEXT NOT NULL,\n offset_bytes INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (project_id, org_id, date)\n );\n CREATE TABLE IF NOT EXISTS org_chat_reads ( -- user data (company mode): each user's read cursor in an organization's chat\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n user_id TEXT NOT NULL,\n last_read_id TEXT NOT NULL,\n PRIMARY KEY (project_id, org_id, user_id)\n );\n CREATE TABLE IF NOT EXISTS org_budget_state ( -- DERIVED CACHE (company mode): warn / pause marks per employee and period, recomputed from usage and the chart's budgets\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n period TEXT NOT NULL,\n warned_at TEXT,\n paused_at TEXT,\n PRIMARY KEY (project_id, org_id, agent_id, period)\n );\n `);\n },\n // Drops the seven tables. LOSES: chat read cursors (each user's \"read up to here\" marks) and\n // the run marks that stop a calendar slot, a ticket change or a budget alert from firing\n // twice — a build with this migration re-registers everything from the files, without\n // backfilling missed slots, and users see every chat message as unread once.\n down(db) {\n db.exec(`\n DROP INDEX IF EXISTS idx_org_ticket_sessions_session;\n DROP INDEX IF EXISTS idx_org_sessions_org;\n DROP TABLE IF EXISTS org_budget_state;\n DROP TABLE IF EXISTS org_chat_reads;\n DROP TABLE IF EXISTS org_chat_state;\n DROP TABLE IF EXISTS org_ticket_state;\n DROP TABLE IF EXISTS org_calendar_state;\n DROP TABLE IF EXISTS org_ticket_sessions;\n DROP TABLE IF EXISTS org_sessions;\n `);\n },\n },\n {\n version: 7,\n name: \"company-mode-channels\",\n // The organization's single group chat became channels: a message lives in\n // `channels/<channel_id>/<date>.jsonl`, so the tail-scan cursor and each user's read\n // cursor are per channel. `org_chat_state` / `org_chat_reads` are dropped for\n // `org_channel_state` / `org_channel_reads`: the tables are renamed and the channel\n // belongs in the primary key, neither of which SQLite does in place. Nothing is carried\n // over: company mode is unreleased, and every row was either rebuildable from the files\n // (the scan cursor) or one pass of \"everything looks unread\" (the read cursor). A\n // predecessor build reads neither table's shape, only its own writes, so this is\n // swap-safe.\n swapSafe: true,\n up(db) {\n db.exec(`\n DROP TABLE IF EXISTS org_chat_state;\n DROP TABLE IF EXISTS org_chat_reads;\n CREATE TABLE IF NOT EXISTS org_channel_state ( -- DERIVED CACHE (company mode): tail-scan byte cursor per channel and day file\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n channel_id TEXT NOT NULL,\n date TEXT NOT NULL,\n offset_bytes INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (project_id, org_id, channel_id, date)\n );\n CREATE TABLE IF NOT EXISTS org_channel_reads ( -- user data (company mode): each user's read cursor in one channel\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n channel_id TEXT NOT NULL,\n user_id TEXT NOT NULL,\n last_read_id TEXT NOT NULL,\n PRIMARY KEY (project_id, org_id, channel_id, user_id)\n );\n `);\n },\n // Recreates the two tables under their old names, exactly as migration 6 declared them —\n // EMPTY. LOSES every scan cursor (re-derived by the next pass, which republishes the\n // messages it re-reads) and every read cursor (users see the recent days as unread once).\n down(db) {\n db.exec(`\n DROP TABLE IF EXISTS org_channel_state;\n DROP TABLE IF EXISTS org_channel_reads;\n CREATE TABLE IF NOT EXISTS org_chat_state ( -- DERIVED CACHE (company mode): tail-scan byte cursor per chat day file\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n date TEXT NOT NULL,\n offset_bytes INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (project_id, org_id, date)\n );\n CREATE TABLE IF NOT EXISTS org_chat_reads ( -- user data (company mode): each user's read cursor in an organization's chat\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n user_id TEXT NOT NULL,\n last_read_id TEXT NOT NULL,\n PRIMARY KEY (project_id, org_id, user_id)\n );\n `);\n },\n },\n {\n version: 8,\n name: \"company-mode-desk-notices\",\n // Additive: one new table and its index. A ticket change no longer starts a work run at\n // the owner's desk; it is queued here and delivered inside the body of that employee's\n // next calendar sweep. A predecessor build never reads the table, so a rollback survives\n // it — with whatever rows are in it left undelivered.\n swapSafe: true,\n up(db) {\n db.exec(`\n CREATE TABLE IF NOT EXISTS org_desk_notices ( -- DERIVED CACHE (company mode): ticket changes waiting for an employee's next calendar sweep; dropping it loses only the digests not delivered yet\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n ticket_id TEXT NOT NULL,\n change TEXT NOT NULL,\n at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_org_desk_notices_agent ON org_desk_notices(project_id, org_id, agent_id);\n `);\n },\n // LOSES every queued notice: the ticket changes an employee has not been told about yet.\n // The change itself is in the ticket file and its history either way; what\n // goes is the \"Since your last sweep\" line that would have named it.\n down(db) {\n db.exec(`\n DROP INDEX IF EXISTS idx_org_desk_notices_agent;\n DROP TABLE IF EXISTS org_desk_notices;\n `);\n },\n },\n {\n version: 9,\n name: \"model-promotions\",\n // Additive: one new table, nothing existing touched. A predecessor build never reads it\n // and prices every row at the number in its Project file, so a rollback survives it.\n swapSafe: true,\n up(db) {\n // Frozen copy of the DDL as of the model-promotions feature; do not re-derive from\n // schema.ts. IF NOT EXISTS because the declarative track may already have created it\n // (ADOPTION).\n db.exec(`\n CREATE TABLE IF NOT EXISTS model_promotions ( -- NOT a cache rebuildable from files: the only record of a Project row's running promotion (.project_config.toml keeps the list price), written by preset seeding at Project creation, \"sync presets\" and Penguin Go authorization / sync, and read by cost; lost rows price usage at list until the next sync writes them back\n project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,\n provider TEXT NOT NULL,\n model_id TEXT NOT NULL,\n discount REAL NOT NULL CHECK (discount > 0 AND discount < 1),\n updated_at TEXT NOT NULL,\n PRIMARY KEY (project_id, provider, model_id)\n );\n `);\n },\n // LOSES every stored promotion: no file holds a copy of the fractions, so usage is priced\n // at the Project files' list prices until the next \"sync presets\" or Penguin Go sync\n // writes them back.\n down(db) {\n db.exec(\"DROP TABLE IF EXISTS model_promotions\");\n },\n },\n {\n version: 10,\n name: \"model-provider-auth-tokens\",\n // Additive: one new table, nothing existing touched. A predecessor build never reads it;\n // the access token already written into .project_config.toml keeps working until it\n // expires, so rollback only loses silent refresh state.\n // KEEP until every supported upgrade starts from schema 10 or newer. The release that\n // raises the minimum database baseline past 9 owns removing this migration block and its\n // version-9 fixture; the table itself remains while provider token refresh uses it.\n swapSafe: true,\n up(db) {\n // Frozen copy of the DDL as of the provider-auth-token feature; do not re-derive from\n // schema.ts. IF NOT EXISTS because the declarative track may already have created it\n // (ADOPTION).\n db.exec(`\n CREATE TABLE IF NOT EXISTS model_provider_auth_tokens ( -- Server-side OAuth refresh metadata for provider groups. The current request token remains in .project_config.toml as api_key; this table holds only the refresh material that must never be returned to the frontend or written into Project files.\n project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,\n provider TEXT NOT NULL,\n refresh_token TEXT NOT NULL,\n access_token_expires_at TEXT,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (project_id, provider)\n );\n `);\n },\n // LOSES every stored refresh token and access-token expiry. Existing access tokens in\n // Project files remain until they expire; users re-authorize to restore silent refresh.\n down(db) {\n db.exec(\"DROP TABLE IF EXISTS model_provider_auth_tokens\");\n },\n },\n {\n version: 11,\n name: \"sessions-sandbox\",\n // The Session's own sandbox policy (JSON), snapshotted from the server's settings when\n // the Session is created, so a later settings change leaves running Sessions alone.\n // NULL = a row from before this column: it takes the settings in force at its next\n // command and keeps them from then on. Swap-safe: a pushed platform boots against the\n // runtime's already-open database, so the column has to arrive by a migration.\n swapSafe: true,\n up(db) {\n ensureColumn(db, \"sessions\", \"sandbox\", \"TEXT\");\n },\n // Not a DROP: schema.ts declares the column, and dropping it would put every Session\n // back under whatever the settings say.\n down() {},\n },\n {\n version: 12,\n name: \"machines-columns\",\n // A machines table can predate migration 4 — a data root that ran the machines line\n // before it was released kept forwards, not sessions — and that migration's IF NOT\n // EXISTS adopted it whatever its columns were, so the first connect failed on the row's\n // insert. Adds what is missing, nullable; a platform rolled back to 4 declared these\n // columns itself, so there is nothing for it to mind.\n swapSafe: true,\n up(db) {\n ensureColumn(db, \"machines\", \"session_pid\", \"INTEGER\");\n ensureColumn(db, \"machines\", \"platform\", \"TEXT\");\n },\n // Nothing to undo: what this added, 4 already declares, and a column it found in place\n // was never this migration's to take away.\n down() {},\n },\n {\n version: 13,\n name: \"browser-extensions\",\n // Additive: one new table and its index. The Chrome backend's pairings — one row per\n // PenguinHarness Browser extension a user paired, its token stored hashed. A predecessor\n // build never reads the table, so a rollback survives it; the paired extensions then simply\n // fail to connect until a build that knows them is back.\n swapSafe: true,\n up(db) {\n // Frozen copy of the DDL as of the system-Chrome feature; do not re-derive from schema.ts.\n // IF NOT EXISTS because the declarative track may already have created it (ADOPTION).\n db.exec(`\n CREATE TABLE IF NOT EXISTS browser_extensions ( -- one row per Chrome paired to a user (builtin-browser/extension-pairing.ts): the PenguinHarness Browser extension's long-lived credential, stored only hashed; NOT rebuildable — a lost row means pairing that Chrome again\n extension_id TEXT PRIMARY KEY,\n user_id TEXT NOT NULL REFERENCES users(user_id) ON DELETE CASCADE,\n token_hash TEXT NOT NULL UNIQUE,\n name TEXT NOT NULL,\n version TEXT NOT NULL,\n created_at TEXT NOT NULL,\n last_seen_at TEXT,\n revoked_at TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_browser_extensions_user ON browser_extensions(user_id);\n `);\n },\n // LOSES every pairing: each user's Chrome has to be paired again (a new code from the\n // Browser panel) before agents can drive it.\n down(db) {\n db.exec(`\n DROP INDEX IF EXISTS idx_browser_extensions_user;\n DROP TABLE IF EXISTS browser_extensions;\n `);\n },\n },\n {\n version: 14,\n name: \"agent-api\",\n // Additive: two new tables and an index. The Agent API's per-Agent settings (the switch,\n // keyless access, the approval mode API Sessions are created with) and its keys, stored\n // hashed. A predecessor build never reads them and serves no /api/amsp route, so a\n // rollback survives it: callers get 404 until a build that knows the tables is back.\n swapSafe: true,\n up(db) {\n // Frozen copy of the DDL as of the Agent API feature; do not re-derive from schema.ts.\n // IF NOT EXISTS because the declarative track may already have created them (ADOPTION).\n db.exec(`\n CREATE TABLE IF NOT EXISTS agent_api ( -- per-Agent public API settings (amsp/routes.ts); NOT rebuildable from files\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n enabled INTEGER NOT NULL DEFAULT 0,\n open INTEGER NOT NULL DEFAULT 0,\n approval_mode TEXT NOT NULL DEFAULT 'allow-all',\n updated_at TEXT NOT NULL,\n PRIMARY KEY (project_id, agent_id)\n );\n CREATE TABLE IF NOT EXISTS agent_api_keys ( -- one row per key the API tab or the CLI minted; the caller alone holds the key\n key_id TEXT PRIMARY KEY,\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n token_hash TEXT NOT NULL UNIQUE,\n prefix TEXT NOT NULL,\n name TEXT NOT NULL,\n created_by TEXT NOT NULL REFERENCES users(user_id),\n created_at TEXT NOT NULL,\n last_used_at TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_agent_api_keys_agent ON agent_api_keys(project_id, agent_id);\n `);\n },\n // LOSES every Agent's API settings and every key: each exposed Agent reads as disabled\n // again (404 to its callers), and every caller needs a newly created key once it is back\n // on — no file holds a copy of either.\n down(db) {\n db.exec(`\n DROP INDEX IF EXISTS idx_agent_api_keys_agent;\n DROP TABLE IF EXISTS agent_api_keys;\n DROP TABLE IF EXISTS agent_api;\n `);\n },\n },\n {\n version: 15,\n name: \"messaging-conversations\",\n // Additive: one new table. The WeChat connector's per-(bot, user) delivery state — the\n // context token every send must echo, how many sends it has funded, and replies held for\n // the user's next message. A predecessor build never reads it and keeps its tokens in\n // memory as it always did, so a rollback survives it.\n swapSafe: true,\n up(db) {\n // Frozen copy of the DDL as of the WeChat delivery fix; do not re-derive from schema.ts.\n // IF NOT EXISTS because the declarative track may already have created it (ADOPTION).\n db.exec(`\n CREATE TABLE IF NOT EXISTS messaging_conversations ( -- per-(bot, chat) delivery state a connector must keep across reconnects and restarts (WeChat: the context token, its send count, held replies); deleted once no messaging_bindings row references (channel, account_id) — see MessagingBindingsRepo\n channel TEXT NOT NULL,\n account_id TEXT NOT NULL,\n chat_id TEXT NOT NULL,\n state_json TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (channel, account_id, chat_id)\n );\n `);\n },\n // LOSES every stored context token and every held reply: replies sent before each user's\n // next message are refused again, and what was held never arrives.\n down(db) {\n db.exec(\"DROP TABLE IF EXISTS messaging_conversations\");\n },\n },\n {\n version: 16,\n name: \"sessions-kept-at\",\n // The \"keep in sidebar\" mark: written when the user unarchives a Session, cleared when they\n // archive it. The listing rule files a background Session (api / schedule / cli) away unless\n // it carries the mark, so existing rows are listed by the rule as they stand and nothing is\n // rewritten. Swap-safe: a pushed platform boots against the runtime's already-open database,\n // so the column has to arrive by a migration.\n swapSafe: true,\n up(db) {\n ensureColumn(db, \"sessions\", \"kept_at\", \"TEXT\");\n },\n // Not a DROP: schema.ts declares the column, and dropping it would file every kept\n // background Session away again.\n down() {},\n },\n {\n version: 17,\n name: \"agent-api-session-settings\",\n // Retain until the minimum supported database version exceeds 16; the maintainer raising\n // that baseline removes this upgrade after all supported data roots have these columns.\n // Nullable additions preserve existing keys, exposure, approvals and new-Session defaults.\n swapSafe: true,\n up(db) {\n ensureColumn(db, \"agent_api\", \"provider\", \"TEXT\");\n ensureColumn(db, \"agent_api\", \"model_id\", \"TEXT\");\n ensureColumn(db, \"agent_api\", \"thinking_level\", \"TEXT\");\n ensureColumn(db, \"agent_api\", \"workspace\", \"TEXT\");\n },\n // Keep the saved defaults on rollback; older builds ignore the additional columns.\n down() {},\n },\n {\n version: 18,\n name: \"agent-api-concurrency\",\n // Retain until the minimum supported database version exceeds 17. The maintainer raising\n // that baseline removes this upgrade once every supported data root has the column.\n swapSafe: true,\n up(db) {\n ensureColumn(db, \"agent_api\", \"max_concurrent_runs\", \"INTEGER NOT NULL DEFAULT 4\");\n },\n // Keep the configured limit on rollback; older builds ignore this column.\n down() {},\n },\n];\n\n/** The highest version this build knows how to reach. */\nexport const LATEST_VERSION: number = MIGRATIONS.reduce((n, m) => Math.max(n, m.version), 0);\n\n/** How far this database has been migrated. Unstamped (pre-migrations) databases read 0. */\nexport function schemaVersion(db: DatabaseSync): number {\n const row = db.prepare(\"PRAGMA user_version\").get() as { user_version: number } | undefined;\n return row?.user_version ?? 0;\n}\n\nexport class IrreversibleMigrationError extends Error {\n constructor(readonly migration: Migration) {\n super(\n `migration ${migration.version} (${migration.name}) declares no down and cannot be rolled back. ` +\n `Restore the database from a backup taken before it was applied.`,\n );\n this.name = \"IrreversibleMigrationError\";\n }\n}\n\nexport class RestartRequiredError extends Error {\n constructor(readonly migration: Migration) {\n super(\n `migration ${migration.version} (${migration.name}) is restart-only and cannot be applied ` +\n `while a pushed platform boots: it is not safe to leave behind if this boot is rolled back. ` +\n `Restart the runtime on a build that carries it, then push again.`,\n );\n this.name = \"RestartRequiredError\";\n }\n}\n\n/**\n * Applies every migration this database has not reached yet, in order.\n *\n * Each migration and its version stamp commit together, so an interrupted run leaves the\n * database at the last version that fully applied — never half-migrated. Already-current\n * databases do no work and touch nothing.\n *\n * `swapPath` marks the caller as a booting pushed platform: the first pending migration\n * that is not `swapSafe` throws RestartRequiredError BEFORE anything is applied, so the\n * push is refused whole rather than partially landed.\n */\nexport function migrate(\n db: DatabaseSync,\n { swapPath = false }: { swapPath?: boolean } = {},\n): { from: number; to: number; applied: readonly string[] } {\n const from = schemaVersion(db);\n const pending = [...MIGRATIONS]\n .sort((a, b) => a.version - b.version)\n .filter((m) => m.version > from);\n if (swapPath) {\n const blocked = pending.find((m) => !m.swapSafe);\n if (blocked) throw new RestartRequiredError(blocked);\n }\n const applied: string[] = [];\n for (const m of pending) {\n db.exec(\"BEGIN\");\n try {\n m.up(db);\n // PRAGMA takes no bound parameter; the value is this file's own integer literal.\n db.exec(`PRAGMA user_version = ${m.version}`);\n db.exec(\"COMMIT\");\n } catch (err) {\n db.exec(\"ROLLBACK\");\n throw new Error(`migration ${m.version} (${m.name}) failed: ${String(err)}`, { cause: err });\n }\n applied.push(m.name);\n }\n return { from, to: schemaVersion(db), applied };\n}\n\n/**\n * Reverts the database DOWN to `targetVersion`, newest migration first.\n *\n * An operator's tool, and a destructive one — see each migration's `down` for what its rows\n * were. Deliberately not reachable from the swap path: a failed platform boot reverts the\n * PLATFORM, never the schema (module doc).\n *\n * Refused whole, before anything runs, if any migration in range declares no `down`: a\n * partial rollback would leave the database at a version whose meaning nobody wrote down.\n * Each `down` commits with its version stamp, so an interrupted run stops at a real version.\n */\nexport function rollbackTo(\n db: DatabaseSync,\n targetVersion: number,\n): { from: number; to: number; reverted: readonly string[] } {\n const from = schemaVersion(db);\n if (targetVersion < 0) throw new Error(`target version ${targetVersion} is negative`);\n if (targetVersion > from) {\n throw new Error(`database is at version ${from}, which is already below ${targetVersion}`);\n }\n const toRevert = [...MIGRATIONS]\n .filter((m) => m.version > targetVersion && m.version <= from)\n .sort((a, b) => b.version - a.version);\n const blocked = toRevert.find((m) => m.down === null);\n if (blocked) throw new IrreversibleMigrationError(blocked);\n\n const reverted: string[] = [];\n for (const m of toRevert) {\n db.exec(\"BEGIN\");\n try {\n m.down!(db);\n // Versions are contiguous, so the predecessor of `m` is exactly m.version - 1.\n db.exec(`PRAGMA user_version = ${m.version - 1}`);\n db.exec(\"COMMIT\");\n } catch (err) {\n db.exec(\"ROLLBACK\");\n throw new Error(`rollback of migration ${m.version} (${m.name}) failed: ${String(err)}`, {\n cause: err,\n });\n }\n reverted.push(m.name);\n }\n return { from, to: schemaVersion(db), reverted };\n}\n","/**\n * SQLite table-creation SQL.\n *\n * SQLite stores only indexes and aggregates: users / login sessions / Project authorization /\n * Agent & Session indexes / usage summaries / error records / UI preferences. Agent State,\n * Trace, and Workspace still follow the local directory-based storage rules.\n * Product not yet released: no migration branches — everything is CREATE IF NOT EXISTS, formed\n * once. The one exception: columns added to an existing table after release of a web.db are\n * ALTERed in by the idempotent per-column guard in database.ts (ensureColumn), since CREATE\n * TABLE IF NOT EXISTS never touches an existing table. A *reshaped* index follows the same\n * rule under a new name, with the superseded one dropped on open (idx_usage_session →\n * idx_usage_session_ts): CREATE INDEX IF NOT EXISTS never rebuilds an existing index either.\n */\n\nexport const MODEL_PROMOTIONS_SQL = `\nCREATE TABLE IF NOT EXISTS model_promotions ( -- NOT a cache rebuildable from files: the only record of a Project row's running promotion (.project_config.toml keeps the list price), written by preset seeding at Project creation, \"sync presets\" and Penguin Go authorization / sync, and read by cost; lost rows price usage at list until the next sync writes them back\n project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,\n provider TEXT NOT NULL,\n model_id TEXT NOT NULL,\n discount REAL NOT NULL CHECK (discount > 0 AND discount < 1), -- fraction off the row's list price: billed = list × (1 − discount)\n updated_at TEXT NOT NULL,\n PRIMARY KEY (project_id, provider, model_id)\n);`;\n\nexport const MODEL_PROVIDER_AUTH_TOKENS_SQL = `\nCREATE TABLE IF NOT EXISTS model_provider_auth_tokens ( -- Server-side OAuth refresh metadata for provider groups. The current request token remains in .project_config.toml as api_key; this table holds only the refresh material that must never be returned to the frontend or written into Project files.\n project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,\n provider TEXT NOT NULL,\n refresh_token TEXT NOT NULL,\n access_token_expires_at TEXT,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (project_id, provider)\n);`;\n\nexport const SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS users (\n user_id TEXT PRIMARY KEY, -- semantic id doubles as login name: ^[a-z][a-z0-9_-]{1,31}$\n password_hash TEXT NOT NULL, -- scrypt$N$r$p$salt$hash(base64)\n is_admin INTEGER NOT NULL DEFAULT 0, -- 1 for the built-in admin (seeded at startup)\n password_is_initial INTEGER NOT NULL DEFAULT 0, -- 1=initial password (seeded/admin-set); cleared once the user changes it\n display_name TEXT, -- nickname shown in place of user_id (1-32 characters); NULL = never set, surfaces show the id\n avatar TEXT, -- avatar as a data URL (image/png|jpeg|webp, <= 131072 characters); NULL = never set, surfaces draw the letter placeholder\n created_at TEXT NOT NULL\n);\n-- Server-side sessions backing the HttpOnly cookie: the cookie carries a 32-byte random\n-- token, the row stores only its sha256. A session outlives a restart (it is on disk), which\n-- is why the model is a row and not a signed statement.\nCREATE TABLE IF NOT EXISTS auth_sessions (\n token_hash TEXT PRIMARY KEY, -- sha256(token) hex; the cookie stores only the raw token\n user_id TEXT NOT NULL REFERENCES users(user_id) ON DELETE CASCADE,\n created_at TEXT NOT NULL,\n expires_at TEXT NOT NULL, -- 30-day sliding renewal, topped up in place when <29 days remain\n via TEXT -- 'password'|'desktop'|'setup'|'cli'|'remote'; NULL = legacy (password)\n);\n-- deleteExpired runs on every login and mint, deleteByUser on every admin reset; without\n-- these both scan the whole table.\nCREATE INDEX IF NOT EXISTS idx_auth_sessions_expires ON auth_sessions(expires_at);\nCREATE INDEX IF NOT EXISTS idx_auth_sessions_user ON auth_sessions(user_id);\n\nCREATE TABLE IF NOT EXISTS projects (\n project_id TEXT PRIMARY KEY, -- directory name doubles as id; display name lives in project_config.toml\n owner_user_id TEXT NOT NULL REFERENCES users(user_id),\n created_at TEXT NOT NULL\n);\nCREATE TABLE IF NOT EXISTS project_members ( -- member grants only; owners are not stored here\n project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,\n user_id TEXT NOT NULL REFERENCES users(user_id) ON DELETE CASCADE,\n created_at TEXT NOT NULL,\n PRIMARY KEY (project_id, user_id)\n);\n${MODEL_PROMOTIONS_SQL}\n${MODEL_PROVIDER_AUTH_TOKENS_SQL}\nCREATE TABLE IF NOT EXISTS agents ( -- index only; name/description live in system_config.yaml\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n created_at TEXT NOT NULL,\n PRIMARY KEY (project_id, agent_id)\n);\nCREATE TABLE IF NOT EXISTS sessions (\n session_id TEXT PRIMARY KEY,\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n provider TEXT NOT NULL, -- provider group of the session's CURRENT model (paired with model_id as a model reference; moves with each in-session switch)\n model_id TEXT NOT NULL, -- upstream model id of the current model (sent to MMSP as-is; never concatenate <provider>/<id>)\n workspace TEXT NOT NULL,\n approval_mode TEXT NOT NULL DEFAULT 'allow-all', -- allow-all|deny-all|read-only|always-ask\n thinking_level TEXT, -- level pinned for THIS session (none|low|medium|high|xhigh|max); NULL=not pinned, runs follow the Agent config\n title TEXT, -- auto-generated by the model after the first exchange; NULL=not yet (frontend shows \"New chat\")\n archived_at TEXT, -- the user archived it (ISO time); NULL = not archived by hand (the listing rule may still file it away)\n kept_at TEXT, -- \"keep in sidebar\": set when the user unarchives, cleared when they archive; NULL = the listing rule decides (a background source is archived, a user Session is active). Never written by a run.\n client TEXT, -- creating client: 'web' (created via the Web App) | 'cli' (adopted from a CLI Trace) | 'org' (company mode) | 'api' (an Agent API run); NULL = legacy row, treated as web\n has_trace INTEGER NOT NULL DEFAULT 0, -- cache: a Trace record exists (set at task start / adoption / subagent registration; lazily backfilled by list hydration)\n fork_count INTEGER NOT NULL DEFAULT 0, -- monotonically allocated child-fork number for this source Session; never decremented when a fork is deleted\n sandbox TEXT, -- the Session's sandbox policy snapshot (JSON SandboxSettings); NULL = legacy row, snapshotted at its next command\n last_active_at TEXT, -- last activity this server drove for the session (ISO; stamped once when a run starts and once when it ends, initialized to created_at); monotonic, never moves backwards; NULL only before openDatabase's one-time backfill\n created_at TEXT NOT NULL\n); -- the Session's SOURCE (user/api/schedule/subagent/cli/company) is NOT stored: session_meta in the Trace is the single source of truth (see runtime/session-sources.ts); \"client\" is a different, DB-only axis (who created the row), read for the source only where the Trace records none ('org' → company)\nCREATE INDEX IF NOT EXISTS idx_sessions_agent_created ON sessions(project_id, agent_id, created_at DESC);\nCREATE TABLE IF NOT EXISTS usage_records (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n ts TEXT NOT NULL,\n date TEXT NOT NULL, -- local date yyyy-mm-dd (aggregation key; same convention as Trace date directories)\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n session_id TEXT NOT NULL, -- top-level Session (child-session usage counts toward its main Session)\n origin_session_id TEXT, -- immediate source child Session (last of the origin chain); NULL=main session\n provider TEXT NOT NULL, -- provider group: paired with model_id as the attribution key; always GROUP BY provider, model_id\n model_id TEXT NOT NULL, -- upstream model id (paired with provider; same model_id across providers aggregates separately)\n cache_read INTEGER NOT NULL,\n cache_write INTEGER NOT NULL,\n output INTEGER NOT NULL,\n total INTEGER NOT NULL, -- from token_usage.request (one row per Request)\n status TEXT NOT NULL DEFAULT 'completed' -- request outcome: completed=success (with tokens); others=failure (0 tokens, for success rate)\n); -- cost is not stored: computed at query time from current pricing\nCREATE INDEX IF NOT EXISTS idx_usage_project_date ON usage_records(project_id, date);\nCREATE INDEX IF NOT EXISTS idx_usage_session_ts ON usage_records(session_id, ts); -- (session_id) alone was idx_usage_session (dropped on open): ts makes the last_active_at backfill's MAX(ts) a covering index scan instead of a random row lookup per usage record\nCREATE TABLE IF NOT EXISTS error_records ( -- server-side error capture (the Costs page's \"Errors\" tab)\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n ts TEXT NOT NULL,\n date TEXT NOT NULL, -- local date yyyy-mm-dd (same convention as usage_records)\n project_id TEXT, -- nullable: sign-in/registration and process-level errors have no Project context\n agent_id TEXT,\n session_id TEXT,\n source TEXT NOT NULL, -- http | session | usage | title | subagent | process | llm | environment | compaction | schedule | messaging | organization | id_suggest | plugin\n kind TEXT NOT NULL, -- expected (HttpError, business 4xx) | unexpected (500/runtime)\n code TEXT NOT NULL, -- HttpError.code / internal / session_run_failed / ...\n status INTEGER, -- HTTP status code; NULL for non-HTTP sources\n message TEXT NOT NULL -- truncated to 500 chars (no stack stored: stacks go to logs only)\n);\nCREATE INDEX IF NOT EXISTS idx_error_project_date ON error_records(project_id, date);\nCREATE TABLE IF NOT EXISTS schedule_state ( -- schedule runtime state (files are declarative intent; the system never writes back)\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n name TEXT NOT NULL, -- file name (without .toml) doubles as the identifier\n creator_user_id TEXT, -- creator (recorded on API create; hand-edited file reconciliation falls back to the Project owner)\n start_at_ms INTEGER NOT NULL, -- defines identity: a start_at change counts as a new task instance, resetting fire state\n def_hash TEXT NOT NULL, -- file content fingerprint: any change clears the invalid flag (the file takes effect again after edits)\n last_slot_ms INTEGER, -- latest due slot already consumed (advances on fire or skip; no re-fire across restarts)\n last_fired_at TEXT, -- last actual fire time (for display)\n fired_once INTEGER NOT NULL DEFAULT 0, -- one-shot task has fired\n missed INTEGER NOT NULL DEFAULT 0, -- one-shot task was missed (flagged by startup/registration reconciliation; not backfilled)\n invalid_reason TEXT, -- invalidation reason (e.g. the bound Session was deleted); NULL=healthy\n PRIMARY KEY (project_id, agent_id, name)\n);\nCREATE TABLE IF NOT EXISTS messaging_bindings ( -- Session ↔ messaging-channel bot bindings (runtime/messaging/ holds the long connections)\n session_id TEXT NOT NULL, -- a Session keeps at most one saved config PER channel (composite PK below); at most ONE of them is enabled at a time (route-enforced, 409 another_channel_enabled), and enabling is what binds the account to this Session\n channel TEXT NOT NULL, -- messaging channel discriminator ('feishu' | 'telegram' | 'qq' | 'wechat')\n account_id TEXT NOT NULL, -- channel-scoped bot/app identity (feishu: app_id; telegram: the bot token's numeric id; qq: the bot's App ID; wechat: the scanned bot id); NOT unique — any number of Sessions may keep the same account saved side by side, each with its own config and last-chat memory; only ENABLING is exclusive (route-enforced, 409 account_enabled_elsewhere: one account has one event stream, two live connections on it would race)\n config_json TEXT NOT NULL, -- channel-specific credentials/config JSON (feishu: appId/appSecret/baseDomain; telegram: botToken; qq: appId/appSecret; wechat: botId/botToken/baseUrl/userId); secrets plaintext at rest (same trade-off as the proxy address in server_settings), masked at every API surface; a cleared secret is stored as \"\" (the row and its account identity stay)\n enabled INTEGER NOT NULL DEFAULT 0, -- INTENT state (the connection's runtime status stays in memory): new bindings start disabled — saving credentials never opens a connection, the explicit state toggle does\n line_per_message INTEGER NOT NULL DEFAULT 0, -- delivery preference: 1 = every non-blank line of a relayed assistant reply is sent as its own message (a reply written as spoken lines arrives as spoken lines), 0 = one message per reply. Channel-agnostic, so it lives here rather than in config_json, which each connector owns\n final_reply_only INTEGER NOT NULL DEFAULT 0, -- delivery preference: 1 = a run's intermediate assistant messages are held and only its LAST completed one is sent, at the run's end, 0 = every completed assistant message mirrors the moment it completes. Channel-agnostic like the column above and independent of it: with both set, that one final text is the one split per line\n render_markdown INTEGER NOT NULL DEFAULT 1, -- delivery preference: 1 = a relayed reply's Markdown is rendered in the channel's own markup (Telegram HTML, a Feishu card, QQ markdown, the subset WeChat itself reads), 0 = the reply's characters are sent as written. DEFAULT 1 because the model writes Markdown and showing it raw was the defect; the per-channel subsets and the plain-text fallback live in the connectors\n last_chat_id TEXT, -- most recent inbound chat (NULL until the bot is messaged once; replies and test messages target it); CONNECTOR-OPAQUE, not necessarily a bare chat id — telegram appends the forum topic (see telegram-connector.ts chatRefOf), so only that channel's connector may interpret it\n last_chat_is_direct INTEGER NOT NULL DEFAULT 1, -- 1 = direct chat (reply by chat id), 0 = group chat (prefer reply-to-message)\n last_inbound_message_id TEXT, -- channel id of the most recently PROCESSED inbound message (NULL until one arrives); the durable half of the bridge's redelivery guard, so a channel replaying an event this server already turned into a Task after a restart does not run it twice\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (session_id, channel)\n);\nCREATE INDEX IF NOT EXISTS idx_messaging_by_account ON messaging_bindings(channel, account_id); -- serves the enable guard's by-account lookup; deliberately NOT unique, unlike its predecessor idx_messaging_account (dropped on open) which made an account exclusive to one Session forever\nCREATE TABLE IF NOT EXISTS messaging_conversations ( -- per-(bot, chat) delivery state a connector must keep across reconnects and restarts (WeChat: the context token, its send count, held replies); deleted once no messaging_bindings row references (channel, account_id) — see MessagingBindingsRepo\n channel TEXT NOT NULL, -- messaging channel discriminator (only 'wechat' writes rows today)\n account_id TEXT NOT NULL, -- the bot, as messaging_bindings.account_id names it\n chat_id TEXT NOT NULL, -- the connector's own chat id (wechat: the user's ilink_user_id)\n state_json TEXT NOT NULL, -- connector-owned JSON (wechat: {contextToken, tokenAt, spent, held, heldSince}); the token is a conversation handle at rest, same trade-off as config_json's credentials\n updated_at TEXT NOT NULL,\n PRIMARY KEY (channel, account_id, chat_id)\n);\nCREATE TABLE IF NOT EXISTS ui_prefs (\n user_id TEXT PRIMARY KEY REFERENCES users(user_id) ON DELETE CASCADE,\n prefs_json TEXT NOT NULL -- {theme?, lastProjectId?, ...} free-form JSON\n);\nCREATE TABLE IF NOT EXISTS browser_extensions ( -- one row per Chrome paired to a user (builtin-browser/extension-pairing.ts): the PenguinHarness Browser extension's long-lived credential, stored only hashed; NOT rebuildable — a lost row means pairing that Chrome again\n extension_id TEXT PRIMARY KEY, -- random id shown in the Web App's list\n user_id TEXT NOT NULL REFERENCES users(user_id) ON DELETE CASCADE,\n token_hash TEXT NOT NULL UNIQUE, -- sha256(token) hex; the extension alone holds the token\n name TEXT NOT NULL, -- how the extension names this Chrome (\"Chrome 130 on macOS\")\n version TEXT NOT NULL, -- the extension's version, as of its last hello\n created_at TEXT NOT NULL,\n last_seen_at TEXT, -- last connect or disconnect; NULL = never connected\n revoked_at TEXT -- set by Revoke; a revoked token's socket is closed 4003\n);\nCREATE INDEX IF NOT EXISTS idx_browser_extensions_user ON browser_extensions(user_id);\nCREATE TABLE IF NOT EXISTS agent_api ( -- per-Agent public API settings (amsp/routes.ts); NOT rebuildable from files\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n enabled INTEGER NOT NULL DEFAULT 0, -- the API tab's switch; off = every /api/amsp request for it is 404 agent_not_found\n open INTEGER NOT NULL DEFAULT 0, -- keyless access: a request without Authorization is accepted; off = 401 unauthorized\n approval_mode TEXT NOT NULL DEFAULT 'allow-all', -- copied onto each new API Session\n provider TEXT, -- NULL pair follows the Project default model\n model_id TEXT,\n thinking_level TEXT, -- NULL follows Agent/Project configuration\n workspace TEXT, -- NULL creates a temporary Workspace\n max_concurrent_runs INTEGER NOT NULL DEFAULT 4,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (project_id, agent_id)\n);\nCREATE TABLE IF NOT EXISTS agent_api_keys ( -- one row per key the API tab or the CLI minted; the caller alone holds the key\n key_id TEXT PRIMARY KEY, -- 16 base64url chars, shown in the list\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n token_hash TEXT NOT NULL UNIQUE, -- sha256(key) hex\n prefix TEXT NOT NULL, -- the key's first 16 characters (\"penguin_\" + 8), shown in the list\n name TEXT NOT NULL, -- 1-64 characters\n created_by TEXT NOT NULL REFERENCES users(user_id),\n created_at TEXT NOT NULL,\n last_used_at TEXT -- stamped once per run request that authenticated with it; NULL = never\n);\nCREATE INDEX IF NOT EXISTS idx_agent_api_keys_agent ON agent_api_keys(project_id, agent_id);\nCREATE TABLE IF NOT EXISTS server_settings ( -- admin-level server-global settings (GET/PUT /api/admin/settings)\n key TEXT PRIMARY KEY, -- setting name, e.g. 'proxy_for_app'\n value TEXT NOT NULL -- JSON-encoded value; an absent row means the setting's built-in default\n);\nCREATE TABLE IF NOT EXISTS machine ( -- this server's OWN identity, minted here and never assigned from outside (what 'penguin server status' reports)\n singleton INTEGER PRIMARY KEY CHECK (singleton = 1), -- exactly one row, enforced by the schema rather than by convention\n machine_id TEXT NOT NULL -- 16 base64url characters; what every stored reference to this machine points at\n);\nCREATE TABLE IF NOT EXISTS machines ( -- one row per machine this server installed on or reached (machines/service.ts)\n address TEXT PRIMARY KEY, -- 'ssh:<alias>'\n machine_id TEXT, -- that machine's own id, once heard\n version TEXT, -- what this server last installed there; NULL = never\n installed_at TEXT,\n session_pid INTEGER, -- the ssh session this server holds to it; what a successor App closes after a hot swap\n remote_port INTEGER, -- its server's port over there, as of the last connect\n platform TEXT -- linux | darwin | win32, as the install found it: the shell dialect the status probe speaks to it in\n);\nCREATE TABLE IF NOT EXISTS machine_project ( -- which machines a Project uses; no row = none yet. Follows the Project out, like project_members\n project_id TEXT PRIMARY KEY REFERENCES projects(project_id) ON DELETE CASCADE,\n addresses TEXT NOT NULL -- JSON array of 'ssh:<alias>'\n);\nCREATE TABLE IF NOT EXISTS trace_files ( -- DERIVED CACHE of the on-disk Trace tree (services/trace-index.ts): the directories stay the single source of truth, every row is rebuildable from disk, and a row is never authority for absence — consumers reconcile + retry on a miss, so a stale index costs one extra scan, never a false 404\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n session_id TEXT NOT NULL,\n file_index INTEGER NOT NULL, -- shard index NNN of <session_id>_NNN.jsonl (name/path are reconstructed from the row, never stored: the data root may move)\n date TEXT NOT NULL, -- date directory name (local yyyy-mm-dd)\n size_bytes INTEGER NOT NULL, -- last observed size (listings stat-refresh the returned page and write back; an actively-appended shard may lag in between)\n page_stats TEXT, -- cached message-window scan state at this shard's END (services/message-window.ts ShardPrefixRecord JSON); immutable shards only, NULL = not yet computed, nulled whenever size_bytes changes\n PRIMARY KEY (project_id, agent_id, session_id, file_index)\n);\nCREATE INDEX IF NOT EXISTS idx_trace_files_agent_date ON trace_files(project_id, agent_id, date);\nCREATE INDEX IF NOT EXISTS idx_trace_files_session ON trace_files(session_id);\nCREATE TABLE IF NOT EXISTS trace_sessions ( -- per-session facts read ONCE at registration from the earliest shard's head (same derived-cache rules as trace_files; listing needs zero head-reads)\n session_id TEXT PRIMARY KEY,\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n source TEXT, -- session_meta source as the head carried it: 'user' | 'api' | 'schedule' | 'subagent' | 'cli' | 'company'; NULL = the head records none (written before the source was required: read as 'company' for an 'org' row, else 'user' — readRecordedSource); 'benchmark' from older rows reads as 'cli' (normalizeSessionSource; meaningless while meta_read = 0)\n workspace TEXT NOT NULL DEFAULT '',\n title TEXT, -- first-prompt fallback title (sessions.title always wins when present)\n provider TEXT, -- model reference from session_meta: the model the Session was created on (CLI adoption reads it from here, and the runtime's own answer corrects the row at load; NULL = meta unreadable / legacy without provider)\n model_id TEXT,\n first_ts TEXT, -- first record's timestamp (adoption's createdAt fallback when the id embeds no time)\n meta_read INTEGER NOT NULL DEFAULT 0 -- 1 once the head parsed; 0 = facts unknown, retried by the next reconcile that touches the session\n);\nCREATE INDEX IF NOT EXISTS idx_trace_sessions_agent ON trace_sessions(project_id, agent_id);\nCREATE TABLE IF NOT EXISTS org_sessions ( -- DERIVED CACHE (company mode): desk sessions, rebuilt from each organization's desks.toml (current + previous); trigger_hop is mention-chain accounting and reads 0 after a rebuild\n session_id TEXT PRIMARY KEY,\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n current INTEGER NOT NULL DEFAULT 1,\n trigger_hop INTEGER NOT NULL DEFAULT 0\n);\nCREATE INDEX IF NOT EXISTS idx_org_sessions_org ON org_sessions(project_id, org_id);\nCREATE TABLE IF NOT EXISTS org_ticket_sessions ( -- DERIVED CACHE (company mode): ticket <-> contributing session, rebuilt from each ticket's Sessions header\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n ticket_id TEXT NOT NULL,\n session_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n trigger_hop INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (project_id, org_id, ticket_id, session_id)\n);\nCREATE INDEX IF NOT EXISTS idx_org_ticket_sessions_session ON org_ticket_sessions(session_id);\nCREATE TABLE IF NOT EXISTS org_calendar_state ( -- calendar run state (company mode; the files are declarative intent), same rules as schedule_state\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n name TEXT NOT NULL,\n start_at_ms INTEGER NOT NULL,\n def_hash TEXT NOT NULL,\n last_slot_ms INTEGER,\n last_fired_at TEXT,\n fired_once INTEGER NOT NULL DEFAULT 0,\n missed INTEGER NOT NULL DEFAULT 0,\n invalid_reason TEXT,\n last_outcome TEXT,\n PRIMARY KEY (project_id, org_id, agent_id, name)\n);\nCREATE TABLE IF NOT EXISTS org_ticket_state ( -- DERIVED CACHE (company mode): the last (status, owner, blocked) seen per ticket, so a change is notified once; rebuilt silently from the ticket files\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n ticket_id TEXT NOT NULL,\n status TEXT NOT NULL,\n owner TEXT NOT NULL DEFAULT '',\n blocked TEXT NOT NULL DEFAULT '',\n blocked_by TEXT NOT NULL DEFAULT '',\n PRIMARY KEY (project_id, org_id, ticket_id)\n);\nCREATE TABLE IF NOT EXISTS org_channel_state ( -- DERIVED CACHE (company mode): tail-scan byte cursor per channel and day file\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n channel_id TEXT NOT NULL,\n date TEXT NOT NULL,\n offset_bytes INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (project_id, org_id, channel_id, date)\n);\nCREATE TABLE IF NOT EXISTS org_channel_reads ( -- user data (company mode): each user's read cursor in one channel\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n channel_id TEXT NOT NULL,\n user_id TEXT NOT NULL,\n last_read_id TEXT NOT NULL,\n PRIMARY KEY (project_id, org_id, channel_id, user_id)\n);\nCREATE TABLE IF NOT EXISTS org_budget_state ( -- DERIVED CACHE (company mode): warn / pause marks per employee and period, recomputed from usage and the chart's budgets\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n period TEXT NOT NULL,\n warned_at TEXT,\n paused_at TEXT,\n PRIMARY KEY (project_id, org_id, agent_id, period)\n);\nCREATE TABLE IF NOT EXISTS org_desk_notices ( -- DERIVED CACHE (company mode): ticket changes waiting for an employee's next calendar sweep; dropping it loses only the digests not delivered yet\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n ticket_id TEXT NOT NULL,\n change TEXT NOT NULL,\n at TEXT NOT NULL\n);\nCREATE INDEX IF NOT EXISTS idx_org_desk_notices_agent ON org_desk_notices(project_id, org_id, agent_id);\n`;\n"],"mappings":";AAOA,SAAS,iBAAiB;AAC1B,OAAO,UAAU;;;ACoEV,IAAM,aAAmC;AAAA,EAC9C;AAAA,IACE,SAAS;AAAA,IACT,MAAM;AAAA;AAAA;AAAA;AAAA,IAIN,UAAU;AAAA,IACV,GAAG,IAAI;AAIL,SAAG,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,OAkBP;AAAA,IACH;AAAA;AAAA;AAAA;AAAA,IAIA,KAAK,IAAI;AACP,SAAG,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA,OAKP;AAAA,IACH;AAAA,EACF;AAAA,EACA;AAAA,IACE,SAAS;AAAA,IACT,MAAM;AAAA;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A4B;AAKvF,eAAa,IAAI,sBAAsB,mBAAmB,4BAA4B;AACtF,eAAa,IAAI,sBAAsB,2BAA2B,MAAM;AAIxE,KAAG,KAAK,wCAAwC;AAUhD,KAAG,KAAK,4CAA4C;AACpD,sBAAoB,EAAE;AAGtB,UAAQ,EAAE;AACV,SAAO;AACT;AAYA,SAAS,oBAAoB,IAAwB;AACnD,KAAG,KAAK,OAAO;AACf,MAAI;AACF,QAAI,aAAa,IAAI,YAAY,kBAAkB,MAAM,GAAG;AAC1D,SAAG;AAAA,QACD;AAAA;AAAA;AAAA;AAAA,MAIF;AAAA,IACF;AACA,OAAG,KAAK,QAAQ;AAAA,EAClB,SAAS,KAAK;AACZ,OAAG,KAAK,UAAU;AAClB,UAAM;AAAA,EACR;AACF;AAOO,SAAS,aACd,IACA,OACA,QACA,KACS;AACT,QAAM,OAAO,GAAG,QAAQ,qBAAqB,KAAK,GAAG,EAAE,IAAI;AAC3D,MAAI,KAAK,KAAK,CAAC,MAAM,EAAE,SAAS,MAAM,EAAG,QAAO;AAChD,KAAG,KAAK,eAAe,KAAK,eAAe,MAAM,IAAI,GAAG,EAAE;AAC1D,SAAO;AACT;","names":[]}
@@ -1,9 +1,6 @@
1
- import {
2
- HttpError
3
- } from "./chunk-Q4ON2L6E.js";
4
1
  import {
5
2
  sessionTokenHash
6
- } from "./chunk-TOOTEEM4.js";
3
+ } from "./chunk-G7GY7PJU.js";
7
4
  import {
8
5
  __decorateElement,
9
6
  __decoratorStart,
@@ -113,9 +110,53 @@ function tokensEqual(a, b) {
113
110
  return timingSafeEqual2(digest(a), digest(b));
114
111
  }
115
112
 
113
+ // src/http/errors.ts
114
+ var HttpError = class extends Error {
115
+ constructor(status, code, message, retryAfterSeconds, details) {
116
+ super(message);
117
+ this.status = status;
118
+ this.code = code;
119
+ this.retryAfterSeconds = retryAfterSeconds;
120
+ this.details = details;
121
+ this.name = "HttpError";
122
+ }
123
+ status;
124
+ code;
125
+ retryAfterSeconds;
126
+ details;
127
+ };
128
+ function badRequest(message) {
129
+ return new HttpError(400, "bad_request", message);
130
+ }
131
+ function errorBody(code, message, details) {
132
+ return { error: { code, message, ...details !== void 0 ? { details } : {} } };
133
+ }
134
+ function isMissingCredential(err) {
135
+ const message = err instanceof Error ? err.message : String(err);
136
+ return /missing credentials|api[_ ]?key/i.test(message);
137
+ }
138
+ function modelCredentialMissing(modelId) {
139
+ return new HttpError(
140
+ 400,
141
+ "model_credential_missing",
142
+ `Model ${modelId} has no API key yet. Configure it on the Models page first.`
143
+ );
144
+ }
145
+ function handleError(err, c) {
146
+ if (err instanceof HttpError) {
147
+ if (err.retryAfterSeconds !== void 0) {
148
+ c.header("Retry-After", String(err.retryAfterSeconds));
149
+ }
150
+ return c.json(errorBody(err.code, err.message, err.details), err.status);
151
+ }
152
+ console.error(`[server] Unhandled exception: ${err.stack ?? err.message}`);
153
+ return c.json(errorBody("internal", "Internal server error."), 500);
154
+ }
155
+
116
156
  // src/auth/service.ts
117
157
  import { Component as Component2, Use, Interface as Interface2 } from "@prismshadow/penguin-core/kernel";
118
158
  var MIN_PASSWORD_LENGTH = 8;
159
+ var REMOTE_SESSION_TTL_MS = 60 * 6e4;
119
160
  var ADMIN_USER_ID = "admin";
120
161
  var LOGIN_FREE_ATTEMPTS = 5;
121
162
  var LOGIN_BACKOFF_START_MS = 1e3;
@@ -302,6 +343,22 @@ var AuthService = class {
302
343
  }
303
344
  return { user: toUserInfo(row), token: this.issueSession(row.userId, "desktop") };
304
345
  }
346
+ issueRemoteSession() {
347
+ const row = this.users.findById(ADMIN_USER_ID);
348
+ if (!row) {
349
+ throw new HttpError(500, "internal", "Built-in admin has not been seeded.");
350
+ }
351
+ const maxAgeSeconds = Math.floor(REMOTE_SESSION_TTL_MS / 1e3);
352
+ return {
353
+ ...this.authSessions.issue({
354
+ userId: row.userId,
355
+ via: "remote",
356
+ now: this.clock.now(),
357
+ ttlMs: REMOTE_SESSION_TTL_MS
358
+ }),
359
+ maxAgeSeconds
360
+ };
361
+ }
305
362
  /** Self password change (user settings): validates the old password first; the current session stays valid. */
306
363
  async changePassword(userId, oldPassword, newPassword) {
307
364
  const row = this.users.findById(userId);
@@ -379,7 +436,7 @@ var AuthService = class {
379
436
  this.authSessions.touch(tokenHash, new Date(now.getTime() + this.sessionTtlMs).toISOString());
380
437
  renewed = true;
381
438
  }
382
- const via = session.via === "desktop" ? "desktop" : session.via === "setup" ? "setup" : "password";
439
+ const via = session.via === "remote" ? "token" : session.via === "desktop" ? "desktop" : session.via === "setup" ? "setup" : "password";
383
440
  return { user, via, renewed };
384
441
  }
385
442
  /**
@@ -423,6 +480,12 @@ InitialProjectProvisioner = __decorateElement(_init4, 0, "InitialProjectProvisio
423
480
  __runInitializers(_init4, 1, InitialProjectProvisioner);
424
481
 
425
482
  export {
483
+ HttpError,
484
+ badRequest,
485
+ errorBody,
486
+ isMissingCredential,
487
+ modelCredentialMissing,
488
+ handleError,
426
489
  mintApiToken,
427
490
  storeApiToken,
428
491
  hashPassword,
@@ -435,4 +498,4 @@ export {
435
498
  AuthService,
436
499
  InitialProjectProvisioner
437
500
  };
438
- //# sourceMappingURL=chunk-5Z4UCHDB.js.map
501
+ //# sourceMappingURL=chunk-D3JNA6ZI.js.map