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

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.11",
3
+ "version": "6.0.12",
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.",
@@ -68,7 +68,7 @@ export {
68
68
  // fine as long as neither side READS an imported binding while the other's
69
69
  // body is still running — rows.mjs builds its class map on first use, and
70
70
  // every use here is inside a function.
71
- import { payloadToRows, rowsToPayload, diffRows } from "./rows.mjs";
71
+ import { payloadToRows, rowsToPayload, diffRows, renormalizeAssembledPayload } from "./rows.mjs";
72
72
 
73
73
  // The rollup vocabulary and its tuning constants live with the compaction
74
74
  // layer; re-exported here so store consumers keep one import site.
@@ -846,11 +846,14 @@ async function readRowMeta(handle, key, fallback) {
846
846
  try { return JSON.parse(raw); } catch { return fallback; }
847
847
  }
848
848
 
849
- /** loadMemory's read for Backend D: one `readRows()` per cold open, assembled
850
- * once with the seed overlay, then served from `cachedPayload` with no
851
- * further backend traffic. Bookkeeping rows are held aside — they round-trip
852
- * through the store but never compose into a payload. */
853
- async function readRowPayload(handle) {
849
+ /** The assembled payload ITSELF, assembled on the first call and served from
850
+ * `cachedPayload` after that with no further backend traffic. Bookkeeping rows
851
+ * are held aside — they round-trip through the store but never compose into a
852
+ * payload. The caller must not hand this object out: `readRowPayload` is the
853
+ * seam that clones, and cloning a seed-sized payload is the single most
854
+ * expensive thing this backend does, so a caller that only needs the cache
855
+ * warm calls this one instead. */
856
+ async function ensureRowPayload(handle) {
854
857
  if (!handle.cachedPayload) {
855
858
  const empty = emptyMemory();
856
859
  const stored = await collectRows(handle.impl.readRows());
@@ -872,7 +875,13 @@ async function readRowPayload(handle) {
872
875
  handle.cachedPayload = rowsToPayload(overlayRows(handle.baseRows, handle.storedRows), { meta });
873
876
  }
874
877
  }
875
- return cloneJson(handle.cachedPayload);
878
+ return handle.cachedPayload;
879
+ }
880
+
881
+ /** loadMemory's read for Backend D: one `readRows()` per cold open, then a
882
+ * clone of the assembled payload per call. */
883
+ async function readRowPayload(handle) {
884
+ return cloneJson(await ensureRowPayload(handle));
876
885
  }
877
886
 
878
887
  /** A record with its audit stamp removed. `mgx:updatedAt` moves on every
@@ -903,7 +912,7 @@ function movedBeyondAuditStamp(beforeRow, row) {
903
912
  * write drops the cache so the next read rebuilds from the store rather than
904
913
  * from a payload that never landed. */
905
914
  async function persistRowPayload(handle, payload) {
906
- await readRowPayload(handle);
915
+ await ensureRowPayload(handle);
907
916
  const seedKeys = seedOnlyKeys(handle);
908
917
  // On the sqlite path the seed is out of BOTH sides of the diff: the rows it
909
918
  // holds are exactly the keys no write may touch, so projecting them would
@@ -936,13 +945,18 @@ async function persistRowPayload(handle, payload) {
936
945
  for (const row of writes) next.set(row.rowKey, row);
937
946
  handle.storedRows = [...next.values()];
938
947
  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 });
948
+ if (handle.sqliteSeedStore && !removals.length) {
949
+ patchAssembledPayload(handle.cachedPayload, meta, writes);
950
+ } else if (handle.sqliteSeedStore) {
951
+ handle.cachedPayload = null;
952
+ handle.cachedPayload = assembleSqliteSeededPayload(handle, meta);
953
+ } else {
954
+ // Dropped before the rebuild, not after it: the payload this replaces is the
955
+ // largest object the handle holds, and keeping it reachable while the next
956
+ // one assembles doubles the peak for no reason.
957
+ handle.cachedPayload = null;
958
+ handle.cachedPayload = rowsToPayload(overlayRows(handle.baseRows, handle.storedRows), { meta });
959
+ }
946
960
  }
947
961
 
948
962
  /** The payload minus a set of row keys, for a projection that must not spend
@@ -1051,6 +1065,58 @@ function assembleSqliteSeededPayload(handle, meta) {
1051
1065
  );
1052
1066
  }
1053
1067
 
1068
+ /** The assembled payload after a write that only added or rewrote rows, brought
1069
+ * up to date without reading the seed again.
1070
+ *
1071
+ * Why the positions work out: a write only ever carries session rows, and
1072
+ * `payloadToRows` gives a newly-keyed row an ord past every ord already
1073
+ * assembled, so a new individual belongs at the tail and a rewritten one
1074
+ * belongs exactly where it already sits. Both are where a rebuild from the
1075
+ * same rows would put them, and the fact set is unchanged or grown, so the
1076
+ * fact ordering `renormalizeAssembledPayload` reapplies lands the same way.
1077
+ * Everything the payload derives goes through that one function, the same one
1078
+ * `rowsToPayload` itself ends on, so a patched payload and a rebuilt one
1079
+ * cannot drift apart.
1080
+ *
1081
+ * A REMOVAL is not patchable this way and does not come here: dropping an
1082
+ * individual from the assembled array drops it from wherever the fact ordering
1083
+ * moved it to, which is a different position from the one it occupied in row
1084
+ * order, and every fact after it shifts. `persistRowPayload` rebuilds for those.
1085
+ * Mutates and returns `payload`. */
1086
+ function patchAssembledPayload(payload, meta, writes) {
1087
+ payload.memory = meta.memory;
1088
+ payload.prefixes = meta.prefixes;
1089
+ if (!writes.length) return renormalizeAssembledPayload(payload);
1090
+
1091
+ const individualPositions = new Map();
1092
+ for (let i = 0; i < payload.individuals.length; i += 1) individualPositions.set(payload.individuals[i]?.id, i);
1093
+ const groupPositions = new Map();
1094
+ for (let i = 0; i < payload.objectProperties.length; i += 1) groupPositions.set(payload.objectProperties[i]?.prop, i);
1095
+
1096
+ for (const row of writes) {
1097
+ if (row.rowClass === BOOKKEEPING_ROW_CLASS) continue;
1098
+ const record = JSON.parse(row.json);
1099
+ if (row.rowClass === EDGE_GROUP_ROW_CLASS) {
1100
+ const group = record?.group;
1101
+ if (!group?.prop) continue;
1102
+ const at = groupPositions.get(group.prop);
1103
+ if (at === undefined) {
1104
+ groupPositions.set(group.prop, payload.objectProperties.length);
1105
+ payload.objectProperties.push(group);
1106
+ } else payload.objectProperties[at] = group;
1107
+ continue;
1108
+ }
1109
+ const individual = record?.individual;
1110
+ if (!individual?.id) continue;
1111
+ const at = individualPositions.get(individual.id);
1112
+ if (at === undefined) {
1113
+ individualPositions.set(individual.id, payload.individuals.length);
1114
+ payload.individuals.push(individual);
1115
+ } else payload.individuals[at] = individual;
1116
+ }
1117
+ return renormalizeAssembledPayload(payload);
1118
+ }
1119
+
1054
1120
  /** Every distinct subject and object a seed store's facts carry, off the
1055
1121
  * `facts` projection's own columns — the raw values, folded by whoever needs
1056
1122
  * them. A caller that would otherwise walk the seed's individuals to collect
@@ -209,7 +209,12 @@ function sortFactIndividualsById(individuals) {
209
209
  /** Re-derive each record's backward supersession pointer from the union of the
210
210
  * forward ones. Two turns that superseded the same record concurrently both
211
211
  * land, because each wrote its own row and neither touched the record they
212
- * replaced. */
212
+ * replaced.
213
+ *
214
+ * Idempotent: a record that no longer has any successor loses the pointer it
215
+ * used to carry. Rows never carry one (`storedIndividualForm` strips it), so
216
+ * that arm is dead when this runs over a fresh projection and live when it
217
+ * runs again over individuals it already derived. */
213
218
  function applyDerivedSupersessions(individuals) {
214
219
  const successorsById = new Map();
215
220
  for (const ind of individuals) {
@@ -222,11 +227,12 @@ function applyDerivedSupersessions(individuals) {
222
227
  }
223
228
  for (const ind of individuals) {
224
229
  const successors = successorsById.get(ind?.id);
225
- if (!successors) continue;
226
- ind.attributes = [
227
- ...(ind.attributes || []).filter((a) => a?.prop !== SUPERSEDED_BY_PROP),
228
- { prop: SUPERSEDED_BY_PROP, key: "supersededBy", value: [...successors].sort().join(" ") },
229
- ];
230
+ const carried = (ind?.attributes || []).some((a) => a?.prop === SUPERSEDED_BY_PROP);
231
+ if (!successors && !carried) continue;
232
+ const rest = (ind.attributes || []).filter((a) => a?.prop !== SUPERSEDED_BY_PROP);
233
+ ind.attributes = successors
234
+ ? [...rest, { prop: SUPERSEDED_BY_PROP, key: "supersededBy", value: [...successors].sort().join(" ") }]
235
+ : rest;
230
236
  }
231
237
  }
232
238
 
@@ -275,13 +281,27 @@ export function rowsToPayload(rows, { meta = null } = {}) {
275
281
  individualEntries.sort(byOrdThenRowKey);
276
282
  groupEntries.sort(byOrdThenRowKey);
277
283
 
278
- const individuals = individualEntries.map((e) => e.individual).filter(Boolean);
284
+ payload.individuals = individualEntries.map((e) => e.individual).filter(Boolean);
285
+ payload.objectProperties = groupEntries.map((e) => e.group).filter(Boolean);
286
+ return renormalizeAssembledPayload(payload);
287
+ }
288
+
289
+ /** Everything an assembled payload derives from its own individuals: the fact
290
+ * ordering, the backward supersession pointers, the class counts, the prose
291
+ * index and `generated_at`. `rowsToPayload` ends here, and so does a caller
292
+ * that assembled a payload once and then changed a few of its individuals in
293
+ * place — running this leaves the same payload either route, which is what
294
+ * lets a cached assembly be patched instead of rebuilt from its rows.
295
+ * Mutates and returns `payload`. */
296
+ export function renormalizeAssembledPayload(payload) {
297
+ const individuals = payload.individuals || [];
279
298
  sortFactIndividualsById(individuals);
280
299
  applyDerivedSupersessions(individuals);
281
-
282
- payload.individuals = individuals;
283
- payload.objectProperties = groupEntries.map((e) => e.group).filter(Boolean);
284
300
  payload.classes = recountedClasses(individuals);
301
+ // Released before the replacement is built, not after: over a seed-sized
302
+ // store the prose index is the largest derived structure here, and holding
303
+ // the outgoing one while the incoming one grows doubles it for no reason.
304
+ payload.proseIndex = null;
285
305
  payload.proseIndex = buildProseIndex(individuals);
286
306
  payload.generated_at = latestUtteranceTimestamp(individuals);
287
307
  return payload;