@polycode-projects/the-mechanical-code-talker 6.0.10 → 6.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@polycode-projects/the-mechanical-code-talker",
3
- "version": "6.0.10",
3
+ "version": "6.0.11",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "The Mechanical Code Talker (tmct) — a tolerant, offline, $0 chat surface that guides you toward precision queries about a software repository. ELIZA/PARRY-style but domain-obsessed with code. No model calls; indexes a repo on request (tmct index) or reads any producer's graph.",
@@ -205,6 +205,10 @@
205
205
  "build:wink-vendor": "node scripts/build-wink-vendor.mjs",
206
206
  "build:three-vendor": "node scripts/build-three-vendor.mjs",
207
207
  "build:chat-seed": "node scripts/build-chat-seed.mjs",
208
+ "build:seed-sqlite:mid": "node scripts/build-seed-sqlite.mjs mid",
209
+ "build:seed-sqlite:xl": "node scripts/build-seed-sqlite.mjs xl",
210
+ "build:seed-sqlite": "node scripts/build-seed-sqlite.mjs",
211
+ "verify:image": "bash scripts/verify-image-local.sh",
208
212
  "build:demo-graph": "node scripts/build-demo-graph.mjs",
209
213
  "build:demo-pack": "node scripts/build-demo-pack.mjs",
210
214
  "build:demo-sprites-pack": "node scripts/build-demo-sprites-pack.mjs",
@@ -712,6 +712,27 @@ export function closeSqliteMemoryStore(handle) {
712
712
  if (isSqliteHandle(handle)) handle.db.close();
713
713
  }
714
714
 
715
+ /** Open a pre-built seed file READ-ONLY: the same tables
716
+ * `createSqliteMemoryStore` writes, opened without the DDL, the backfills or
717
+ * the WAL pragma, so the file itself never changes and it can sit on a
718
+ * read-only image layer. This is the base layer a
719
+ * `wrapRowBackendOverSqliteSeed` handle assembles under a session's own rows.
720
+ * No row-backend methods are attached: nothing may ever write here. Close it
721
+ * with `closeSqliteMemoryStore`. */
722
+ export async function openSqliteSeedStore(dbPath) {
723
+ installSqliteWarningFilter();
724
+ const { DatabaseSync } = await import("node:sqlite");
725
+ try {
726
+ return { backend: BACKEND_SQLITE, db: new DatabaseSync(dbPath, { readOnly: true }), dbPath, readOnly: true };
727
+ } catch (cause) {
728
+ // A seed file whose writer never closed keeps a live -wal beside it, and
729
+ // recovering that needs write access the caller does not have. Say which
730
+ // file and say read-only, or the raw sqlite message sends the reader
731
+ // looking for a missing file that is right there.
732
+ throw new BackendUnavailable(`could not open the seed store ${dbPath} read-only: ${cause.message}`, { cause });
733
+ }
734
+ }
735
+
715
736
  // ---- Backend D — a consumer's own row store ------------------------------
716
737
  // The consumer constructs the store (row-backend.mjs is the contract) and
717
738
  // tmct binds it into the same `memoryDir` token every memory call threads.
@@ -738,17 +759,39 @@ const ROW_NODE_ID_KEY = "nodeId";
738
759
  /** Bind a row backend as a `memoryDir` token: `{ backend: "row", impl,
739
760
  * cachedPayload, basePayload }`. `basePayload` is the read-only seed overlay;
740
761
  * `onOversizedRow` is the projection's posture for a record over the per-row
741
- * cap ("throw", the default, or "drop"), and `log` takes the drop notices. */
742
- export function wrapRowBackend(impl, { basePayload = null, onOversizedRow = "throw", log = undefined } = {}) {
762
+ * cap ("throw", the default, or "drop"), and `log` takes the drop notices.
763
+ *
764
+ * `sqliteSeedStore` is the same seed overlay held as an OPEN sqlite store
765
+ * (`openSqliteSeedStore`) instead of a parsed payload — see
766
+ * `wrapRowBackendOverSqliteSeed`, the entry point that takes one.
767
+ * `sqliteSeedOverlayRows` are rows that layer over that seed and under the
768
+ * session's own (a turn's retrieved corpus subgraph), read-only exactly as
769
+ * the seed is. */
770
+ export function wrapRowBackend(impl, {
771
+ basePayload = null,
772
+ sqliteSeedStore = null,
773
+ sqliteSeedOverlayRows = null,
774
+ onOversizedRow = "throw",
775
+ log = undefined,
776
+ } = {}) {
743
777
  const problems = rowBackendProblems(impl);
744
778
  if (problems.length) {
745
779
  throw new BackendRejected(`not a memory row backend: ${problems.join("; ")}`);
746
780
  }
781
+ if (sqliteSeedStore && !isSqliteHandle(sqliteSeedStore)) {
782
+ throw new BackendRejected("sqliteSeedStore must be an open sqlite store handle (openSqliteSeedStore)");
783
+ }
784
+ if (sqliteSeedStore && basePayload) {
785
+ throw new BackendRejected("a handle takes its seed either as a basePayload or as a sqliteSeedStore, never both");
786
+ }
747
787
  return {
748
788
  backend: BACKEND_ROW,
749
789
  impl,
750
790
  cachedPayload: null,
751
791
  basePayload: cloneMemoryPayload(basePayload),
792
+ sqliteSeedStore,
793
+ sqliteSeedOverlayRows: sqliteSeedOverlayRows ? [...sqliteSeedOverlayRows] : null,
794
+ sqliteSeedKeyOrds: null,
752
795
  baseRows: null,
753
796
  storedRows: null,
754
797
  onOversizedRow,
@@ -756,6 +799,16 @@ export function wrapRowBackend(impl, { basePayload = null, onOversizedRow = "thr
756
799
  };
757
800
  }
758
801
 
802
+ /** `wrapRowBackend` over a seed held as an open read-only sqlite store. The
803
+ * seed's rows stream into assembly one at a time and the keys the session may
804
+ * never write come off the store's own key columns, so a 60k-fact seed is
805
+ * never materialized as a row array: the assembled payload is the only copy
806
+ * of it this process holds. `overlayRows` layer over the seed and under the
807
+ * session's own rows. */
808
+ export function wrapRowBackendOverSqliteSeed(impl, sqliteSeedStore, { overlayRows = null, onOversizedRow = "throw", log = undefined } = {}) {
809
+ return wrapRowBackend(impl, { sqliteSeedStore, sqliteSeedOverlayRows: overlayRows, onOversizedRow, log });
810
+ }
811
+
759
812
  /** Drain whatever `readRows()` returned: the contract allows an array or an
760
813
  * async iterable, so a paginating backend can stream its pages. */
761
814
  async function collectRows(source) {
@@ -779,7 +832,12 @@ function overlayRows(baseRows, sessionRows) {
779
832
  * session store does not already hold a row for. */
780
833
  function seedOnlyKeys(handle) {
781
834
  const sessionKeys = new Set(handle.storedRows.map((r) => r.rowKey));
782
- return new Set(handle.baseRows.map((r) => r.rowKey).filter((key) => !sessionKeys.has(key)));
835
+ const baseKeys = handle.sqliteSeedStore
836
+ ? sqliteSeedKeyOrds(handle).keys()
837
+ : handle.baseRows.map((r) => r.rowKey);
838
+ const seedOnly = new Set();
839
+ for (const key of baseKeys) if (!sessionKeys.has(key)) seedOnly.add(key);
840
+ return seedOnly;
783
841
  }
784
842
 
785
843
  async function readRowMeta(handle, key, fallback) {
@@ -796,20 +854,23 @@ async function readRowPayload(handle) {
796
854
  if (!handle.cachedPayload) {
797
855
  const empty = emptyMemory();
798
856
  const stored = await collectRows(handle.impl.readRows());
799
- // "keep": the base overlay's own rows never reach the wire (persistRowPayload
800
- // excludes every seed key from every write via seedOnlyKeys below), so the
801
- // per-row byte cap that protects a real backend's real item-size limit has
802
- // nothing to protect here — capping it would silently drop a real corpus
803
- // band's own high-fan-out property (one edge per fact is normal, not a
804
- // pathology) and break every read that depends on it.
805
- handle.baseRows = payloadToRows(handle.basePayload || empty, { onOversizedRow: "keep" });
806
857
  handle.storedRows = stored.filter((row) => row?.rowClass !== BOOKKEEPING_ROW_CLASS);
807
- handle.cachedPayload = rowsToPayload(overlayRows(handle.baseRows, handle.storedRows), {
808
- meta: {
809
- memory: await readRowMeta(handle, ROW_META_MEMORY_KEY, handle.basePayload?.memory ?? empty.memory),
810
- prefixes: await readRowMeta(handle, ROW_META_PREFIXES_KEY, handle.basePayload?.prefixes ?? empty.prefixes),
811
- },
812
- });
858
+ const meta = {
859
+ memory: await readRowMeta(handle, ROW_META_MEMORY_KEY, seedScalar(handle, "memory", empty.memory)),
860
+ prefixes: await readRowMeta(handle, ROW_META_PREFIXES_KEY, seedScalar(handle, "prefixes", empty.prefixes)),
861
+ };
862
+ if (handle.sqliteSeedStore) {
863
+ handle.cachedPayload = assembleSqliteSeededPayload(handle, meta);
864
+ } else {
865
+ // "keep": the base overlay's own rows never reach the wire (persistRowPayload
866
+ // excludes every seed key from every write via seedOnlyKeys below), so the
867
+ // per-row byte cap that protects a real backend's real item-size limit has
868
+ // nothing to protect here — capping it would silently drop a real corpus
869
+ // band's own high-fan-out property (one edge per fact is normal, not a
870
+ // pathology) and break every read that depends on it.
871
+ handle.baseRows = payloadToRows(handle.basePayload || empty, { onOversizedRow: "keep" });
872
+ handle.cachedPayload = rowsToPayload(overlayRows(handle.baseRows, handle.storedRows), { meta });
873
+ }
813
874
  }
814
875
  return cloneJson(handle.cachedPayload);
815
876
  }
@@ -843,15 +904,18 @@ function movedBeyondAuditStamp(beforeRow, row) {
843
904
  * from a payload that never landed. */
844
905
  async function persistRowPayload(handle, payload) {
845
906
  await readRowPayload(handle);
846
- const before = overlayRows(handle.baseRows, handle.storedRows);
907
+ const seedKeys = seedOnlyKeys(handle);
908
+ // On the sqlite path the seed is out of BOTH sides of the diff: the rows it
909
+ // holds are exactly the keys no write may touch, so projecting them would
910
+ // materialize the whole seed only to filter every row of it back out.
911
+ const before = handle.sqliteSeedStore ? handle.storedRows : overlayRows(handle.baseRows, handle.storedRows);
847
912
  const beforeByKey = new Map(before.map((row) => [row.rowKey, row]));
848
- const after = payloadToRows(payload, {
849
- priorRows: before,
913
+ const after = payloadToRows(handle.sqliteSeedStore ? payloadWithoutRowKeys(payload, seedKeys) : payload, {
914
+ priorRows: handle.sqliteSeedStore ? sqliteSeedPriorRows(handle) : before,
850
915
  onOversizedRow: handle.onOversizedRow,
851
916
  ...(handle.log ? { log: handle.log } : {}),
852
917
  });
853
918
  const { puts, deletes } = diffRows(before, after);
854
- const seedKeys = seedOnlyKeys(handle);
855
919
  const writes = puts
856
920
  .filter((row) => !seedKeys.has(row.rowKey))
857
921
  .filter((row) => movedBeyondAuditStamp(beforeByKey.get(row.rowKey), row));
@@ -871,9 +935,141 @@ async function persistRowPayload(handle, payload) {
871
935
  const next = new Map(handle.storedRows.filter((row) => !removed.has(row.rowKey)).map((row) => [row.rowKey, row]));
872
936
  for (const row of writes) next.set(row.rowKey, row);
873
937
  handle.storedRows = [...next.values()];
874
- handle.cachedPayload = rowsToPayload(overlayRows(handle.baseRows, handle.storedRows), {
875
- meta: { memory: payload.memory, prefixes: payload.prefixes },
876
- });
938
+ const meta = { memory: payload.memory, prefixes: payload.prefixes };
939
+ // Dropped before the rebuild, not after it: the payload this replaces is the
940
+ // largest object the handle holds, and keeping it reachable while the next
941
+ // one assembles doubles the peak for no reason.
942
+ handle.cachedPayload = null;
943
+ handle.cachedPayload = handle.sqliteSeedStore
944
+ ? assembleSqliteSeededPayload(handle, meta)
945
+ : rowsToPayload(overlayRows(handle.baseRows, handle.storedRows), { meta });
946
+ }
947
+
948
+ /** The payload minus a set of row keys, for a projection that must not spend
949
+ * bytes on rows the write path is about to filter out anyway. */
950
+ function payloadWithoutRowKeys(payload, excluded) {
951
+ if (!excluded.size) return payload;
952
+ return {
953
+ ...payload,
954
+ individuals: (payload?.individuals || []).filter((ind) => !excluded.has(String(ind?.id ?? ""))),
955
+ objectProperties: (payload?.objectProperties || []).filter((group) => !excluded.has(`${EDGE_GROUP_KEY_PREFIX}${group?.prop}`)),
956
+ };
957
+ }
958
+
959
+ // ---- A sqlite store as the seed layer --------------------------------------
960
+ // The seed a Backend D handle reads under its session's own rows can be an
961
+ // open read-only sqlite store instead of a parsed payload. Nothing about the
962
+ // contract changes: the same rows assemble in the same order and the same keys
963
+ // are barred from every write. What changes is how many copies of the seed
964
+ // exist at once — the rows stream out of the store one at a time and the
965
+ // write path never projects them, so the assembled payload is the only one.
966
+
967
+ /** node:sqlite's row-at-a-time read where the runtime has it, the whole result
968
+ * set where it does not. Streaming is the point: a seed row is garbage the
969
+ * moment assembly has parsed it. */
970
+ function statementRowStream(statement) {
971
+ return typeof statement.iterate === "function" ? statement.iterate() : statement.all();
972
+ }
973
+
974
+ /** Every row the seed store holds, one at a time. `coveredByAnotherLayer(key)`
975
+ * drops the keys the subgraph overlay or the session's own rows already own,
976
+ * so assembly sees each key exactly once. */
977
+ function* sqliteSeedRowStream(store, coveredByAnotherLayer) {
978
+ const individuals = store.db.prepare(
979
+ "SELECT i.id AS id, i.ord AS ord, i.class AS class, i.json AS json, f.subject AS subject"
980
+ + " FROM individuals i LEFT JOIN facts f ON f.id = i.id ORDER BY i.ord, i.id",
981
+ );
982
+ for (const r of statementRowStream(individuals)) {
983
+ if (coveredByAnotherLayer(r.id)) continue;
984
+ const rowClass = ROW_CLASS_BY_INDIVIDUAL_CLASS.get(r.class) || "";
985
+ yield {
986
+ rowKey: r.id,
987
+ rowClass,
988
+ term: rowClass === "fact" ? normFactTerm(r.subject || "") : "",
989
+ json: individualRowJson(r.ord, r.json),
990
+ };
991
+ }
992
+ // One query per group rather than one over every edge in the store: a group
993
+ // is freed as soon as assembly has taken it, so the edges of the largest
994
+ // property are all this ever holds at once.
995
+ const edgesOfProp = store.db.prepare(
996
+ "SELECT subject, object, subject_label, object_label, extra FROM edges WHERE prop = ? ORDER BY rowid",
997
+ );
998
+ for (const relation of store.db.prepare("SELECT prop, ord, predicate, count FROM relations ORDER BY ord, prop").all()) {
999
+ if (coveredByAnotherLayer(`${EDGE_GROUP_KEY_PREFIX}${relation.prop}`)) continue;
1000
+ const examples = [];
1001
+ for (const e of edgesOfProp.all(relation.prop)) {
1002
+ const edge = { subject: e.subject, object: e.object, subjectLabel: e.subject_label, objectLabel: e.object_label };
1003
+ if (e.extra) Object.assign(edge, JSON.parse(e.extra));
1004
+ examples.push(edge);
1005
+ }
1006
+ yield edgeGroupRow({ predicate: relation.predicate, prop: relation.prop, count: relation.count, examples }, relation.ord);
1007
+ }
1008
+ for (const row of readUnmappedRows(store.db)) {
1009
+ if (!coveredByAnotherLayer(row.rowKey)) yield row;
1010
+ }
1011
+ }
1012
+
1013
+ /** Every key the read-only layers hold, with the ord each one carries — the
1014
+ * keys-only view of the seed the write path needs. A key and an integer per
1015
+ * row is small where the rows themselves are not, so this is held for the
1016
+ * handle's life once a write has asked for it. */
1017
+ function sqliteSeedKeyOrds(handle) {
1018
+ if (handle.sqliteSeedKeyOrds) return handle.sqliteSeedKeyOrds;
1019
+ const db = handle.sqliteSeedStore.db;
1020
+ const ords = new Map();
1021
+ for (const r of statementRowStream(db.prepare("SELECT id, ord FROM individuals"))) ords.set(r.id, r.ord);
1022
+ for (const r of statementRowStream(db.prepare("SELECT prop, ord FROM relations"))) ords.set(`${EDGE_GROUP_KEY_PREFIX}${r.prop}`, r.ord);
1023
+ for (const row of readUnmappedRows(db)) ords.set(row.rowKey, ordOfRow(row));
1024
+ for (const row of handle.sqliteSeedOverlayRows || []) ords.set(row.rowKey, ordOfRow(row));
1025
+ handle.sqliteSeedKeyOrds = ords;
1026
+ return ords;
1027
+ }
1028
+
1029
+ /** What `payloadToRows` reads off prior rows: the ord each key already carries,
1030
+ * in the smallest row shape that carries one. The session's own rows come
1031
+ * last, so a key both layers hold keeps the session's ord — the precedence
1032
+ * assembly gives it. */
1033
+ function* sqliteSeedPriorRows(handle) {
1034
+ for (const [rowKey, ord] of sqliteSeedKeyOrds(handle)) yield { rowKey, json: `{"ord":${ord}}` };
1035
+ yield* handle.storedRows;
1036
+ }
1037
+
1038
+ function* chainedRows(...sources) {
1039
+ for (const source of sources) yield* source;
1040
+ }
1041
+
1042
+ /** seed ⊕ overlay ⊕ session, assembled once: the seed streams out of sqlite,
1043
+ * the overlay rows layer over it, and the session's own rows win both. */
1044
+ function assembleSqliteSeededPayload(handle, meta) {
1045
+ const covered = new Set(handle.storedRows.map((row) => row.rowKey));
1046
+ const overlay = (handle.sqliteSeedOverlayRows || []).filter((row) => row?.rowKey && !covered.has(row.rowKey));
1047
+ for (const row of overlay) covered.add(row.rowKey);
1048
+ return rowsToPayload(
1049
+ chainedRows(sqliteSeedRowStream(handle.sqliteSeedStore, (key) => covered.has(key)), overlay, handle.storedRows),
1050
+ { meta },
1051
+ );
1052
+ }
1053
+
1054
+ /** Every distinct subject and object a seed store's facts carry, off the
1055
+ * `facts` projection's own columns — the raw values, folded by whoever needs
1056
+ * them. A caller that would otherwise walk the seed's individuals to collect
1057
+ * its vocabulary asks the database instead and parses no record at all. */
1058
+ export function* sqliteSeedFactTermValues(store) {
1059
+ for (const column of ["subject", "object"]) {
1060
+ for (const r of statementRowStream(store.db.prepare(`SELECT DISTINCT ${column} AS value FROM facts`))) {
1061
+ if (r.value) yield r.value;
1062
+ }
1063
+ }
1064
+ }
1065
+
1066
+ /** The seed's own value for one of the two stored scalars, whichever way this
1067
+ * handle holds its seed. */
1068
+ function seedScalar(handle, key, fallback) {
1069
+ if (!handle.sqliteSeedStore) return handle.basePayload?.[key] ?? fallback;
1070
+ const row = handle.sqliteSeedStore.db.prepare("SELECT v FROM meta WHERE k = ?").get(key);
1071
+ if (!row) return fallback;
1072
+ try { return JSON.parse(row.v); } catch { return fallback; }
877
1073
  }
878
1074
 
879
1075
  /** Resolve a backend token ("memory" | "sqlite" | anything else) into
@@ -1,6 +1,5 @@
1
1
  // news-viz.mjs — news.html: a thin client over the row service's news
2
- // routes (PLAN_MEMORY_BACKEND.md's news.html-goes-thin revision), on the
3
- // ledger.html dashboard precedent (src/services/ledger-viz.mjs: `.dash`/
2
+ // routes, on the ledger.html dashboard precedent (src/services/ledger-viz.mjs: `.dash`/
4
3
  // `.kpirow`/`.tile`/`.tile-bars`, the same THEME_TOKENS_CSS palette).
5
4
  //
6
5
  // This page carries no engine and no seed. Every card, tile, bar, source