dsh-taskbridge 1.3.2 → 1.4.1

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.
@@ -25,6 +25,7 @@ import * as nodeFs from 'node:fs/promises';
25
25
  import { dirname, join } from 'node:path';
26
26
 
27
27
  import { redactDeep } from '../config/redact.js';
28
+ import { REVIEW_NOTE_MAX_CHARS, truncateCodePoints } from './review-note.js';
28
29
 
29
30
  /** Persisted document format version. Unknown versions are refused, never migrated. */
30
31
  const SCHEMA_VERSION = 1;
@@ -230,7 +231,7 @@ export class HistoryStore {
230
231
  async save(view) {
231
232
  if (this.disposed) throw this.disposedError();
232
233
  if (this.refusal !== null) this.throwIfRefused();
233
- const entry = projectView(view, this.maxEntryBytes);
234
+ let entry = projectView(view, this.maxEntryBytes, { rejectOversizeNote: true });
234
235
  const run = this.enqueue(async () => {
235
236
  this.throwIfRefused();
236
237
  const base = await this.ensureLoaded();
@@ -243,6 +244,18 @@ export class HistoryStore {
243
244
  // race must not resurrect a finished task as `running`, so the terminal record
244
245
  // wins and the stale checkpoint is discarded instead of stored.
245
246
  if (isTerminal(draft[index].state) && !isTerminal(entry.state)) return structuredClone(draft[index]);
247
+ // Inspect the current row INSIDE the write queue. A terminal snapshot can
248
+ // have been captured before a review, then queued behind its slow write.
249
+ const recorded = draft[index].hostAcceptance;
250
+ if (recorded !== null && recorded !== undefined) {
251
+ if (entry.hostAcceptance !== null && entry.hostAcceptance !== undefined
252
+ && (entry.hostAcceptance.state !== recorded.state || entry.hostAcceptance.note !== recorded.note)) {
253
+ throw new HistoryError(HISTORY_CODES.viewInvalid, 'a saved review cannot be replaced by a task snapshot', {
254
+ taskId: entry.taskId,
255
+ });
256
+ }
257
+ entry = projectView({ ...entry, hostAcceptance: recorded }, this.maxEntryBytes, { rejectOversizeNote: true });
258
+ }
246
259
  draft[index] = entry;
247
260
  } else {
248
261
  draft.push(entry);
@@ -257,6 +270,48 @@ export class HistoryStore {
257
270
  return await run;
258
271
  }
259
272
 
273
+ /**
274
+ * Atomically patch ONE stored record through a caller-supplied mutation.
275
+ *
276
+ * The stored row is the base, so a patch can add a conclusion without discarding the
277
+ * execution evidence already on disk, and it runs on the same write queue as `save` so
278
+ * two writes can never interleave. The mutation receives a detached copy of the CURRENT
279
+ * row (re-read under the write) and returns the row to store; throwing refuses with the
280
+ * caller's error and nothing is written.
281
+ * @param {string} taskId - stored task id.
282
+ * @param {(row: object) => object} mutate - mutation of the current stored row.
283
+ * @returns {Promise<object>} detached copy of the stored entry.
284
+ * @throws {HistoryError} `HISTORY_VIEW_INVALID` when this task has no stored row.
285
+ */
286
+ async update(taskId, mutate) {
287
+ if (this.disposed) throw this.disposedError();
288
+ if (this.refusal !== null) this.throwIfRefused();
289
+ if (typeof taskId !== 'string' || taskId.trim() === '') {
290
+ throw new HistoryError(HISTORY_CODES.viewInvalid, 'a job history update needs a taskId', {});
291
+ }
292
+ const run = this.enqueue(async () => {
293
+ this.throwIfRefused();
294
+ const base = await this.ensureLoaded();
295
+ const index = base.findIndex((job) => job.taskId === taskId);
296
+ if (index < 0) {
297
+ throw new HistoryError(HISTORY_CODES.viewInvalid, 'no stored record exists for this task', { taskId });
298
+ }
299
+ const entry = projectView(await mutate(structuredClone(base[index])), this.maxEntryBytes, { rejectOversizeNote: true });
300
+ if (entry.taskId !== taskId) {
301
+ throw new HistoryError(HISTORY_CODES.viewInvalid, 'a history update may not change the task it patches', { taskId });
302
+ }
303
+ const draft = base.map((job) => structuredClone(job));
304
+ draft[index] = entry;
305
+ draft.sort(compareStored);
306
+ const now = Date.now();
307
+ this.enforceLimits(draft, entry.taskId, now);
308
+ await this.writeDocument(draft, now);
309
+ this.jobs = draft;
310
+ return structuredClone(entry);
311
+ });
312
+ return await run;
313
+ }
314
+
260
315
  /**
261
316
  * Wait for the in-flight read and every queued write to settle.
262
317
  * @returns {Promise<void>} resolves when the document is consistent.
@@ -489,9 +544,12 @@ export class HistoryStore {
489
544
  * field, a credential or a native handle by widening its own object.
490
545
  * @param {object} view - public job view.
491
546
  * @param {number} maxEntryBytes - per-entry byte budget.
547
+ * @param {{ rejectOversizeNote?: boolean }} [options] - `rejectOversizeNote` refuses an
548
+ * oversized review note instead of cutting it (writes); a load keeps the cut.
492
549
  * @returns {object} bounded, redacted entry.
550
+ * @throws {HistoryError} when the view, or the note under `rejectOversizeNote`, is invalid.
493
551
  */
494
- function projectView(view, maxEntryBytes) {
552
+ function projectView(view, maxEntryBytes, options = {}) {
495
553
  if (!isPlainObject(view)) {
496
554
  throw new HistoryError(HISTORY_CODES.viewInvalid, 'a job history view must be an object', {});
497
555
  }
@@ -504,6 +562,7 @@ function projectView(view, maxEntryBytes) {
504
562
  }
505
563
 
506
564
  const ctx = newCutContext(view.truncation, maxEntryBytes);
565
+ const acceptance = acceptanceView(view.hostAcceptance, ctx, { rejectOversize: options.rejectOversizeNote === true });
507
566
  const entry = {
508
567
  taskId,
509
568
  state: view.state,
@@ -545,7 +604,7 @@ function projectView(view, maxEntryBytes) {
545
604
  activity: activityView(view.activity),
546
605
  error: errorView(view.error, ctx),
547
606
  cancelledBy: label(view.cancelledBy),
548
- hostAcceptance: acceptanceView(view.hostAcceptance),
607
+ hostAcceptance: acceptance,
549
608
  // A completed job is not an accepted one. This is fixed, never copied.
550
609
  selfApproved: false,
551
610
  };
@@ -632,6 +691,7 @@ function effectiveView(value) {
632
691
  ? {
633
692
  selfCheckSeconds: count(value.monitoring.selfCheckSeconds),
634
693
  attentionSeconds: count(value.monitoring.attentionSeconds),
694
+ repeatFailureThreshold: count(value.monitoring.repeatFailureThreshold),
635
695
  }
636
696
  : null,
637
697
  provenance: {
@@ -1029,6 +1089,33 @@ function activityView(value) {
1029
1089
  }
1030
1090
  : {}),
1031
1091
  kinds,
1092
+ // The repeated-failure reminder as bounded evidence: a tool NAME, a failure CODE,
1093
+ // an operation digest and counts. No arguments, no output, no error prose — the
1094
+ // live monitor already reduced it to that, and this keeps the same shape.
1095
+ repeatFailure: repeatFailureOf(value.repeatFailure),
1096
+ };
1097
+ }
1098
+
1099
+ /**
1100
+ * Project a stored `repeatFailure` block, dropping anything but the bounded facts.
1101
+ * @param {unknown} value - candidate block.
1102
+ * @returns {object | null} projection.
1103
+ */
1104
+ function repeatFailureOf(value) {
1105
+ if (!isPlainObject(value)) return null;
1106
+ const reported = Array.isArray(value.reported) ? value.reported : [];
1107
+ return {
1108
+ threshold: count(value.threshold),
1109
+ reported: reported.filter(isPlainObject).slice(0, 32).map((entry) => ({
1110
+ kind: label(entry.kind),
1111
+ toolName: label(entry.toolName),
1112
+ failureCode: label(entry.failureCode),
1113
+ operationDigest: label(entry.operationDigest),
1114
+ consecutive: count(entry.consecutive),
1115
+ threshold: count(entry.threshold),
1116
+ firstSeenAt: time(entry.firstSeenAt),
1117
+ lastSeenAt: time(entry.lastSeenAt),
1118
+ })),
1032
1119
  };
1033
1120
  }
1034
1121
 
@@ -1075,18 +1162,70 @@ function errorView(value, ctx) {
1075
1162
  };
1076
1163
  }
1077
1164
 
1078
- /** @returns {object | null} bounded host-acceptance record. */
1079
- function acceptanceView(value) {
1165
+ /**
1166
+ * Bounded host-acceptance record.
1167
+ *
1168
+ * A recorded conclusion is free prose, so `label()` (256 characters) is the wrong rule for
1169
+ * its note: that silently dropped most of a longer conclusion. A note within the shared
1170
+ * code-point bound is kept exactly as written and REFUSED here when it is longer, so a
1171
+ * caller can never be told a shortened conclusion was saved; a document already carrying
1172
+ * more than the bound keeps read-compatible behaviour.
1173
+ * @param {unknown} value - host-acceptance value.
1174
+ * @param {object} ctx - cut context.
1175
+ * @param {{ rejectOversize?: boolean }} [options] - `rejectOversize` refuses instead of cutting.
1176
+ * @returns {object | null} bounded host-acceptance record.
1177
+ * @throws {HistoryError} `HISTORY_VIEW_INVALID` when the note exceeds the bound and
1178
+ * `rejectOversize` is set.
1179
+ */
1180
+ function acceptanceView(value, ctx, options = {}) {
1080
1181
  if (!isPlainObject(value)) return null;
1182
+ const note = options.rejectOversize === true ? requireNote(value.note) : noteText(value.note, ctx);
1081
1183
  return {
1082
1184
  accepted: value.accepted === true,
1083
1185
  state: label(value.state),
1084
1186
  acceptedAt: time(value.acceptedAt),
1085
1187
  by: label(value.by),
1086
- note: label(value.note),
1188
+ note,
1189
+ noteChars: typeof value.note === 'string' ? Array.from(value.note).length : null,
1087
1190
  };
1088
1191
  }
1089
1192
 
1193
+ /**
1194
+ * Validate an incoming note against the shared bound, refusing rather than cutting.
1195
+ * @param {unknown} value - note.
1196
+ * @returns {string | null} the note as given, or null when there is none.
1197
+ * @throws {HistoryError} `HISTORY_VIEW_INVALID` with the actual length and the limit.
1198
+ */
1199
+ function requireNote(value) {
1200
+ if (typeof value !== 'string' || value === '') return null;
1201
+ const length = Array.from(value).length;
1202
+ if (length > REVIEW_NOTE_MAX_CHARS) {
1203
+ throw new HistoryError(
1204
+ HISTORY_CODES.viewInvalid,
1205
+ `hostAcceptance.note must be at most ${REVIEW_NOTE_MAX_CHARS} Unicode code points, but it is ${length}`,
1206
+ { field: 'hostAcceptance.note', limit: REVIEW_NOTE_MAX_CHARS, length, unit: 'unicode-code-points' },
1207
+ );
1208
+ }
1209
+ return value;
1210
+ }
1211
+
1212
+ /**
1213
+ * Keep a stored review note as written, cutting only a value beyond the accepted bound and
1214
+ * stating that cut.
1215
+ * @param {unknown} value - note.
1216
+ * @param {object} ctx - cut context.
1217
+ * @returns {string | null} the note, or null when there is none.
1218
+ */
1219
+ function noteText(value, ctx) {
1220
+ if (typeof value !== 'string' || value === '') return null;
1221
+ const bounded = truncateCodePoints(value, REVIEW_NOTE_MAX_CHARS);
1222
+ if (bounded !== value) {
1223
+ ctx.fields.add('hostAcceptance.note');
1224
+ return `${bounded}${TRUNCATION_MARK}`;
1225
+ }
1226
+ return value;
1227
+ }
1228
+
1090
1229
  /**
1091
1230
  * Bound an open-ended detail object by shape, not by name: depth, key count and
1092
1231
  * string size. `redactDeep` still masks every secret-named key inside it.
@@ -1151,6 +1290,13 @@ function fitEntry(entry, ctx) {
1151
1290
 
1152
1291
  /**
1153
1292
  * Halve the longest remaining free-text field.
1293
+ *
1294
+ * The recorded host review is NOT in {@link TEXT_PATHS}: an accepted conclusion is the most
1295
+ * valuable prose in the entry, so a large diff or a long worker output is reduced first,
1296
+ * then the long arrays and optional blocks. If a legal note still does not fit beside all
1297
+ * of that, the save is REFUSED — a conclusion is never shortened and then reported saved.
1298
+ * Only a note past the accepted bound (another writer's document) is cut, by
1299
+ * {@link noteText}, with the cut stated.
1154
1300
  * @param {object} entry - mutable entry.
1155
1301
  * @param {object} ctx - cut context.
1156
1302
  * @returns {boolean} whether anything was cut.
@@ -0,0 +1,63 @@
1
+ // The one bound and normalization for a host-review note.
2
+ //
3
+ // A review note is free prose: Chinese, line breaks and emoji are ordinary in it. That is
4
+ // why the bound is counted in Unicode code points — `Array.from(text).length` — rather than
5
+ // in UTF-16 units, where an emoji counts twice. The same rule applies at every entry point
6
+ // (MCP schema, HTTP route, engine, durable history projection), because a note one layer
7
+ // accepts and another cuts is worse than a refusal: the caller would be told "recorded"
8
+ // about text that was never recorded.
9
+ //
10
+ // This module has no imports on purpose: `src/mcp/server.js` is loaded by the standalone
11
+ // MCP binary, which must not pull the engine or any native DSH module in through a shared
12
+ // constant.
13
+
14
+ /** Longest review note, in Unicode code points. */
15
+ export const REVIEW_NOTE_MAX_CHARS = 8_000;
16
+
17
+ /**
18
+ * The normalization applied wherever a note is accepted or stored: surrounding whitespace
19
+ * only. The body of the note is preserved exactly.
20
+ * @param {unknown} value - candidate note.
21
+ * @returns {string} the trimmed note, or '' for a non-string.
22
+ */
23
+ export function normalizeReviewNote(value) {
24
+ return typeof value === 'string' ? value.trim() : '';
25
+ }
26
+
27
+ /**
28
+ * @param {string} value - text to measure.
29
+ * @returns {number} length in Unicode code points (0 for a non-string).
30
+ */
31
+ export function reviewNoteLength(value) {
32
+ return typeof value === 'string' ? Array.from(value).length : 0;
33
+ }
34
+
35
+ /**
36
+ * Refusal facts for an over-long note, so every surface reports the same numbers.
37
+ * @param {string} value - the rejected note.
38
+ * @returns {{ limit: number, length: number, message: string }} bound, actual length, message.
39
+ */
40
+ export function reviewNoteOverflow(value) {
41
+ const length = reviewNoteLength(value);
42
+ return {
43
+ limit: REVIEW_NOTE_MAX_CHARS,
44
+ length,
45
+ message: `note must be at most ${REVIEW_NOTE_MAX_CHARS} Unicode code points, but it is ${length}`,
46
+ };
47
+ }
48
+
49
+ /**
50
+ * Cut a string to a code-point bound.
51
+ *
52
+ * Only for a stored value that reached the document some other way (an older build, a
53
+ * hand-edited file). An accepted request is REFUSED when it is too long, never shortened.
54
+ * @param {unknown} value - candidate text.
55
+ * @param {number} [limit] - code points to keep.
56
+ * @returns {string | null} bounded text, or null when the value is not a non-empty string.
57
+ */
58
+ export function truncateCodePoints(value, limit = REVIEW_NOTE_MAX_CHARS) {
59
+ if (typeof value !== 'string' || value === '') return null;
60
+ const points = Array.from(value);
61
+ if (points.length <= limit) return value;
62
+ return points.slice(0, limit).join('');
63
+ }