pi-goal-list-loop-audit 0.38.55 → 0.38.57

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/CHANGELOG.md CHANGED
@@ -1,5 +1,99 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.38.57 — Phased drafting, truthful waits and outcome-first summaries (2026-09-17)
4
+
5
+ ### Tool-first phased drafting
6
+
7
+ Structured drafting choices use the question picker when available; independent
8
+ questions are batched within visible phases, while dependent questions wait for
9
+ earlier answers. A narrowly detected promise-only ending after an answered
10
+ questionnaire gets one ownership- and lifecycle-fenced corrective handoff per
11
+ draft. Genuine questions, cancellation, replacement and busy hosts stand down.
12
+
13
+ ### Truthful pauses and outcome-first completion
14
+
15
+ Deliberate timed waits show scheduled continuation, untimed waits name the user
16
+ action, and durable recovery episodes retain retry ownership. Age alone no longer
17
+ labels queued work as monitoring. Completion chat leads with the outcome and
18
+ readable area groups rather than narrative tables; compact verification retains
19
+ failures, skips and unrun checks. Commands, hashes and repository bookkeeping
20
+ stay archival. Evidence stripping removes empty wrappers, approval is not repeated
21
+ in the header/table, and repair claims retain the whole-work recap in chat and
22
+ the archive. Archive evidence and approval/lifecycle barriers remain intact.
23
+
24
+ ### Paragraph seeds stay one list item
25
+
26
+ Typed multi-sentence prose to `/list` no longer routes to the
27
+ "Import into list?" sentence-split (field 2026-09-16 — the only
28
+ options were sentences-as-items or nothing). The router batches explicit
29
+ list structure (≥2 bulleted, numbered, or checklist lines) or independent
30
+ records with inline contracts / subtask declarations, identically for bare
31
+ `/list` and its add/import aliases. A standalone `Done when:` block stays
32
+ with its paragraph; contract-less prose drafts instead. The draft prompt
33
+ states the rule: a paragraph is ONE item proposed whole, split only on
34
+ request or when the interview establishes genuinely separate tasks.
35
+
36
+ ### Audit follow-up
37
+
38
+ Acknowledgment-prefixed compound tweaks such as “OK, fix login and update
39
+ its tests” remain explicit replacements, rather than being mistaken for
40
+ chatter and redirected to older session context. Added regression coverage
41
+ for routing boundaries, full paragraph seed forwarding, inferred-tweak
42
+ confirmation rejection, and held-loop history/reset and wrong-branch guards.
43
+
44
+ ## 0.38.56 — Refine-and-resume loops, chatter-resolving tweaks (2026-09-16)
45
+
46
+ ### Context-inferred tweak objectives
47
+
48
+ `/goal tweak`, `/list tweak`, and the bare-tweak dialog resolve chatter
49
+ against the session context instead of adopting it (field 2026-09-16 —
50
+ the VidPro ledger recorded `objective:"ok adjsut it"`). Self-contained
51
+ text still adopts verbatim; an acknowledgment (`go`, `ok adjust it`)
52
+ resolves via the discussed context and the confirm shows
53
+ CURRENT → INFERRED; with nothing clear discussed, a guidance message
54
+ names the shape and nothing changes. An explicit `Done when:` contract
55
+ stays verbatim — explicit intent wins. Raw chatter never reaches the
56
+ ledger on any adoption path (including the plain-`/goal` conflict
57
+ update, which funnels through the same resolver).
58
+
59
+ ### Loop-sweep refinability
60
+
61
+ `/loop refine` works on resumable-held loops (field 2026-09-16 loop
62
+ sweep): the hint queues, then the byte-identical resume path runs —
63
+ refine-and-resume (owner choice), with wrong-branch and active-goal
64
+ guards keeping their voices so the loop stays held when they fire. Dead
65
+ loops stay refused with the honest path (`/loop start` for ended runs,
66
+ the agent `propose_loop_refine` repair for broken measures — no hint is
67
+ queued onto a loop that can never run again). The agent tool predicate
68
+ accepts parked loops too, so both surfaces agree (parity matrix pinned;
69
+ broken-measure stays tool-only by design). `stop`/`pause`/`finish`/
70
+ `status`/`resume` already handled held loops gracefully — sweep found no
71
+ further dead spots.
72
+
73
+ ### Paused-goal tweak
74
+
75
+ `/goal tweak` accepts a paused goal instead of stranding it behind a
76
+ resume round-trip (field 2026-09-16, the VidPro park: tweak bounced
77
+ with "No active goal to tweak" while the goal sat paused). Mirrors
78
+ `/list tweak`, which is paused-only: the tweak applies, the goal stays
79
+ paused with its pause reason intact, nothing is scheduled, and the
80
+ result points at `/goal resume`. The nothing-to-tweak refusal now reads
81
+ "No goal to tweak. /goal <objective> to start one."
82
+
83
+ ### Structured-long summaries
84
+
85
+ A section-structured `Outcome` (2+ `##`–`####` headers, tables) now
86
+ renders in full as the card's `### Summary` section — a working document
87
+ is no longer truncated into a status ping (field 2026-09-16, the
88
+ keyword-review close). The card answers two questions, informative over
89
+ long: Summary carries what happened plus the horizon (slices 2–3),
90
+ `Next` still names only the single immediate move (slice 1). Structure
91
+ is the price of length: unstructured values keep today's budgets and
92
+ the headline echo stays short. Delivery-only (terminal card +
93
+ archive human layer) with a 100k pathological guard pointing at the
94
+ archive; headline, verification, recap, and every recycled per-tick
95
+ payload stay bounded.
96
+
3
97
  ## 0.38.55 — Full-parity terminal card, lenient auditor, agent resume (2026-09-16)
4
98
 
5
99
  ### Full-parity terminal card
package/docs/INDEX.md CHANGED
@@ -16,7 +16,7 @@ Policy contracts and recent changes live in the `audit/` directory of the
16
16
  failback; v0.35.9 hardened cross-version npm tarball checks; v0.35.10
17
17
  handles multi-entry npm dry-run reports; v0.35.11 accepts both npm report
18
18
  shapes; v0.35.12 supports npm 12's keyed pack reports; v0.35.13 fixes stale-API recovery loops.
19
- v0.35.14–v0.38.55 continue through the supervisor freeze (`/glla pause`),
19
+ v0.35.14–v0.38.57 continue through the supervisor freeze (`/glla pause`),
20
20
  load hold, auditor picker parity, Windows launch fix, zombie-watchdog
21
21
  subagent carve-out, due-wait backstop, the `/glla agents` visibility panel,
22
22
  durable state-root selection, blank-until-resume auditor context, frozen
@@ -182,26 +182,11 @@ export interface HumanCompletionBrief {
182
182
  export function chatSafeDetailValue(value: string): string {
183
183
  // v0.38.45 audit: loop the innermost-group strip to a fixpoint
184
184
  // (bounded) — a single pass left nested husks like "(log )" behind.
185
- let withoutGroups = value;
186
- for (let pass = 0; pass < 5; pass++) {
187
- const next = withoutGroups.replace(/\([^()]*\)/g, (group) => {
188
- // A parenthesized group that carries nothing but stripped tokens and
189
- // receipt words is machine packaging — drop the whole group so no
190
- // `( tarball )` husk survives. Groups with real words stay verbatim.
191
- const inner = group
192
- .slice(1, -1)
193
- .replace(/(?:\/var)?\/tmp\/\S+/g, "")
194
- .replace(/\S+\.tgz\b/g, "")
195
- .replace(/\btarballs?\b|\blogs?\b/gi, "");
196
- return /[a-z]/i.test(inner) ? group : "";
197
- });
198
- if (next === withoutGroups) break;
199
- withoutGroups = next;
200
- }
185
+ let withoutGroups = stripMachineGroups(value);
201
186
  const stripped = withoutGroups
202
187
  .replace(/(?:\/var)?\/tmp\/\S+/g, "")
203
188
  .replace(/\btarballs?\s+\S+\.tgz\b/gi, "")
204
- .replace(/\S+\.tgz\b/g, "")
189
+ .replace(/(?<!\S)\S+\.tgz\b/g, "")
205
190
  .replace(/\(\s*\)/g, "")
206
191
  .replace(/\s{2,}/g, " ")
207
192
  .trim();
@@ -217,12 +202,31 @@ export function humanCompletionBrief(
217
202
  text: string | undefined,
218
203
  outcomeBudget = 140,
219
204
  valueBudget = 120,
205
+ priorWholeWork?: string,
220
206
  ): HumanCompletionBrief {
221
207
  const lines = completionSummaryLines(text, Math.max(outcomeBudget, valueBudget));
222
208
  const rawOutcome = (lines[0] ?? "").replace(/^Outcome:\s*/, "");
223
- const outcome = clipSummaryValue(briefValueContent(rawOutcome) ?? "done", outcomeBudget);
209
+ // 2026-09-16 whole-work recap: when the audited claim is a delta-only
210
+ // repair note, the whole-work recap from the FIRST claim leads. The
211
+ // repair details still ride; the headline summarizes the whole work.
212
+ const priorLines = priorWholeWork ? completionSummaryLines(priorWholeWork, Math.max(outcomeBudget, valueBudget)) : [];
213
+ const priorDetails = priorLines ? priorLines.slice(1) : [];
214
+ const mergedDetails = [...priorDetails, ...lines.slice(1)];
215
+ const outcomeSource = priorLines[0]?.replace(/^Outcome:\s*/, "") ?? rawOutcome;
216
+ // 2026-09-16 field shots: the headline echo must summarize the ask, not
217
+ // flatten section-structured Outcome markdown into one clipped line. The
218
+ // lead paragraph (text before the first section header) is the human
219
+ // summary; headers ride only in the ### Summary section.
220
+ const structured = structuredSummaryLines(priorWholeWork ?? text);
221
+ const lead = structured
222
+ ? (structured.join("\n").split(/\n(?=#{2,4}\s)/)[0] ?? "")
223
+ .split("\n")
224
+ .filter((l) => l.trim() && !/^#{1,4}\s/.test(l.trim()))
225
+ .join(" ")
226
+ : "";
227
+ const outcome = clipSummaryValue(briefValueContent(lead || outcomeSource) ?? "done", outcomeBudget);
224
228
  const details: string[] = [];
225
- for (const line of lines.slice(1)) {
229
+ for (const line of mergedDetails) {
226
230
  const separator = line.indexOf(":");
227
231
  if (separator < 0) continue;
228
232
  const content = briefValueContent(line.slice(separator + 1));
@@ -289,6 +293,107 @@ export const RICH_OBJECTIVE_ECHO_CHARS = 80;
289
293
  export const RICH_TABLE_GROUP_THRESHOLD = 4;
290
294
  /** v0.38.50: evidence tokens per finding cell — density, not a dump. */
291
295
  export const RICH_EVIDENCE_TOKENS_PER_FINDING = 4;
296
+ /** Structured-long doctrine (field 2026-09-16 — the keyword-review close):
297
+ * a section-structured label value is a working document, not a status
298
+ * ping, and truncating it destroys its purpose. Structure is the price
299
+ * of length: at least this many `##`–`####` section headers keeps the
300
+ * value on the structured path; anything else keeps today's budgets.
301
+ * Delivery-only: the terminal card and the archive human layer. Recycled
302
+ * per-tick payloads (continuation, handoff, checkpoint) stay bounded. */
303
+ export const RICH_STRUCTURED_MIN_HEADERS = 2;
304
+ /** Structured-long guard against pathological megabytes: the tool call
305
+ * carries no length bound, so the structured path still ends — with an
306
+ * honest truncation note pointing at the archive, never silent soup. */
307
+ export const RICH_STRUCTURED_VALUE_BUDGET = 100_000;
308
+
309
+ /** Count markdown section headers (`##`–`####` with text) in raw text.
310
+ * H1 (`# `) is a document title, not a section — it does not count. */
311
+ export function countSectionHeaders(text: string): number {
312
+ const matches = (text ?? "").match(/^#{2,4}\s+\S/gm);
313
+ return matches ? matches.length : 0;
314
+ }
315
+
316
+ export function isSectionStructured(text: string): boolean {
317
+ return countSectionHeaders(text) >= RICH_STRUCTURED_MIN_HEADERS;
318
+ }
319
+
320
+ const STRUCTURED_LABELS = ["Outcome:", "Changed:", "Evidence:", "Tests:", "Unresolved:", "Next:"];
321
+
322
+ /** Raw (newline-preserving) label value for the structured path. Labels
323
+ * anchor to line starts and the last restatement wins — the same
324
+ * doctrine as labelPositions on the flattened path (v0.38.45). Residual
325
+ * ambiguity (a structured doc quoting `Changed:` at a line start) cuts
326
+ * the value early and the detector usually falls back to clipped
327
+ * rendering — doubt resolves to today's behavior, never to invention. */
328
+ export function rawLabelValue(text: string, label: string): string | null {
329
+ const source = text ?? "";
330
+ if (!source) return null;
331
+ const openings: number[] = [];
332
+ const openPattern = new RegExp(`^${label}`, "gim");
333
+ for (const match of source.matchAll(openPattern)) openings.push(match.index ?? 0);
334
+ if (openings.length === 0) return null;
335
+ const start = openings[openings.length - 1]! + label.length;
336
+ const restPattern = new RegExp(`^(${STRUCTURED_LABELS.filter((entry) => entry !== label).join("|")})`, "gim");
337
+ restPattern.lastIndex = start;
338
+ const next = restPattern.exec(source);
339
+ const end = next ? (next.index ?? source.length) : source.length;
340
+ const value = source.slice(start, end).trim();
341
+ return value || null;
342
+ }
343
+
344
+ /** Drop parenthesized groups whose content is nothing but machine
345
+ * packaging (paths, tarballs, log words) after inner stripping. Groups
346
+ * with real words stay verbatim. Bounded to a fixpoint so nested husks
347
+ * like "(log )" cannot survive. Shared by chat and structured strips. */
348
+ function stripMachineGroups(value: string): string {
349
+ let out = value;
350
+ for (let pass = 0; pass < 5; pass++) {
351
+ const next = out.replace(/\([^()]*\)/g, (group) => {
352
+ const inner = group
353
+ .slice(1, -1)
354
+ .replace(/(?:\/var)?\/tmp\/\S+/g, "")
355
+ .replace(/(?<!\S)\S+\.tgz\b/g, "")
356
+ .replace(/\btarballs?\b|\blogs?\b/gi, "");
357
+ return /\w/.test(inner) ? group : "";
358
+ });
359
+ if (next === out) break;
360
+ out = next;
361
+ }
362
+ return out;
363
+ }
364
+
365
+ /** Machine-token strip for structured lines. chatSafeDetailValue also
366
+ * collapses multi-space runs, which would damage markdown table
367
+ * alignment padding — structured lines keep their spacing and drop
368
+ * only the archive-only tokens. */
369
+ function stripMachineTokens(line: string): string {
370
+ return stripMachineGroups(line)
371
+ .replace(/(?:\/var)?\/tmp\/\S+/g, "")
372
+ // Attempt a greedy token match only at its start, not at every byte
373
+ // of a long nonmatching token (quadratic on pathological summaries).
374
+ .replace(/(?<!\S)\S+\.tgz\b/g, "")
375
+ .replace(/\(\s*\)/g, "")
376
+ .replace(/\s+([,.;:])/g, "$1")
377
+ .replace(/\s+$/u, "");
378
+ }
379
+
380
+ /** Full Outcome body for the `### Summary` card section, or null when
381
+ * the value is not section-structured (caller keeps today's budgets).
382
+ * Newlines and tables survive; machine paths stay archive-only; the
383
+ * pathological guard ends with an honest pointer, never silent soup. */
384
+ export function structuredSummaryLines(summary: string | undefined, label = "Outcome:"): string[] | null {
385
+ const raw = rawLabelValue(summary ?? "", label);
386
+ if (!raw || !isSectionStructured(raw)) return null;
387
+ const lines = raw.split("\n").map(stripMachineTokens);
388
+ while (lines.length > 0 && !(lines[0] ?? "").trim()) lines.shift();
389
+ while (lines.length > 0 && !(lines[lines.length - 1] ?? "").trim()) lines.pop();
390
+ let text = lines.join("\n");
391
+ const units = [...text];
392
+ if (units.length > RICH_STRUCTURED_VALUE_BUDGET) {
393
+ text = `${units.slice(0, RICH_STRUCTURED_VALUE_BUDGET).join("")}\n\n… (truncated for chat — full text in the archived record.)`;
394
+ }
395
+ return text.split("\n");
396
+ }
292
397
 
293
398
  export interface RichTerminalParts {
294
399
  /** v0.38.55 (full parity): verdict banner — `## Done — auditor
@@ -303,6 +408,11 @@ export interface RichTerminalParts {
303
408
  /** v0.38.55 (full parity): final repository state section lines.
304
409
  * Empty when the state could not be read (absent stays absent). */
305
410
  repoLines: string[];
411
+ /** Structured-long body (field 2026-09-16): full Outcome text with
412
+ * newlines preserved, rendered as `### Summary`. Empty unless the
413
+ * value earned the structured path — never a second copy of the
414
+ * clipped headline echo. */
415
+ summaryLines: string[];
306
416
  }
307
417
 
308
418
  function escapeTableCell(value: string): string {
@@ -350,10 +460,13 @@ export function extractEvidenceTokens(text: string): { text: string; evidence: s
350
460
  const stripped = text
351
461
  .replace(EVIDENCE_TOKEN_PATTERN, (match) => {
352
462
  if (evidence.length < RICH_EVIDENCE_TOKENS_PER_FINDING && !evidence.includes(match)) evidence.push(match);
463
+ // The token often rides in parentheses — move the wrapper too, so
464
+ // no "()" husk remains. Groups that still carry words stay intact.
353
465
  return "";
354
466
  })
355
- .replace(/\s+/g, " ")
467
+ .replace(/\(([^()]*)\)/g, (group, inner: string) => (/\w/.test(inner) ? group : ""))
356
468
  .replace(/\s+([,.;:])/g, "$1")
469
+ .replace(/\s{2,}/g, " ")
357
470
  .trim();
358
471
  return { text: stripped, evidence };
359
472
  }
@@ -399,6 +512,19 @@ export function requestEchoHeadline(kind: "Done" | "Aborted", objective: string
399
512
  return echo ? `## ${kind}: ${echo} \u2014 ${outcome}` : `## ${kind} \u2014 ${outcome}`;
400
513
  }
401
514
 
515
+ /** Chat-only projection: keep explanations and counts, not command/hash receipts. */
516
+ function chatNarrative(value: string): string {
517
+ return stripMachineGroups(chatSafeDetailValue(value)
518
+ .replace(/\b(?:fixed in|commit|HEAD(?: at)?|built from)\s+`?[a-f0-9]{7,64}`?/gi, "")
519
+ .replace(/\b(?=[a-f0-9]*[a-f])(?=[a-f0-9]*\d)[a-f0-9]{7,64}\b/gi, "")
520
+ .replace(/`(?:bun|npm|npx|node|git|tsc)\s+[^`]+`/g, "")
521
+ .replace(/\b(?:bun test|npm (?:run \S+|test)|npx tsc|tsc --noEmit)\b(?:\s+(?:--[\w=-]+|[\w./-]+\.(?:ts|js|mjs)))*/g, "")
522
+ .replace(/\(\s*[,;:]*\s*\)/g, "")
523
+ .replace(/\s+([,.;:])/g, "$1")
524
+ .replace(/\s{2,}/g, " ")
525
+ .trim());
526
+ }
527
+
402
528
  /** Build the section parts shared by chat, transcript, and archive.
403
529
  * v0.38.50: agent-structured groups render as `#### n. Area` subsections
404
530
  * with nested evidence bullets; at RICH_TABLE_GROUP_THRESHOLD groups the
@@ -472,15 +598,21 @@ export function buildRichTerminalParts(args: {
472
598
  * tree cleanliness) from the render call site, which owns cwd access.
473
599
  * Absent keeps the section out — never invented. */
474
600
  repoState?: string[];
601
+ /** Structured-long body lines from structuredSummaryLines. Absent
602
+ * keeps the `### Summary` section out (unstructured summaries keep
603
+ * today's headline-echo shape). */
604
+ summaryLines?: string[];
605
+ /** Chat favors explanations; the archive retains raw commands and tables. */
606
+ chat?: boolean;
475
607
  }): RichTerminalParts {
476
608
  const { findings, tests, next } = partitionRichDetails(args.details);
477
609
  const outcome = args.outcome;
478
610
  const kind = args.kind ?? "Done";
479
- const headline = requestEchoHeadline(kind, args.objective, outcome);
611
+ const headline = args.chat ? `## ${kind} — ${outcome}` : requestEchoHeadline(kind, args.objective, outcome);
480
612
  const auditStatus = auditRowStatus(args.auditHistory);
481
- const banner = `## ${kind} \u2014 ${bannerVerdict(auditStatus)}`;
613
+ const banner = args.chat ? headline : `## ${kind} \u2014 ${bannerVerdict(auditStatus)}`;
482
614
  const groups = args.groups ?? [];
483
- const useTable = groups.length >= RICH_TABLE_GROUP_THRESHOLD;
615
+ const useTable = !args.chat && groups.length >= RICH_TABLE_GROUP_THRESHOLD;
484
616
  const findingLines: string[] = [];
485
617
  if (useTable) {
486
618
  findingLines.push("| Area | Finding | Evidence |", "| --- | --- | --- |");
@@ -501,17 +633,17 @@ export function buildRichTerminalParts(args: {
501
633
  groups.forEach((group, i) => {
502
634
  findingLines.push(`#### ${i + 1}. ${group.title}`);
503
635
  group.findings.forEach((finding, fi) => {
504
- const { lead, body } = leadBody(finding);
636
+ const { lead, body } = leadBody(args.chat ? chatNarrative(extractEvidenceTokens(finding).text) : finding);
505
637
  findingLines.push(`- **${lead}** \u2014 ${body}`);
506
638
  // v0.38.52: per-finding test proof (shot C) — absent stays absent.
507
639
  const proof = group.tests?.[fi]?.trim();
508
- if (proof) findingLines.push(` - Test Results: ${proof}`);
640
+ if (proof) findingLines.push(` - Test Results: ${args.chat ? chatNarrative(proof) : proof}`);
509
641
  });
510
642
  });
511
643
  } else {
512
644
  // v0.38.55: the flat fallback renders every detail — no cap.
513
645
  findings.forEach((detail, i) => {
514
- const { lead, body } = leadBody(detail);
646
+ const { lead, body } = leadBody(args.chat ? chatNarrative(detail) : detail);
515
647
  findingLines.push(`${i + 1}. **${lead}** \u2014 ${body}`);
516
648
  });
517
649
  }
@@ -523,23 +655,24 @@ export function buildRichTerminalParts(args: {
523
655
  // v0.38.55: every row renders with its repro command when any row
524
656
  // carries one (Stage | Command | Result | Notes parity) — no row cap.
525
657
  const gates = args.gates ?? [];
526
- const showCommand = gates.some((row) => row.command?.trim());
658
+ const showCommand = !args.chat && gates.some((row) => row.command?.trim());
527
659
  if (gates.length > 0) {
528
660
  for (const row of gates) {
529
661
  const derived = testsRowStatus(row.notes ?? "");
662
+ const notes = args.chat ? chatNarrative(row.notes ?? "") : row.notes?.trim();
530
663
  const command = row.command?.trim() || "\u2014";
531
664
  tableRows.push(showCommand
532
- ? `| ${escapeTableCell(row.gate)} | ${escapeTableCell(command)} | ${escapeTableCell(row.scope?.trim() || "\u2014")} | ${derived} | ${escapeTableCell(row.notes?.trim() || "\u2014")} |`
533
- : `| ${escapeTableCell(row.gate)} | ${escapeTableCell(row.scope?.trim() || "\u2014")} | ${derived} | ${escapeTableCell(row.notes?.trim() || "\u2014")} |`);
665
+ ? `| ${escapeTableCell(row.gate)} | ${escapeTableCell(command)} | ${escapeTableCell(row.scope?.trim() || "\u2014")} | ${derived} | ${escapeTableCell(notes || "\u2014")} |`
666
+ : `| ${escapeTableCell(row.gate)} | ${escapeTableCell(row.scope?.trim() || "\u2014")} | ${derived} | ${escapeTableCell(notes || "\u2014")} |`);
534
667
  }
535
668
  } else {
536
669
  for (const detail of tests) {
537
670
  const { body } = leadBody(detail);
538
671
  const status = testsRowStatus(body);
539
- tableRows.push(`| Tests | ${status} | ${escapeTableCell(body)} |`);
672
+ tableRows.push(`| Tests | ${status} | ${escapeTableCell(args.chat ? chatNarrative(body) : body)} |`);
540
673
  }
541
674
  }
542
- if (auditStatus !== "NO VERDICT") {
675
+ if (!args.chat && auditStatus !== "NO VERDICT") {
543
676
  const auditBody = args.countsLine.replace(/^\u2014\s*/, "").replace(/\.\s*$/, "");
544
677
  // v0.38.55 audit: the Audit row's Scope names the row kind — the old
545
678
  // shape duplicated the counts text in Scope and Notes.
@@ -572,7 +705,8 @@ export function buildRichTerminalParts(args: {
572
705
  findingLines,
573
706
  tableLines,
574
707
  nextLines,
575
- repoLines: args.repoState ?? [],
708
+ repoLines: args.chat ? [] : args.repoState ?? [],
709
+ summaryLines: args.summaryLines ?? [],
576
710
  };
577
711
  }
578
712
 
@@ -587,6 +721,14 @@ export function composeRichTerminalLines(parts: RichTerminalParts): string[] {
587
721
  const lines = [parts.banner ?? parts.headline, ""];
588
722
  if (parts.headline !== lines[0]) lines.push(parts.headline, "");
589
723
  if (parts.durationLine) lines.push(parts.durationLine, "");
724
+ // Structured-long (field 2026-09-16): the full Outcome body rides its
725
+ // own section between the headline and the findings — findings-first
726
+ // order is preserved (findings, verification, Next keep their relative
727
+ // order), the headline echo stays short, and the one-action Next rule
728
+ // is untouched.
729
+ if (parts.summaryLines.length > 0) {
730
+ lines.push("### Summary", ...parts.summaryLines, "");
731
+ }
590
732
  if (parts.findingLines.length > 0) {
591
733
  lines.push("### Key Findings & Remediation", ...parts.findingLines, "");
592
734
  }
@@ -607,10 +749,16 @@ export function composeRichTerminalLines(parts: RichTerminalParts): string[] {
607
749
  * raw six-label recap stays verbatim in `## Completion summary` as the
608
750
  * machine layer. Headline follows terminal status; aborted records never
609
751
  * wear a `Done` headline. */
610
- export function buildRichArchiveSection(goal: Goal, status: Status, archivePath: string, findingGroups?: FindingGroup[], gateRows?: GateRow[]): string[] {
752
+ export function buildRichArchiveSection(goal: Goal, status: Status, archivePath: string, findingGroups?: FindingGroup[], gateRows?: GateRow[], priorWholeWorkOverride?: string): string[] {
611
753
  const facts: CompletionSummaryFacts = { goal, status, archivePath };
612
754
  const summary = resolveCompletionSummary(facts, goal.completionSummary).summary;
613
- const brief = humanCompletionBrief(summary, 140, RICH_FULL_VALUE_BUDGET);
755
+ // 2026-09-16 whole-work recap: after a repair re-claim, the archived
756
+ // card leads with the whole work. The caller (archiveCurrentGoal)
757
+ // captures the claim's carried recap BEFORE pendingCompletion is
758
+ // cleared; the goal-field fallback covers direct callers.
759
+ const priorWholeWork = priorWholeWorkOverride ?? goal.pendingCompletion?.priorCompletionSummary;
760
+ const brief = humanCompletionBrief(summary, 140, RICH_FULL_VALUE_BUDGET, priorWholeWork);
761
+ const structured = structuredSummaryLines(priorWholeWork ?? summary);
614
762
  const history = goal.auditHistory ?? [];
615
763
  const latest = history[history.length - 1];
616
764
  const approval = latest
@@ -628,12 +776,14 @@ export function buildRichArchiveSection(goal: Goal, status: Status, archivePath:
628
776
  gates: gateRows,
629
777
  // v0.38.55: aborted records never wear a Done banner/headline.
630
778
  kind: status === "complete" ? "Done" : "Aborted",
779
+ ...(structured ? { summaryLines: structured } : {}),
631
780
  });
632
781
  return [
633
782
  ...composeRichTerminalLines(parts),
634
783
  trailerBullet(stripApprovalModel(approval)),
635
784
  trailerBullet(countsLine),
636
785
  trailerBullet(`\u2014 record: ${archivePath}`),
786
+ ...(priorWholeWork ? ["", "## Original completion claim (verbatim)", "", priorWholeWork] : []),
637
787
  ];
638
788
  }
639
789
 
@@ -736,6 +886,11 @@ export interface TerminalApprovalRenderInput {
736
886
  * buildFinalRepoStateLines(cwd). Absent keeps the section out.
737
887
  */
738
888
  repoState?: string[];
889
+ /** 2026-09-16 whole-work recap: the FIRST claim's completionSummary in
890
+ * this terminal episode. When the audited claim is a delta-only repair
891
+ * note, the render leads with the whole work instead (headline, Summary
892
+ * section, and the flat findings fallback); absent stays absent. */
893
+ priorCompletionSummary?: string;
739
894
  }
740
895
 
741
896
  export interface TerminalApprovalRender {
@@ -777,7 +932,14 @@ export function buildTerminalApprovalRender(input: TerminalApprovalRenderInput):
777
932
  resolveCompletionSummary(facts, candidate).summary,
778
933
  140,
779
934
  RICH_FULL_VALUE_BUDGET,
935
+ input.priorCompletionSummary,
780
936
  );
937
+ // Structured-long (field 2026-09-16): a section-structured Outcome
938
+ // earns the full `### Summary` section on the terminal card (and the
939
+ // archive human layer). Headline echo, verification, Next, recap, and
940
+ // every recycled payload keep their bounds.
941
+ const resolvedSummary = resolveCompletionSummary(facts, candidate).summary;
942
+ const structured = structuredSummaryLines(input.priorCompletionSummary ?? resolvedSummary);
781
943
  // v0.38.37 (audit 2026-09-08): the deliberate non-do comes from the
782
944
  // agent's complete_goal leftOut claim — never invented. Filler ("none")
783
945
  // drops via the same briefValueContent filter; absent stays absent.
@@ -812,6 +974,7 @@ export function buildTerminalApprovalRender(input: TerminalApprovalRenderInput):
812
974
  // knows. The transcript mirrors chat; the archive keeps the full table
813
975
  // and full text plus the machine layer.
814
976
  const richParts = buildRichTerminalParts({
977
+ chat: true,
815
978
  outcome: richBrief.outcome,
816
979
  details: withoutStaleNext(richDetails),
817
980
  countsLine,
@@ -821,6 +984,7 @@ export function buildTerminalApprovalRender(input: TerminalApprovalRenderInput):
821
984
  groups: input.findingGroups,
822
985
  gates: input.gateRows,
823
986
  ...(input.repoState ? { repoState: input.repoState } : {}),
987
+ ...(structured ? { summaryLines: structured } : {}),
824
988
  });
825
989
  const chatBody = composeRichTerminalLines(richParts);
826
990
  const transcriptBody = composeRichTerminalLines(richParts);
@@ -0,0 +1,42 @@
1
+ /** Observes a narrow, positively identified unfinished drafting handoff.
2
+ * Silence and punctuation alone are never evidence that a user wait is
3
+ * broken. The caller owns lifecycle-fenced, once-only dispatch.
4
+ */
5
+ export class DraftingHandoffObserver {
6
+ private answered = false;
7
+ private notified = false;
8
+ revision = 0;
9
+
10
+ invalidate(): void { this.revision++; }
11
+
12
+ reset(): void {
13
+ this.invalidate();
14
+ this.answered = false;
15
+ this.notified = false;
16
+ }
17
+
18
+ noteUserReply(): void { this.invalidate(); this.answered = true; }
19
+
20
+ noteToolResult(toolName: string, answered: boolean): void {
21
+ this.invalidate();
22
+ // A new question or proposal supersedes earlier answer evidence, even
23
+ // on Escape, missing details, error, or a rejected confirmation.
24
+ if (toolName === "ask_user_question") this.answered = answered;
25
+ if (toolName === "propose_goal_draft" || toolName === "propose_loop_draft") this.answered = false;
26
+ }
27
+
28
+ observe(text: string, stopReason: string | undefined): boolean {
29
+ if (!this.answered || this.notified || stopReason !== "stop") return false;
30
+ const lastLine = text.trim().split("\n").at(-1)?.trim() ?? "";
31
+ // Match the field screenshot's dangling introduction, not a real
32
+ // question, imperative request, option list, or arbitrary short reply.
33
+ if (!/^(?:two|three|four|[2-4]) (?:final |remaining )?(?:policy )?(?:choices|questions|decisions) (?:will|would) make (?:the |our )?(?:implementation )?(?:contract|scope|plan) concrete:\s*$/i.test(lastLine)) return false;
34
+ if (text.includes("?")) return false;
35
+ this.notified = true;
36
+ this.answered = false;
37
+ return true;
38
+ }
39
+ }
40
+
41
+ export const draftingHandoff = new DraftingHandoffObserver();
42
+ export const DRAFT_HANDOFF_CORRECTION = "[DRAFT HANDOFF CORRECTION] You announced more questions but did not present them. Continue drafting now: use ask_user_question for the missing structured choices when available, or ask the genuinely free-form question in conversation. If the contract is already concrete, call the drafting proposal tool instead. Never invent answers or activate work without confirmation. This is a one-time correction, not a user answer.";
@@ -39,7 +39,7 @@ import { formatGllaVersion } from "./glla-version.js";
39
39
  import { cmdGllaOwner, cmdGllaTakeover } from "./state-root-owner.js";
40
40
  import { AUDIT_JOB_CLEANUP_MIN_AGE_MS, cancelDetachedGoalCompletionAuditor, cleanupDeadAuditJobs, inspectAuditJobHealth, DEFAULT_AUDITOR_STALL_MS, DEFAULT_AUDITOR_TOOL_TIMEOUT_MS } from "./goal-loop-auditor-process.js";
41
41
  import { releaseAuditorSurface } from "./loops/goal-auditor-surface.js";
42
- import { inferStartFromSession, type StartContextInference } from "./start-context.js";
42
+ import { inferStartFromSession, resolveTweakReplacement, type StartContextInference } from "./start-context.js";
43
43
 
44
44
  /** Child pi sessions live under the shared session store, munged by cwd
45
45
  * (verified layout: ~/.pi/agent/sessions/--home-user-proj--/*.jsonl). */
@@ -755,11 +755,17 @@ export async function cmdTweak(
755
755
  && current?.policy === "list"
756
756
  && (current.status === "active" || current.status === "auditing");
757
757
  const expectedStatus = mode === "list" ? "paused" : "active";
758
- if (!current || (current.status !== expectedStatus && !liveListConflict) || (mode === "list" && current.policy !== "list")) {
758
+ // Field 2026-09-16 (the VidPro park): /goal tweak accepts a paused goal
759
+ // instead of stranding it behind a resume round-trip. Mirrors /list
760
+ // tweak, which is paused-only and stays paused.
761
+ const tweakable = mode === "list"
762
+ ? current?.status === expectedStatus
763
+ : current?.status === "active" || current?.status === "paused";
764
+ if (!current || (!tweakable && !liveListConflict) || (mode === "list" && current.policy !== "list")) {
759
765
  ctx.ui.notify(
760
766
  mode === "list"
761
767
  ? "No paused list item to tweak. /list tweak <replacement objective, optional 'Done when: ...' clause>"
762
- : "No active goal to tweak. /goal <objective> to start one.",
768
+ : "No goal to tweak. /goal <objective> to start one.",
763
769
  "info",
764
770
  );
765
771
  return false;
@@ -797,7 +803,29 @@ export async function cmdTweak(
797
803
  }
798
804
  raw = v.trim();
799
805
  }
800
- const proposed = extractVerificationContract(raw);
806
+ // Field 2026-09-16 (VidPro ledger — `/goal tweak` adopted "ok adjsut it"
807
+ // as the objective): chatter is a pointer at the session context, not a
808
+ // replacement. Resolve it against what was actually discussed; guide when
809
+ // nothing clear was discussed. Raw chatter never reaches the ledger.
810
+ // This sits in cmdTweak because all adoption paths funnel here: /goal
811
+ // tweak, /list tweak, and the plain-/goal "Update current objective"
812
+ // conflict choice (via updateWholeObjectiveFromConflict).
813
+ const replacement = resolveTweakReplacement(raw, ctx.sessionManager);
814
+ let adopted = raw;
815
+ let inferredNote = "";
816
+ if (replacement.kind === "inferred") {
817
+ adopted = replacement.text;
818
+ inferredNote = ` (inferred from ${replacement.source === "recent-context" ? "recent discussion" : "your message"} — yours read "${displaySlice(raw, 80)}"; cancel and re-run with exact wording if this is wrong)`;
819
+ } else if (replacement.kind === "unresolvable") {
820
+ const surface = mode === "list" ? "list item" : "goal";
821
+ let guidance = `That reads as an acknowledgment rather than a replacement ("${displaySlice(raw, 80)}") — nothing changed. The ${surface} keeps: ${displaySlice(current.objective, 120)}. Say what it should become as full replacement text.`;
822
+ if (replacement.reason === "ambiguous" && replacement.candidates.length > 0) {
823
+ guidance += ` It could mean: ${replacement.candidates.slice(0, 2).map((c) => `"${displaySlice(c, 100)}"`).join(" / ")} — re-run with one in full.`;
824
+ }
825
+ ctx.ui.notify(guidance, "info");
826
+ return false;
827
+ }
828
+ const proposed = extractVerificationContract(adopted);
801
829
  const newObjective = proposed.objective;
802
830
  if (!newObjective) {
803
831
  // (a bare input of "Done when: ..." only yields this — the replacement
@@ -833,7 +861,7 @@ export async function cmdTweak(
833
861
  try {
834
862
  confirmed = await ctx.ui.confirm(
835
863
  mode === "list" ? "Tweak list item?" : "Tweak goal?",
836
- `CURRENT:\n${sanitizeDisplayText(current.objective)}\n\nNEW:\n${sanitizeDisplayText(newObjective)}` +
864
+ `CURRENT:\n${sanitizeDisplayText(current.objective)}\n\nNEW${inferredNote}:\n${sanitizeDisplayText(newObjective)}` +
837
865
  (hasNewContract
838
866
  ? `\n\nNew contract:\n${sanitizeDisplayText(proposed.verificationContract)}`
839
867
  : clearsContract
@@ -862,7 +890,7 @@ export async function cmdTweak(
862
890
  return false;
863
891
  }
864
892
  const priorProvenance = latest.objectiveProvenance;
865
- const userSeeds = [...(priorProvenance?.userSeeds ?? []), raw].slice(-10);
893
+ const userSeeds = [...(priorProvenance?.userSeeds ?? []), adopted].slice(-10);
866
894
  const replacingLiveList = liveListConflict
867
895
  && latest.policy === "list"
868
896
  && (latest.status === "active" || latest.status === "auditing");
@@ -921,6 +949,14 @@ export async function cmdTweak(
921
949
  ctx.ui.notify("List item tweaked; it remains paused. /list resume to continue.", "info");
922
950
  return true;
923
951
  }
952
+ // A paused goal stays paused — the tweak must not wake the loop (field
953
+ // 2026-09-16: the VidPro park re-parked on every wake, which is the
954
+ // hamster wheel in the report). The user resumes explicitly when the
955
+ // blocker clears.
956
+ if (latest.status === "paused") {
957
+ ctx.ui.notify("Goal tweaked; it remains paused. /goal resume to continue.", "info");
958
+ return true;
959
+ }
924
960
  ctx.ui.notify("Goal tweaked. The loop continues against the new objective.", "info");
925
961
  scheduleContinuation(ctx, true);
926
962
  return true;
@@ -1397,7 +1433,7 @@ async function cmdList(args: string, ctx: ExtensionContext): Promise<void> {
1397
1433
  await startDrafting(ctx, "list");
1398
1434
  return;
1399
1435
  }
1400
- const aliased = routeListText(ctx.cwd, rest.replace(/^["']|["']$/g, ""));
1436
+ const aliased = routeListText(ctx.cwd, rest.replace(/^["']|["']$/g, ""), { explicitAdd: true });
1401
1437
  if (aliased.kind === "file") {
1402
1438
  await bulkAddFromFile(ctx, aliased.path);
1403
1439
  return;