@polycode-projects/the-mechanical-code-talker 6.0.6 → 6.0.8

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.6",
3
+ "version": "6.0.8",
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.",
@@ -2443,7 +2443,10 @@ function evalCommitFilter(graph, ast) {
2443
2443
  function evalTemporal(graph, ast, opts) {
2444
2444
  const inner = evalSet(graph, ast.inner, opts);
2445
2445
  const ids = new Set(inner.map((i) => i.id));
2446
- if (!ids.size) return { compositeKind: "temporal", matches: [], entityType: ast.entityType, innerCount: 0 };
2446
+ if (!ids.size) {
2447
+ const emptied = emptiedBranch(graph, ast.inner, opts);
2448
+ return { compositeKind: "temporal", matches: [], entityType: ast.entityType, innerCount: 0, ...(emptied ? { emptied } : {}) };
2449
+ }
2447
2450
  // reverseOverSet(touches) collects touching commits across both grains.
2448
2451
  const commits = reverseOverSet(graph, "touches", "Commit", ids);
2449
2452
  const dateOf = (c) => String((c.attributes || []).find((a) => a.key === "date")?.value || "");
@@ -2455,9 +2458,11 @@ function evalTemporal(graph, ast, opts) {
2455
2458
  * recorded site for the renderer to cite. */
2456
2459
  function evalWhereSet(graph, ast, opts) {
2457
2460
  const matches = evalSet(graph, ast.inner, opts);
2461
+ const emptied = matches.length ? null : emptiedBranch(graph, ast.inner, opts);
2458
2462
  return {
2459
2463
  compositeKind: "whereSet", matches, entityType: ast.entityType,
2460
2464
  sites: matches.map((ind) => (ind.attributes || []).find((a) => a.key === "site")?.value || null),
2465
+ ...(emptied ? { emptied } : {}),
2461
2466
  };
2462
2467
  }
2463
2468
 
@@ -3021,16 +3026,16 @@ function heldBranchQuestion(held) {
3021
3026
  * can mistake for the answer, however carefully the rest of the sentence
3022
3027
  * excludes it. Null where the step may claim nothing, which leaves the caller
3023
3028
  * its own honest empty. */
3024
- function emptiedBranchLine(emptied, entityType, fallbackBranchNote = null) {
3029
+ function emptiedBranchLine(emptied, entityType, { branchNote = null, verdictTail = "" } = {}) {
3025
3030
  if (!emptied?.held) return null;
3026
3031
  const step = stepPhrases(emptied.step);
3027
3032
  if (!step) return null;
3028
3033
  const held = emptied.held;
3029
3034
  const phrases = heldPhrases(held);
3030
3035
  const one = held.count === 1;
3031
- const branch = heldBranchQuestion(held) || fallbackBranchNote;
3036
+ const branch = heldBranchQuestion(held) || branchNote;
3032
3037
  const verdict = entityType ? `no ${nounFor(entityType, 2)} match that` : "nothing matches that";
3033
- return `${verdict}. ${one ? phrases.one : phrases.many}, but ${one ? step.one : step.many}.${branch ? ` ${branch}` : ""}`;
3038
+ return `${verdict}${verdictTail}. ${one ? phrases.one : phrases.many}, but ${one ? step.one : step.many}.${branch ? ` ${branch}` : ""}`;
3034
3039
  }
3035
3040
 
3036
3041
  /** The empty line for a composition whose first clause held nothing: the
@@ -3048,12 +3053,29 @@ function emptyClauseLine(leaf) {
3048
3053
  /** The last resort, and the one sentence that must never over-claim: an index
3049
3054
  * holding none of a kind and an index holding plenty of it are different
3050
3055
  * answers, so they get different words. */
3051
- function emptyKindLine(graph, entityType) {
3056
+ function emptyKindClause(graph, entityType) {
3052
3057
  const total = kindPopulation(graph, entityType);
3053
- if (total === null) return `nothing in the index matches that${entityType ? ` (${nounFor(entityType, 2)})` : ""}.`;
3054
- if (total === 0) return `no ${nounFor(entityType, 2)} in this index.`;
3055
- if (total === 1) return `the index has 1 ${nounFor(entityType, 1)}, and it does not match that.`;
3056
- return `the index has ${total} ${nounFor(entityType, 2)}, and none of them matches that.`;
3058
+ if (total === null) return `nothing in the index matches that${entityType ? ` (${nounFor(entityType, 2)})` : ""}`;
3059
+ if (total === 0) return `no ${nounFor(entityType, 2)} in this index`;
3060
+ if (total === 1) return `the index has 1 ${nounFor(entityType, 1)}, and it does not match that`;
3061
+ return `the index has ${total} ${nounFor(entityType, 2)}, and none of them matches that`;
3062
+ }
3063
+
3064
+ const emptyKindLine = (graph, entityType) => `${emptyKindClause(graph, entityType)}.`;
3065
+
3066
+ /** The empty answer for a lane that has to resolve an inner set before it can
3067
+ * answer anything at all. It gets the same emptied-branch receipt every other
3068
+ * empty composition gets, and carries the lane's own consequence — no location
3069
+ * to cite, no change history to date — on the end of the verdict, so the reader
3070
+ * is told what emptied the set and what that costs them in one sentence. */
3071
+ function emptyInnerSetLine(graph, parsed, result, consequence, fallbackHint) {
3072
+ const branchNote = coverageGrainNote(parsed.inner, result.entityType) || qualifierBranchNote(parsed.inner);
3073
+ const receipt = emptiedBranchLine(result.emptied, result.entityType, { branchNote, verdictTail: consequence });
3074
+ if (receipt) return receipt;
3075
+ const lead = result.emptied?.leaf
3076
+ ? emptyClauseLine(result.emptied.leaf)
3077
+ : emptyKindClause(graph, result.entityType);
3078
+ return `${lead}${consequence}. ${branchNote || fallbackHint}`;
3057
3079
  }
3058
3080
 
3059
3081
  function renderComposite(parsed, result, graph) {
@@ -3267,7 +3289,8 @@ function renderComposite(parsed, result, graph) {
3267
3289
  const setNoun = result.entityType ? nounFor(result.entityType, n || 2) : (n === 1 ? "entity" : "entities");
3268
3290
  const wasWere = n === 1 ? "was" : "were";
3269
3291
  if (!n) {
3270
- return { content: `nothing in the index matches the inner set, so there is no change history to date. ${touchesRephraseHint(graph)}`, miss: true, ambiguous: false, matches: [] };
3292
+ const lead = emptyInnerSetLine(graph, parsed, result, ", so there is no change history to date", touchesRephraseHint(graph));
3293
+ return { content: lead, miss: true, ambiguous: false, matches: [] };
3271
3294
  }
3272
3295
  if (!result.matches.length) {
3273
3296
  return { content: `no recorded commit touched the ${n} ${setNoun} in that set in this index. ${touchesRephraseHint(graph)}`, miss: true, ambiguous: false, matches: [] };
@@ -3290,9 +3313,9 @@ function renderComposite(parsed, result, graph) {
3290
3313
  // said out loud rather than dropped, so the count of answers always matches
3291
3314
  // the count of entities the clause resolved to.
3292
3315
  if (result.compositeKind === "whereSet") {
3293
- const setNoun = result.entityType ? nounFor(result.entityType, 2) : "entities";
3294
3316
  if (!result.matches.length) {
3295
- return { content: `nothing in the index matches that clause (${setNoun}), so there is no location to cite. ${compositionalHint()}.`, miss: true, ambiguous: false, matches: [] };
3317
+ const lead = emptyInnerSetLine(graph, parsed, result, ", so there is no location to cite", `${compositionalHint()}.`);
3318
+ return { content: lead, miss: true, ambiguous: false, matches: [] };
3296
3319
  }
3297
3320
  const lines = result.matches.map((ind, i) => definedAtLine(ind, result.sites[i])
3298
3321
  || `${ind.label} has no recorded code location in this index.`);
@@ -3308,7 +3331,7 @@ function renderComposite(parsed, result, graph) {
3308
3331
  // to them, instead of a blanket "nothing matches" beside an unrelated
3309
3332
  // recovery.
3310
3333
  const branchNote = coverageGrainNote(parsed, result.entityType) || qualifierBranchNote(parsed);
3311
- const receipt = emptiedBranchLine(result.emptied, result.entityType, branchNote);
3334
+ const receipt = emptiedBranchLine(result.emptied, result.entityType, { branchNote });
3312
3335
  if (receipt) return { content: receipt, miss: true, ambiguous: false, matches: [] };
3313
3336
  const hint = branchNote || touchesRephraseHint(graph);
3314
3337
  const lead = result.emptied?.leaf
@@ -33,10 +33,38 @@ import {
33
33
  bandPartitionKey, bandSortKeyForRow, buildBandManifest, bandLicenseInfo, MANIFEST_SORT_KEY,
34
34
  } from "../adapters/memory/corpus-bands.mjs";
35
35
  import { BackendRejected, BackendUnavailable, assertValidRow } from "../adapters/memory/row-backend.mjs";
36
+ import { isSystemicFailure } from "../adapters/memory/systemic-failure.mjs";
36
37
  import { termQueryOverDocumentClient } from "./subgraph-retrieval.mjs";
37
38
 
38
39
  const DEFAULT_WRITE_CONCURRENCY = 25;
39
40
 
41
+ // A run against millions of rows meets an occasional transient 500 or
42
+ // throttle as a certainty, not a rare event, so every store call gets its
43
+ // own retry budget rather than treating the first one as fatal. Five
44
+ // attempts with exponential backoff from 100 ms, full jitter, so many
45
+ // concurrent writers recovering from the same outage don't retry in
46
+ // lockstep.
47
+ const DEFAULT_RETRY_ATTEMPTS = 5;
48
+ const RETRY_BASE_DELAY_MS = 100;
49
+
50
+ const defaultSleep = (ms) => new Promise((resolve) => { setTimeout(resolve, ms); });
51
+ const defaultRandom = () => Math.random();
52
+
53
+ /** Delay (ms) before the retry that follows a failed `attempt` (1-based):
54
+ * full jitter, a value drawn uniformly from `[0, baseDelayMs * 2^(attempt-1))`. */
55
+ function retryDelayMs(attempt, baseDelayMs, random) {
56
+ return random() * baseDelayMs * (2 ** (attempt - 1));
57
+ }
58
+
59
+ /** Build the retry knobs `call` reads from a caller's options object,
60
+ * defaulting to the production policy. */
61
+ function retryPolicyFrom({
62
+ retryAttempts = DEFAULT_RETRY_ATTEMPTS, retryBaseDelayMs = RETRY_BASE_DELAY_MS,
63
+ sleep = defaultSleep, random = defaultRandom,
64
+ } = {}) {
65
+ return { attempts: retryAttempts, baseDelayMs: retryBaseDelayMs, sleep, random };
66
+ }
67
+
40
68
  /** Runs `fn` over `items` with at most `limit` calls in flight, mirroring the
41
69
  * DynamoDB row backend's own bounded-concurrency write loop. */
42
70
  async function mapWithConcurrency(items, limit, fn) {
@@ -55,13 +83,28 @@ async function mapWithConcurrency(items, limit, fn) {
55
83
 
56
84
  /** Every store call funnels through here so a network failure or a
57
85
  * 429/5xx-shaped rejection surfaces as `BackendUnavailable`, never a raw
58
- * client error a caller would have to string-match. */
59
- async function call(fn, label) {
60
- try {
61
- return await fn();
62
- } catch (error) {
63
- if (error instanceof BackendRejected || error instanceof BackendUnavailable) throw error;
64
- throw new BackendUnavailable(`corpus loader's ${label} call failed: ${error.message}`, { cause: error });
86
+ * client error a caller would have to string-match. A systemic failure — a
87
+ * throttle, a 5xx, a transient network fault — retries with exponential
88
+ * backoff up to `retry.attempts` times; a validation/schema rejection is
89
+ * not systemic and fails on the first try, because retrying it gets the
90
+ * same answer. The final error names how many attempts were made, so a
91
+ * genuinely down service reads clearly rather than looking like one bad
92
+ * call. */
93
+ async function call(fn, label, retry) {
94
+ for (let attempt = 1; attempt <= retry.attempts; attempt += 1) {
95
+ try {
96
+ return await fn();
97
+ } catch (error) {
98
+ if (error instanceof BackendRejected || error instanceof BackendUnavailable) throw error;
99
+ if (!isSystemicFailure(error) || attempt === retry.attempts) {
100
+ const attemptsNote = attempt > 1 ? ` after ${attempt} attempts` : "";
101
+ throw new BackendUnavailable(
102
+ `corpus loader's ${label} call failed${attemptsNote}: ${error.message}`,
103
+ { cause: error },
104
+ );
105
+ }
106
+ await retry.sleep(retryDelayMs(attempt, retry.baseDelayMs, retry.random));
107
+ }
65
108
  }
66
109
  }
67
110
 
@@ -99,11 +142,15 @@ async function* readWireRows(path) {
99
142
  }
100
143
  }
101
144
 
102
- /** The manifest row for `band`, or null when the band has never been loaded. */
103
- export async function bandStatus({ client, tableName, band }) {
145
+ /** The manifest row for `band`, or null when the band has never been loaded.
146
+ * `retryAttempts`/`retryBaseDelayMs`/`sleep`/`random` tune the retry policy
147
+ * every store call in this module shares; see `retryPolicyFrom`. */
148
+ export async function bandStatus({ client, tableName, band, ...retryOptions }) {
149
+ const retry = retryPolicyFrom(retryOptions);
104
150
  const result = await call(
105
151
  () => client.get({ TableName: tableName, Key: { pk: bandPartitionKey(band), sk: MANIFEST_SORT_KEY } }),
106
152
  "get",
153
+ retry,
107
154
  );
108
155
  return result?.Item ? { ...result.Item } : null;
109
156
  }
@@ -111,7 +158,7 @@ export async function bandStatus({ client, tableName, band }) {
111
158
  /** Every item (fact rows and the manifest, if present) under a band's
112
159
  * partition, paginated. Shared by `clearBand` and any caller that wants a
113
160
  * full inventory rather than one term's rows. */
114
- async function queryWholePartition({ client, tableName, band }) {
161
+ async function queryWholePartition({ client, tableName, band, retry }) {
115
162
  const items = [];
116
163
  let exclusiveStartKey;
117
164
  do {
@@ -120,7 +167,7 @@ async function queryWholePartition({ client, tableName, band }) {
120
167
  KeyConditionExpression: "pk = :pk",
121
168
  ExpressionAttributeValues: { ":pk": bandPartitionKey(band) },
122
169
  ...(exclusiveStartKey ? { ExclusiveStartKey: exclusiveStartKey } : {}),
123
- }), "query");
170
+ }), "query", retry);
124
171
  items.push(...(response?.Items || []));
125
172
  exclusiveStartKey = response?.LastEvaluatedKey || null;
126
173
  } while (exclusiveStartKey);
@@ -130,18 +177,21 @@ async function queryWholePartition({ client, tableName, band }) {
130
177
  /** Load `band` from a jsonl source of wire rows. Resolves to
131
178
  * `{status: "unchanged" | "loaded" | "dry-run", band, rowCount, sourceDigest}`.
132
179
  * `dryRun` computes the digest and reports what would happen without
133
- * writing anything. */
180
+ * writing anything. `retryAttempts`/`retryBaseDelayMs`/`sleep`/`random` tune
181
+ * the retry policy every store call below shares; see `retryPolicyFrom`. */
134
182
  export async function loadBand({
135
183
  client, tableName, band, source, dryRun = false,
136
184
  writeConcurrency = DEFAULT_WRITE_CONCURRENCY, now = () => new Date().toISOString(),
185
+ retryAttempts, retryBaseDelayMs, sleep, random,
137
186
  }) {
138
187
  if (!client) throw new TypeError("loadBand needs a client");
139
188
  if (!tableName) throw new TypeError("loadBand needs a tableName");
140
189
  if (!band) throw new TypeError("loadBand needs a band");
141
190
  if (!source) throw new TypeError("loadBand needs a source path");
142
191
 
192
+ const retry = retryPolicyFrom({ retryAttempts, retryBaseDelayMs, sleep, random });
143
193
  const sourceDigest = await digestFile(source);
144
- const existing = await bandStatus({ client, tableName, band });
194
+ const existing = await bandStatus({ client, tableName, band, retryAttempts, retryBaseDelayMs, sleep, random });
145
195
  if (existing?.sourceDigest === sourceDigest) {
146
196
  return { status: "unchanged", band, rowCount: existing.rowCount, sourceDigest };
147
197
  }
@@ -159,7 +209,7 @@ export async function loadBand({
159
209
  pk, sk: bandSortKeyForRow(row.rowClass, row.term, row.rowKey),
160
210
  rowKey: row.rowKey, rowClass: row.rowClass, term: row.term, json: row.json,
161
211
  };
162
- await call(() => client.put({ TableName: tableName, Item: item }), "put");
212
+ await call(() => client.put({ TableName: tableName, Item: item }), "put", retry);
163
213
  });
164
214
  const manifest = buildBandManifest({
165
215
  band, rowCount, loadedAt: now(), sourceDigest, license, notice,
@@ -167,7 +217,7 @@ export async function loadBand({
167
217
  await call(() => client.put({
168
218
  TableName: tableName,
169
219
  Item: { pk, sk: MANIFEST_SORT_KEY, ...manifest },
170
- }), "put");
220
+ }), "put", retry);
171
221
  return { status: "loaded", band, rowCount, sourceDigest };
172
222
  }
173
223
 
@@ -177,21 +227,27 @@ export async function loadBand({
177
227
 
178
228
  /** Physically delete every item under `band`'s partition, manifest last.
179
229
  * Idempotent: an empty partition (already cleared, or never loaded) is a
180
- * no-op. Resolves to `{band, deleted}`. */
181
- export async function clearBand({ client, tableName, band, writeConcurrency = DEFAULT_WRITE_CONCURRENCY }) {
230
+ * no-op. Resolves to `{band, deleted}`. `retryAttempts`/`retryBaseDelayMs`/
231
+ * `sleep`/`random` tune the retry policy every store call below shares;
232
+ * see `retryPolicyFrom`. */
233
+ export async function clearBand({
234
+ client, tableName, band, writeConcurrency = DEFAULT_WRITE_CONCURRENCY,
235
+ retryAttempts, retryBaseDelayMs, sleep, random,
236
+ }) {
182
237
  if (!client) throw new TypeError("clearBand needs a client");
183
238
  if (!tableName) throw new TypeError("clearBand needs a tableName");
184
239
  if (!band) throw new TypeError("clearBand needs a band");
185
240
 
186
- const items = await queryWholePartition({ client, tableName, band });
241
+ const retry = retryPolicyFrom({ retryAttempts, retryBaseDelayMs, sleep, random });
242
+ const items = await queryWholePartition({ client, tableName, band, retry });
187
243
  const facts = items.filter((item) => item.sk !== MANIFEST_SORT_KEY);
188
244
  const manifestItem = items.find((item) => item.sk === MANIFEST_SORT_KEY);
189
245
 
190
246
  await mapWithConcurrency(facts, writeConcurrency, async (item) => {
191
- await call(() => client.delete({ TableName: tableName, Key: { pk: item.pk, sk: item.sk } }), "delete");
247
+ await call(() => client.delete({ TableName: tableName, Key: { pk: item.pk, sk: item.sk } }), "delete", retry);
192
248
  });
193
249
  if (manifestItem) {
194
- await call(() => client.delete({ TableName: tableName, Key: { pk: manifestItem.pk, sk: manifestItem.sk } }), "delete");
250
+ await call(() => client.delete({ TableName: tableName, Key: { pk: manifestItem.pk, sk: manifestItem.sk } }), "delete", retry);
195
251
  }
196
252
  return { band, deleted: items.length };
197
253
  }
@@ -68,9 +68,9 @@ async function runFetch(fetchImpl, url, init, networkFailureMessage) {
68
68
 
69
69
  /** One retry, on a 5xx only, for the one call the spec singles out.
70
70
  * `deleteAll`'s purge is query-then-mark and idempotent, so a retried
71
- * DELETE just re-marks whatever the first attempt already reached; it
71
+ * delete just re-marks whatever the first attempt already reached; it
72
72
  * never double-applies. Every other mutation gets one attempt only:
73
- * retrying a PUT or a keyed DELETE past a 5xx is a caller decision, not
73
+ * retrying a PUT or a keyed delete past a 5xx is a caller decision, not
74
74
  * this backend's. */
75
75
  async function fetchWithOneRetryOn5xx(fetchImpl, url, init, networkFailureMessage) {
76
76
  const first = await runFetch(fetchImpl, url, init, networkFailureMessage);
@@ -141,12 +141,15 @@ export function createHttpRowBackend({ apiBase, sessionKey, fetchImpl = fetch }
141
141
 
142
142
  async deleteRows(rowKeys) {
143
143
  assertOpen();
144
- await mutate(`/api/sessions/${sessionKey}/rows`, { method: "DELETE", body: { rowKeys } });
144
+ // CloudFront's OAC signs a DELETE as body-less, so the edge can never
145
+ // pass a body-carrying DELETE through. POST .../rows/delete is the
146
+ // edge-safe spelling of the same call.
147
+ await mutate(`/api/sessions/${sessionKey}/rows/delete`, { method: "POST", body: { rowKeys } });
145
148
  },
146
149
 
147
150
  async deleteAll() {
148
151
  assertOpen();
149
- await mutate(`/api/sessions/${sessionKey}/rows`, { method: "DELETE", body: { all: true } }, { retryOn5xx: true });
152
+ await mutate(`/api/sessions/${sessionKey}/rows/delete`, { method: "POST", body: { all: true } }, { retryOn5xx: true });
150
153
  },
151
154
 
152
155
  async readMeta(key) {