dsh-taskbridge 1.5.3 → 1.5.4

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.
@@ -97,6 +97,7 @@ import {
97
97
  reviewNoteLength,
98
98
  reviewNoteOverflow,
99
99
  } from './review-note.js';
100
+ import { TASK_DESCRIPTION_FIELDS, canonicalTaskDescription } from './task-descriptions.js';
100
101
 
101
102
  /** Task lifecycle states. `awaiting-host-review` is terminal for this plugin. */
102
103
  export const TASK_STATES = Object.freeze({
@@ -165,6 +166,7 @@ export const JOB_CODES = Object.freeze({
165
166
  reviewNotReviewable: 'JOB_REVIEW_NOT_REVIEWABLE',
166
167
  reviewInvalid: 'JOB_REVIEW_INVALID',
167
168
  reviewNotPersisted: 'JOB_REVIEW_NOT_PERSISTED',
169
+ descriptionInvalid: 'JOB_DESCRIPTION_INVALID',
168
170
  });
169
171
 
170
172
  /** Default interval of the internal authorization sweep. */
@@ -521,7 +523,8 @@ export class JobEngine {
521
523
  * @param {object} request - `connectionId`, `grantId`, `workspacePath`, `prompt`, `overrides`,
522
524
  * `authorization` (`'task'` consumes a single-use grant, `'session'` checks the named live session grant),
523
525
  * and optional `continueFromTaskId` (this submission is a follow-up to that named
524
- * delegated task and must continue exactly its DSH thread).
526
+ * delegated task and must continue exactly its DSH thread) plus optional
527
+ * `goalDescription` (<= 2000 Unicode code points, trimmed; refused before side effects).
525
528
  * @returns {Promise<object>} the created task view.
526
529
  */
527
530
  async start(request) {
@@ -547,6 +550,15 @@ export class JobEngine {
547
550
  });
548
551
  }
549
552
  const continueFromTaskId = typeof rawContinuation === 'string' ? rawContinuation.trim() : '';
553
+ const goal = canonicalTaskDescription(request?.goalDescription, TASK_DESCRIPTION_FIELDS.goal, redactText);
554
+ if (goal.ok === false) {
555
+ throw new JobError(JOB_CODES.descriptionInvalid, goal.refusal.message, {
556
+ field: goal.refusal.field,
557
+ limit: goal.refusal.limit,
558
+ length: goal.refusal.length,
559
+ unit: goal.refusal.unit,
560
+ });
561
+ }
550
562
 
551
563
  const authorization = this.authorizationMode === 'switch'
552
564
  ? 'switch'
@@ -556,6 +568,7 @@ export class JobEngine {
556
568
  // Frozen before the first await so the task record states, from the moment it
557
569
  // exists, whether it starts a conversation or continues one.
558
570
  task.continueFromTaskId = continueFromTaskId === '' ? null : continueFromTaskId;
571
+ task.goalDescription = goal.value;
559
572
  this.tasks.set(task.taskId, task);
560
573
  this.prune();
561
574
 
@@ -601,6 +614,7 @@ export class JobEngine {
601
614
  // conversation. Frozen at creation: it is what the run does with its session,
602
615
  // and it must not be re-read after the first await.
603
616
  continueFromTaskId: null,
617
+ goalDescription: null,
604
618
  connectionId: null,
605
619
  grantId: null,
606
620
  grantKind: null,
@@ -2568,7 +2582,8 @@ export class JobEngine {
2568
2582
  // uses, so a stored conclusion cannot smuggle a credential into history or a view. It
2569
2583
  // is NOT cut here: the bound was already enforced above.
2570
2584
  const note = redactText(rawNote);
2571
- const entry = this.beginReviewWrite(task, decision, note);
2585
+ const summary = reviewSummary(request?.completionSummary);
2586
+ const entry = this.beginReviewWrite(task, decision, note, summary);
2572
2587
  return await this.awaitReviewWrite(task, entry, reviewWaitMs(request));
2573
2588
  }
2574
2589
 
@@ -2577,13 +2592,15 @@ export class JobEngine {
2577
2592
  * genuinely IN FLIGHT locks the conclusion: `saving`/`timed-out` join the same
2578
2593
  * conclusion and refuse a different one; `failed` with no confirmed record frees the
2579
2594
  * conclusion for a new attempt; `saved` replays idempotently or refuses a conflict.
2595
+ * Decision, note and canonical `completionSummary` together form the review identity.
2580
2596
  * @param {object} task - task record (already proven reviewable and owned).
2581
2597
  * @param {string} decision - validated decision.
2582
2598
  * @param {string} note - normalized, redacted note.
2599
+ * @param {string | null} [completionSummary] - canonical, already-redacted summary.
2583
2600
  * @returns {object} the persistence entry this request must wait on.
2584
2601
  * @throws {JobError} when a different conclusion is recorded or already in flight.
2585
2602
  */
2586
- beginReviewWrite(task, decision, note) {
2603
+ beginReviewWrite(task, decision, note, completionSummary = null) {
2587
2604
  if (this.history === null || this.history === undefined || typeof this.history.save !== 'function') {
2588
2605
  // `persistHistory` answers success for the missing-store posture, which would let a
2589
2606
  // review be claimed as saved when nothing was written, so this is refused up front.
@@ -2596,11 +2613,11 @@ export class JobEngine {
2596
2613
 
2597
2614
  if (current !== null) {
2598
2615
  if (current.state === REVIEW_PERSISTENCE_STATES.saved) {
2599
- return this.replayOrRefuse(task, recorded, decision, note);
2616
+ return this.replayOrRefuse(task, recorded, decision, note, completionSummary);
2600
2617
  }
2601
2618
  if (current.state === REVIEW_PERSISTENCE_STATES.saving
2602
2619
  || current.state === REVIEW_PERSISTENCE_STATES.timedOut) {
2603
- if (current.decision === decision && current.note === note) return current;
2620
+ if (sameConclusion(current, decision, note, completionSummary)) return current;
2604
2621
  throw new JobError(JOB_CODES.reviewNotReviewable,
2605
2622
  'a different review decision is being recorded for this task; wait for it or send a follow-up task', {
2606
2623
  taskId: task.taskId,
@@ -2614,13 +2631,14 @@ export class JobEngine {
2614
2631
  }
2615
2632
 
2616
2633
  if (recorded !== null && recorded !== undefined) {
2617
- return this.replayOrRefuse(task, recorded, decision, note);
2634
+ return this.replayOrRefuse(task, recorded, decision, note, completionSummary);
2618
2635
  }
2619
2636
 
2620
2637
  const entry = {
2621
2638
  state: REVIEW_PERSISTENCE_STATES.saving,
2622
2639
  decision,
2623
2640
  note,
2641
+ completionSummary,
2624
2642
  token: (this.reviewSeq ?? 0) + 1,
2625
2643
  startedAt: this.clock(),
2626
2644
  confirmedAt: null,
@@ -2642,13 +2660,21 @@ export class JobEngine {
2642
2660
  * @param {object} recorded - the recorded `hostAcceptance`.
2643
2661
  * @param {string} decision - requested decision.
2644
2662
  * @param {string} note - requested note.
2663
+ * @param {string | null} [completionSummary] - canonical summary this request states.
2645
2664
  * @returns {object} the saved persistence entry.
2646
2665
  * @throws {JobError} on a different conclusion.
2647
2666
  */
2648
- replayOrRefuse(task, recorded, decision, note) {
2667
+ replayOrRefuse(task, recorded, decision, note, completionSummary = null) {
2649
2668
  if (recorded !== null && recorded !== undefined
2650
- && recorded.state === decision && recorded.note === note) {
2651
- return { state: REVIEW_PERSISTENCE_STATES.saved, decision, note, token: -1, done: Promise.resolve(true) };
2669
+ && sameConclusion(recorded, decision, note, completionSummary)) {
2670
+ return {
2671
+ state: REVIEW_PERSISTENCE_STATES.saved,
2672
+ decision,
2673
+ note,
2674
+ completionSummary: typeof recorded.completionSummary === 'string' ? recorded.completionSummary : null,
2675
+ token: -1,
2676
+ done: Promise.resolve(true),
2677
+ };
2652
2678
  }
2653
2679
  throw new JobError(JOB_CODES.reviewNotReviewable,
2654
2680
  'this task already has a recorded review; send a follow-up task to record a correction', {
@@ -2707,6 +2733,7 @@ export class JobEngine {
2707
2733
  acceptedAt: entry.startedAt,
2708
2734
  by: HOST_REVIEW_BY,
2709
2735
  note: entry.note,
2736
+ ...(typeof entry.completionSummary === 'string' ? { completionSummary: entry.completionSummary } : {}),
2710
2737
  };
2711
2738
  task.historyError = null;
2712
2739
  task.historySavedAt = this.clock();
@@ -4139,6 +4166,7 @@ export class JobEngine {
4139
4166
  acceptedAt: entry.startedAt,
4140
4167
  by: HOST_REVIEW_BY,
4141
4168
  note: entry.note,
4169
+ ...(typeof entry.completionSummary === 'string' ? { completionSummary: entry.completionSummary } : {}),
4142
4170
  };
4143
4171
  return view;
4144
4172
  }
@@ -4244,13 +4272,15 @@ export class JobEngine {
4244
4272
  * @param {string} decision - validated decision.
4245
4273
  * @param {string} note - normalized, redacted note.
4246
4274
  * @param {number} waitMs - per-request wait bound.
4275
+ * @param {string | null} [completionSummary] - raw summary (`undefined` = omitted).
4247
4276
  * @returns {Promise<object>} `{ task, hostAcceptance, reviewPersistence }`.
4248
4277
  * @throws {JobError} on any refusal.
4249
4278
  */
4250
- async recordHistoricalReview({ taskId, connectionId }, decision, note, waitMs) {
4279
+ async recordHistoricalReview({ taskId, connectionId }, decision, note, waitMs, completionSummary = undefined) {
4251
4280
  const input = reviewInput({ decision, note });
4252
4281
  decision = input.decision;
4253
4282
  note = redactText(input.note);
4283
+ const summary = reviewSummary(completionSummary);
4254
4284
  const row = await this.storedTaskRow(taskId, connectionId);
4255
4285
  // The SAME answer an unknown task gets: the live path refuses an unknown id with this
4256
4286
  // wording, so a restored task must not be distinguishable from a missing one.
@@ -4264,7 +4294,7 @@ export class JobEngine {
4264
4294
  state: row.state,
4265
4295
  });
4266
4296
  }
4267
- const entry = this.beginHistoryReviewWrite(row, decision, note);
4297
+ const entry = this.beginHistoryReviewWrite(row, decision, note, summary);
4268
4298
  return await this.awaitHistoryReviewWrite(row, entry, waitMs);
4269
4299
  }
4270
4300
 
@@ -4277,10 +4307,11 @@ export class JobEngine {
4277
4307
  * @param {object} row - the stored row as first read.
4278
4308
  * @param {string} decision - validated decision.
4279
4309
  * @param {string} note - normalized note to record.
4310
+ * @param {string | null} [completionSummary] - normalized summary to record, or null.
4280
4311
  * @returns {object} persistence entry to await.
4281
4312
  * @throws {JobError} on a recorded or in-flight conflict.
4282
4313
  */
4283
- beginHistoryReviewWrite(row, decision, note) {
4314
+ beginHistoryReviewWrite(row, decision, note, completionSummary = null) {
4284
4315
  const history = this.history;
4285
4316
  if (history === null || history === undefined || typeof history.update !== 'function') {
4286
4317
  throw new JobError(JOB_CODES.reviewNotPersisted,
@@ -4294,7 +4325,7 @@ export class JobEngine {
4294
4325
  const current = this.reviewState.get(key) ?? null;
4295
4326
  if (current !== null
4296
4327
  && (current.state === REVIEW_PERSISTENCE_STATES.saving || current.state === REVIEW_PERSISTENCE_STATES.timedOut)) {
4297
- if (current.decision === decision && current.note === note) return current;
4328
+ if (sameConclusion(current, decision, note, completionSummary)) return current;
4298
4329
  throw new JobError(JOB_CODES.reviewNotReviewable,
4299
4330
  'a different review decision is being recorded for this task; wait for it or send a follow-up task', {
4300
4331
  taskId: key,
@@ -4303,8 +4334,15 @@ export class JobEngine {
4303
4334
  });
4304
4335
  }
4305
4336
  if (recorded !== null && recorded !== undefined) {
4306
- if (recorded.state === decision && recorded.note === note) {
4307
- return { state: REVIEW_PERSISTENCE_STATES.saved, decision, note, token: -1, done: Promise.resolve(true) };
4337
+ if (sameConclusion(recorded, decision, note, completionSummary)) {
4338
+ return {
4339
+ state: REVIEW_PERSISTENCE_STATES.saved,
4340
+ decision,
4341
+ note,
4342
+ completionSummary,
4343
+ token: -1,
4344
+ done: Promise.resolve(true),
4345
+ };
4308
4346
  }
4309
4347
  throw new JobError(JOB_CODES.reviewNotReviewable,
4310
4348
  'this task already has a recorded review; send a follow-up task to record a correction', {
@@ -4317,6 +4355,7 @@ export class JobEngine {
4317
4355
  state: REVIEW_PERSISTENCE_STATES.saving,
4318
4356
  decision,
4319
4357
  note,
4358
+ completionSummary,
4320
4359
  token: (this.reviewSeq ?? 0) + 1,
4321
4360
  startedAt: this.clock(),
4322
4361
  confirmedAt: null,
@@ -4344,6 +4383,7 @@ export class JobEngine {
4344
4383
  acceptedAt: entry.startedAt,
4345
4384
  by: HOST_REVIEW_BY,
4346
4385
  note: entry.note,
4386
+ ...(typeof entry.completionSummary === 'string' ? { completionSummary: entry.completionSummary } : {}),
4347
4387
  };
4348
4388
  try {
4349
4389
  await this.history.update(taskId, (row) => {
@@ -4357,7 +4397,7 @@ export class JobEngine {
4357
4397
  });
4358
4398
  }
4359
4399
  if (row.hostAcceptance !== null && row.hostAcceptance !== undefined) {
4360
- if (row.hostAcceptance.state === entry.decision && row.hostAcceptance.note === entry.note) return row;
4400
+ if (sameConclusion(row.hostAcceptance, entry.decision, entry.note, entry.completionSummary)) return row;
4361
4401
  throw new JobError(JOB_CODES.reviewNotReviewable,
4362
4402
  'this task already has a recorded review; send a follow-up task to record a correction', { taskId });
4363
4403
  }
@@ -4740,6 +4780,9 @@ export class JobEngine {
4740
4780
  // Frozen on the task at creation, so the record states the intent even when
4741
4781
  // the run never got as far as driving a conversation.
4742
4782
  continueFromTaskId: task.continueFromTaskId ?? null,
4783
+ ...(typeof task.goalDescription === 'string' && task.goalDescription !== ''
4784
+ ? { goalDescription: task.goalDescription }
4785
+ : {}),
4743
4786
  conversationSaved: task.conversationSaved,
4744
4787
  conversationError: task.conversationError,
4745
4788
  review: task.review,
@@ -5030,7 +5073,8 @@ async function raceOutcome(promise, ms, signal = null) {
5030
5073
  * A review conclusion as a WAIT reports it: status, time and length, never the body.
5031
5074
  *
5032
5075
  * The object is kept so an old client cannot read "no note" as "not reviewed"; the body is
5033
- * read on demand (R5). `noteOmitted: true` states the omission explicitly.
5076
+ * read on demand (R5). `noteOmitted: true` states the omission explicitly; any recorded
5077
+ * `completionSummary` likewise reports length and `completionSummaryOmitted: true` only.
5034
5078
  * @param {object | null} acceptance - recorded acceptance.
5035
5079
  * @returns {object | null} summarized acceptance.
5036
5080
  */
@@ -5043,9 +5087,44 @@ function summarizedAcceptance(acceptance) {
5043
5087
  by: acceptance.by ?? null,
5044
5088
  noteChars: typeof acceptance.note === 'string' ? Array.from(acceptance.note).length : (acceptance.noteChars ?? 0),
5045
5089
  noteOmitted: true,
5090
+ ...(typeof acceptance.completionSummary === 'string' && acceptance.completionSummary !== ''
5091
+ ? {
5092
+ completionSummaryChars: Array.from(acceptance.completionSummary).length,
5093
+ completionSummaryOmitted: true,
5094
+ }
5095
+ : {}),
5046
5096
  };
5047
5097
  }
5048
5098
 
5099
+ /** Canonicalize one proposed completion summary once, or return null when absent. */
5100
+ function reviewSummary(value, field = TASK_DESCRIPTION_FIELDS.summary) {
5101
+ const read = canonicalTaskDescription(value, field, redactText);
5102
+ if (read.ok === false) {
5103
+ throw new JobError(JOB_CODES.reviewInvalid, read.refusal.message, {
5104
+ field: read.refusal.field,
5105
+ limit: read.refusal.limit,
5106
+ length: read.refusal.length,
5107
+ unit: read.refusal.unit,
5108
+ });
5109
+ }
5110
+ return read.value;
5111
+ }
5112
+
5113
+ /** Compare decision, note and canonical completionSummary across live/stored/in-flight records. */
5114
+ function sameConclusion(recorded, decision, note, completionSummary) {
5115
+ if (recorded === null || recorded === undefined) return false;
5116
+ const recordedDecision = typeof recorded.decision === 'string' ? recorded.decision : recorded.state;
5117
+ if (recordedDecision !== decision || recorded.note !== note) return false;
5118
+ const recordedSummary = summaryIdentity(recorded);
5119
+ const requestedSummary = summaryIdentity({ completionSummary });
5120
+ return recordedSummary === requestedSummary;
5121
+ }
5122
+
5123
+ function summaryIdentity(value) {
5124
+ const source = value?.completionSummary;
5125
+ return typeof source === 'string' && source !== '' ? source : null;
5126
+ }
5127
+
5049
5128
  /**
5050
5129
  * The Agent Teams outcome as a WAIT reports it: four booleans and one bounded reason.
5051
5130
  *
@@ -16,6 +16,10 @@
16
16
  // * A limit that cannot be met by evicting a terminal record is refused. A live
17
17
  // (pending/running) job is never silently dropped.
18
18
  //
19
+ // `continueFromTaskId` and `title` are omitted when absent; `goalDescription` and
20
+ // `hostAcceptance.completionSummary` enforce <= 2000 code points on writes (never cut by fitting)
21
+ // and truncate with markers on loads of older/external documents.
22
+ //
19
23
  // On load, `pending`/`running` records become `interrupted` with
20
24
  // `error.code = JOB_INTERRUPTED_RESTART`. They are never resubmitted, and the
21
25
  // authorization that once covered them is not restored.
@@ -24,8 +28,14 @@ import { randomBytes } from 'node:crypto';
24
28
  import * as nodeFs from 'node:fs/promises';
25
29
  import { dirname, join } from 'node:path';
26
30
 
27
- import { redactDeep } from '../config/redact.js';
31
+ import { redactDeep, redactText } from '../config/redact.js';
28
32
  import { REVIEW_NOTE_MAX_CHARS, truncateCodePoints } from './review-note.js';
33
+ import {
34
+ TASK_DESCRIPTION_FIELDS,
35
+ TASK_DESCRIPTION_MAX_CHARS,
36
+ canonicalTaskDescription,
37
+ truncateTaskDescription,
38
+ } from './task-descriptions.js';
29
39
 
30
40
  /** Persisted document format version. Unknown versions are refused, never migrated. */
31
41
  const SCHEMA_VERSION = 1;
@@ -50,6 +60,9 @@ const FIT_RESERVE = 512;
50
60
  const TRUNCATION_MARK = '… [truncated]';
51
61
 
52
62
  const MAX_PATH_CHARS = 4096;
63
+ /** The truncation path of the completion summary, exactly as a reader sees it. */
64
+ const SUMMARY_PATH = `hostAcceptance.${TASK_DESCRIPTION_FIELDS.summary}`;
65
+
53
66
  const MAX_LABEL_CHARS = 256;
54
67
  const MAX_MESSAGE_CHARS = 4096;
55
68
  const MAX_DETAIL_STRING_CHARS = 512;
@@ -246,15 +259,33 @@ export class HistoryStore {
246
259
  if (isTerminal(draft[index].state) && !isTerminal(entry.state)) return structuredClone(draft[index]);
247
260
  // Inspect the current row INSIDE the write queue. A terminal snapshot can
248
261
  // have been captured before a review, then queued behind its slow write.
262
+ let merged = null;
249
263
  const recorded = draft[index].hostAcceptance;
250
264
  if (recorded !== null && recorded !== undefined) {
251
- if (entry.hostAcceptance !== null && entry.hostAcceptance !== undefined
252
- && (entry.hostAcceptance.state !== recorded.state || entry.hostAcceptance.note !== recorded.note)) {
265
+ if (!sameRecordedReview(entry.hostAcceptance, recorded)) {
253
266
  throw new HistoryError(HISTORY_CODES.viewInvalid, 'a saved review cannot be replaced by a task snapshot', {
254
267
  taskId: entry.taskId,
255
268
  });
256
269
  }
257
- entry = projectView({ ...entry, hostAcceptance: recorded }, this.maxEntryBytes, { rejectOversizeNote: true });
270
+ merged = { ...entry, hostAcceptance: recorded };
271
+ }
272
+ // A saved goal description is never replaced by a snapshot that lacks one, and a
273
+ // DIFFERENT one is a conflict refused rather than trusted.
274
+ const savedGoal = draft[index].goalDescription;
275
+ if (typeof savedGoal === 'string' && savedGoal !== '') {
276
+ const incoming = entry.goalDescription;
277
+ if (incoming !== undefined && incoming !== savedGoal) {
278
+ throw new HistoryError(HISTORY_CODES.viewInvalid, 'a saved goal description cannot be replaced by a different one', {
279
+ taskId: entry.taskId,
280
+ field: TASK_DESCRIPTION_FIELDS.goal,
281
+ });
282
+ }
283
+ if (incoming !== savedGoal) {
284
+ merged = { ...(merged ?? entry), goalDescription: savedGoal };
285
+ }
286
+ }
287
+ if (merged !== null) {
288
+ entry = projectView(merged, this.maxEntryBytes, { rejectOversizeNote: true });
258
289
  }
259
290
  draft[index] = entry;
260
291
  } else {
@@ -278,10 +309,13 @@ export class HistoryStore {
278
309
  * two writes can never interleave. The mutation receives a detached copy of the CURRENT
279
310
  * row (re-read under the write) and returns the row to store; throwing refuses with the
280
311
  * caller's error and nothing is written.
312
+ *
313
+ * A stored description may not be erased, replaced, or gain a summary.
281
314
  * @param {string} taskId - stored task id.
282
315
  * @param {(row: object) => object} mutate - mutation of the current stored row.
283
316
  * @returns {Promise<object>} detached copy of the stored entry.
284
- * @throws {HistoryError} `HISTORY_VIEW_INVALID` when this task has no stored row.
317
+ * @throws {HistoryError} `HISTORY_VIEW_INVALID` when this task has no stored row, when the
318
+ * patch would replace a saved description, or when a description is over the bound.
285
319
  */
286
320
  async update(taskId, mutate) {
287
321
  if (this.disposed) throw this.disposedError();
@@ -300,6 +334,39 @@ export class HistoryStore {
300
334
  if (entry.taskId !== taskId) {
301
335
  throw new HistoryError(HISTORY_CODES.viewInvalid, 'a history update may not change the task it patches', { taskId });
302
336
  }
337
+ const storedGoal = base[index].goalDescription;
338
+ if (typeof storedGoal === 'string' && storedGoal !== '') {
339
+ if (entry.goalDescription === undefined) {
340
+ throw new HistoryError(HISTORY_CODES.viewInvalid, 'a history update may not erase the goal description', {
341
+ taskId,
342
+ field: TASK_DESCRIPTION_FIELDS.goal,
343
+ });
344
+ }
345
+ if (entry.goalDescription !== storedGoal) {
346
+ throw new HistoryError(HISTORY_CODES.viewInvalid, 'a history update may not replace the goal description', {
347
+ taskId,
348
+ field: TASK_DESCRIPTION_FIELDS.goal,
349
+ });
350
+ }
351
+ }
352
+ const storedReview = base[index].hostAcceptance;
353
+ const storedSummary = storedReview?.completionSummary;
354
+ if (storedReview !== null && storedReview !== undefined) {
355
+ const proposed = entry.hostAcceptance?.completionSummary;
356
+ const hadSummary = typeof storedSummary === 'string' && storedSummary !== '';
357
+ if (!hadSummary && proposed !== undefined) {
358
+ throw new HistoryError(HISTORY_CODES.viewInvalid, 'a saved review with no completion summary cannot gain one', {
359
+ taskId,
360
+ field: TASK_DESCRIPTION_FIELDS.summary,
361
+ });
362
+ }
363
+ if (hadSummary && proposed !== storedSummary) {
364
+ throw new HistoryError(HISTORY_CODES.viewInvalid, 'a saved completion summary cannot be replaced by a different one', {
365
+ taskId,
366
+ field: TASK_DESCRIPTION_FIELDS.summary,
367
+ });
368
+ }
369
+ }
303
370
  const draft = base.map((job) => structuredClone(job));
304
371
  draft[index] = entry;
305
372
  draft.sort(compareStored);
@@ -545,9 +612,10 @@ export class HistoryStore {
545
612
  * @param {object} view - public job view.
546
613
  * @param {number} maxEntryBytes - per-entry byte budget.
547
614
  * @param {{ rejectOversizeNote?: boolean }} [options] - `rejectOversizeNote` refuses an
548
- * oversized review note instead of cutting it (writes); a load keeps the cut.
615
+ * oversized review note or completion summary instead of cutting it (writes); a load
616
+ * keeps the cut.
549
617
  * @returns {object} bounded, redacted entry.
550
- * @throws {HistoryError} when the view, or the note under `rejectOversizeNote`, is invalid.
618
+ * @throws {HistoryError} when the view, or a description under `rejectOversizeNote`, is invalid.
551
619
  */
552
620
  function projectView(view, maxEntryBytes, options = {}) {
553
621
  if (!isPlainObject(view)) {
@@ -563,9 +631,19 @@ function projectView(view, maxEntryBytes, options = {}) {
563
631
 
564
632
  const ctx = newCutContext(view.truncation, maxEntryBytes);
565
633
  const acceptance = acceptanceView(view.hostAcceptance, ctx, { rejectOversize: options.rejectOversizeNote === true });
634
+ // Both are omitted when absent, so a load does not rewrite a document to add the new keys.
635
+ const title = titleText(view.title, ctx);
636
+ const continueFrom = continuationRef(view.continueFromTaskId, taskId);
637
+ const goalDescription = descriptionText(
638
+ view.goalDescription, ctx, TASK_DESCRIPTION_FIELDS.goal, { rejectOversize: options.rejectOversizeNote === true },
639
+ );
566
640
  const entry = {
567
641
  taskId,
568
642
  state: view.state,
643
+ ...(title === '' ? {} : { title }),
644
+ ...(continueFrom === null ? {} : { continueFromTaskId: continueFrom }),
645
+ // Only present when the commander stated a goal: nothing is derived from the prompt.
646
+ ...(goalDescription === null ? {} : { goalDescription }),
569
647
  phase: label(view.phase),
570
648
  createdAt: time(view.createdAt),
571
649
  startedAt: time(view.startedAt),
@@ -639,6 +717,14 @@ function projectView(view, maxEntryBytes, options = {}) {
639
717
  // already-fitted entry is a no-op and a reload never rewrites the file.
640
718
  const truncation = cutView(ctx);
641
719
  if (truncation !== null) redacted.truncation = truncation;
720
+ const finalBytes = byteLength(JSON.stringify(redacted));
721
+ if (finalBytes > maxEntryBytes) {
722
+ throw new HistoryError(
723
+ HISTORY_CODES.entryTooLarge,
724
+ 'the job history view cannot be bounded to the configured entry budget',
725
+ { bytes: finalBytes, limit: maxEntryBytes },
726
+ );
727
+ }
642
728
  return redacted;
643
729
  }
644
730
 
@@ -1237,16 +1323,20 @@ function errorView(value, ctx) {
1237
1323
  * code-point bound is kept exactly as written and REFUSED here when it is longer, so a
1238
1324
  * caller can never be told a shortened conclusion was saved; a document already carrying
1239
1325
  * more than the bound keeps read-compatible behaviour.
1326
+ *
1327
+ * `completionSummary` is the same kind of prose under the same rule, stored only here.
1240
1328
  * @param {unknown} value - host-acceptance value.
1241
1329
  * @param {object} ctx - cut context.
1242
1330
  * @param {{ rejectOversize?: boolean }} [options] - `rejectOversize` refuses instead of cutting.
1243
1331
  * @returns {object | null} bounded host-acceptance record.
1244
- * @throws {HistoryError} `HISTORY_VIEW_INVALID` when the note exceeds the bound and
1245
- * `rejectOversize` is set.
1332
+ * @throws {HistoryError} `HISTORY_VIEW_INVALID` when the note or the summary exceeds the
1333
+ * bound and `rejectOversize` is set.
1246
1334
  */
1247
1335
  function acceptanceView(value, ctx, options = {}) {
1248
1336
  if (!isPlainObject(value)) return null;
1249
- const note = options.rejectOversize === true ? requireNote(value.note) : noteText(value.note, ctx);
1337
+ const reject = options.rejectOversize === true;
1338
+ const note = reject ? requireNote(value.note) : noteText(value.note, ctx);
1339
+ const summary = descriptionText(value.completionSummary, ctx, SUMMARY_PATH, { rejectOversize: reject });
1250
1340
  return {
1251
1341
  accepted: value.accepted === true,
1252
1342
  state: label(value.state),
@@ -1254,9 +1344,44 @@ function acceptanceView(value, ctx, options = {}) {
1254
1344
  by: label(value.by),
1255
1345
  note,
1256
1346
  noteChars: typeof value.note === 'string' ? Array.from(value.note).length : null,
1347
+ ...(summary === null ? {} : { completionSummary: summary }),
1257
1348
  };
1258
1349
  }
1259
1350
 
1351
+ function descriptionRefusal(refusal) {
1352
+ return new HistoryError(HISTORY_CODES.viewInvalid, refusal.message, {
1353
+ field: refusal.field,
1354
+ limit: refusal.limit,
1355
+ length: refusal.length,
1356
+ unit: refusal.unit,
1357
+ });
1358
+ }
1359
+
1360
+ /** Project `goalDescription` or `completionSummary` (refuse on write; redact + bound on load). */
1361
+ function descriptionText(value, ctx, field, options = {}) {
1362
+ if (options.rejectOversize === true) {
1363
+ const read = canonicalTaskDescription(value, field, redactText);
1364
+ if (read.ok === false) throw descriptionRefusal(read.refusal);
1365
+ return read.value;
1366
+ }
1367
+ if (typeof value !== 'string') return null;
1368
+ const trimmed = redactText(value.trim());
1369
+ if (trimmed === '') return null;
1370
+ if (Array.from(trimmed).length <= TASK_DESCRIPTION_MAX_CHARS) return trimmed;
1371
+ const bounded = truncateTaskDescription(trimmed, Array.from(TRUNCATION_MARK).length);
1372
+ ctx.fields.add(field);
1373
+ return `${bounded}${TRUNCATION_MARK}`;
1374
+ }
1375
+
1376
+ /** Compare incoming review block against the recorded one (absent incoming summary keeps stored). */
1377
+ function sameRecordedReview(incoming, stored) {
1378
+ if (incoming === null || incoming === undefined) return true;
1379
+ if (incoming.state !== stored.state || incoming.note !== stored.note) return false;
1380
+ const mine = incoming.completionSummary;
1381
+ if (mine === undefined) return true;
1382
+ return mine === stored.completionSummary;
1383
+ }
1384
+
1260
1385
  /**
1261
1386
  * Validate an incoming note against the shared bound, refusing rather than cutting.
1262
1387
  * @param {unknown} value - note.
@@ -1334,6 +1459,10 @@ function boundedDetails(value, ctx, field, depth) {
1334
1459
  * Free text is halved first, then long arrays, then optional blocks; each cut is
1335
1460
  * recorded, so a consumer can see that evidence was reduced instead of receiving
1336
1461
  * a silently short record. Only when nothing more can be cut is the entry refused.
1462
+ *
1463
+ * Neither commander description is ever cut to fit: a legal description CAN be the reason an
1464
+ * entry does not fit, and then the save is REFUSED. `completionSummary` lives inside
1465
+ * `hostAcceptance`, which {@link dropBlock} cannot drop.
1337
1466
  * @param {object} entry - mutable entry.
1338
1467
  * @param {object} ctx - cut context.
1339
1468
  * @returns {void}
@@ -1370,20 +1499,28 @@ function fitEntry(entry, ctx) {
1370
1499
  */
1371
1500
  function cutLargestText(entry, ctx) {
1372
1501
  let chosen = null;
1502
+ let chosenNext = '';
1373
1503
  let length = 0;
1374
1504
  for (const parts of TEXT_PATHS) {
1375
1505
  const value = getPath(entry, parts);
1376
1506
  if (typeof value !== 'string' || value === '') continue;
1507
+ const base = value.endsWith(TRUNCATION_MARK) ? value.slice(0, -TRUNCATION_MARK.length) : value;
1508
+ let limit = Math.floor(base.length / 2);
1509
+ if (limit > 0) {
1510
+ const lead = base.charCodeAt(limit - 1);
1511
+ const trail = base.charCodeAt(limit);
1512
+ if (lead >= 0xd800 && lead <= 0xdbff && trail >= 0xdc00 && trail <= 0xdfff) limit -= 1;
1513
+ }
1514
+ const next = `${base.slice(0, limit)}${TRUNCATION_MARK}`;
1515
+ if (byteLength(JSON.stringify(next)) >= byteLength(JSON.stringify(value))) continue;
1377
1516
  if (value.length > length) {
1378
1517
  chosen = parts;
1518
+ chosenNext = next;
1379
1519
  length = value.length;
1380
1520
  }
1381
1521
  }
1382
1522
  if (chosen === null) return false;
1383
- const current = getPath(entry, chosen);
1384
- const base = current.endsWith(TRUNCATION_MARK) ? current.slice(0, -TRUNCATION_MARK.length) : current;
1385
- const limit = Math.floor(base.length / 2);
1386
- setPath(entry, chosen, `${base.slice(0, limit)}${TRUNCATION_MARK}`);
1523
+ setPath(entry, chosen, chosenNext);
1387
1524
  const field = chosen.join('.');
1388
1525
  ctx.fields.add(field);
1389
1526
  // Keep the existing evidence flags honest when the patch itself was cut.
@@ -1540,6 +1677,21 @@ function label(value) {
1540
1677
  return value.slice(0, MAX_LABEL_CHARS);
1541
1678
  }
1542
1679
 
1680
+ /** Bounded display title, or '' when absent (never synthesized). */
1681
+ function titleText(value, ctx) {
1682
+ if (typeof value !== 'string' || value.trim() === '') return '';
1683
+ return text(value, ctx, 'title', MAX_LABEL_CHARS);
1684
+ }
1685
+
1686
+ /** Explicit continuation reference, or null when absent/invalid/self-referential. */
1687
+ function continuationRef(value, taskId) {
1688
+ if (typeof value !== 'string') return null;
1689
+ const trimmed = value.trim();
1690
+ if (trimmed === '' || trimmed.length > MAX_LABEL_CHARS) return null;
1691
+ if (trimmed === taskId) return null;
1692
+ return trimmed;
1693
+ }
1694
+
1543
1695
  /**
1544
1696
  * A short, bounded reason string (a code or a one-line diagnostic), cut once and
1545
1697
  * the cut stated.