@sun-asterisk/sungen 3.3.0-alpha.5 → 3.3.0-alpha.7

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.
Files changed (206) hide show
  1. package/dist/cli/commands/contract-derive-command.d.ts.map +1 -1
  2. package/dist/cli/commands/contract-derive-command.js +2 -0
  3. package/dist/cli/commands/contract-derive-command.js.map +1 -1
  4. package/dist/cli/commands/delivery.d.ts.map +1 -1
  5. package/dist/cli/commands/delivery.js +21 -3
  6. package/dist/cli/commands/delivery.js.map +1 -1
  7. package/dist/cli/commands/generate.d.ts.map +1 -1
  8. package/dist/cli/commands/generate.js +3 -1
  9. package/dist/cli/commands/generate.js.map +1 -1
  10. package/dist/cli/commands/next.d.ts +5 -2
  11. package/dist/cli/commands/next.d.ts.map +1 -1
  12. package/dist/cli/commands/next.js +14 -1
  13. package/dist/cli/commands/next.js.map +1 -1
  14. package/dist/cli/commands/triage.d.ts +2 -1
  15. package/dist/cli/commands/triage.d.ts.map +1 -1
  16. package/dist/cli/commands/triage.js +42 -2
  17. package/dist/cli/commands/triage.js.map +1 -1
  18. package/dist/cli/commands/update.d.ts.map +1 -1
  19. package/dist/cli/commands/update.js +6 -2
  20. package/dist/cli/commands/update.js.map +1 -1
  21. package/dist/cli/index.js +4 -0
  22. package/dist/cli/index.js.map +1 -1
  23. package/dist/cli/json-error-on-exit.d.ts +34 -0
  24. package/dist/cli/json-error-on-exit.d.ts.map +1 -0
  25. package/dist/cli/json-error-on-exit.js +63 -0
  26. package/dist/cli/json-error-on-exit.js.map +1 -0
  27. package/dist/cli/waiting-for-you-block.d.ts +15 -0
  28. package/dist/cli/waiting-for-you-block.d.ts.map +1 -0
  29. package/dist/cli/waiting-for-you-block.js +19 -0
  30. package/dist/cli/waiting-for-you-block.js.map +1 -0
  31. package/dist/contract/derive-free-feature.d.ts +2 -0
  32. package/dist/contract/derive-free-feature.d.ts.map +1 -1
  33. package/dist/contract/derive-free-feature.js +22 -0
  34. package/dist/contract/derive-free-feature.js.map +1 -1
  35. package/dist/decisions/decision-schema.d.ts +2 -1
  36. package/dist/decisions/decision-schema.d.ts.map +1 -1
  37. package/dist/decisions/decision-schema.js +2 -1
  38. package/dist/decisions/decision-schema.js.map +1 -1
  39. package/dist/decisions/legacy-waiver-migration.d.ts +2 -0
  40. package/dist/decisions/legacy-waiver-migration.d.ts.map +1 -1
  41. package/dist/decisions/legacy-waiver-migration.js +5 -2
  42. package/dist/decisions/legacy-waiver-migration.js.map +1 -1
  43. package/dist/graph/board-human-actions.d.ts +5 -0
  44. package/dist/graph/board-human-actions.d.ts.map +1 -0
  45. package/dist/graph/board-human-actions.js +83 -0
  46. package/dist/graph/board-human-actions.js.map +1 -0
  47. package/dist/graph/evaluate-graph.d.ts +16 -0
  48. package/dist/graph/evaluate-graph.d.ts.map +1 -1
  49. package/dist/graph/evaluate-graph.js +29 -6
  50. package/dist/graph/evaluate-graph.js.map +1 -1
  51. package/dist/graph/human-action.d.ts +21 -0
  52. package/dist/graph/human-action.d.ts.map +1 -0
  53. package/dist/graph/human-action.js +3 -0
  54. package/dist/graph/human-action.js.map +1 -0
  55. package/dist/graph/manual-triage-decisions.d.ts +19 -0
  56. package/dist/graph/manual-triage-decisions.d.ts.map +1 -0
  57. package/dist/graph/manual-triage-decisions.js +53 -0
  58. package/dist/graph/manual-triage-decisions.js.map +1 -0
  59. package/dist/graph/node-decl.d.ts +9 -0
  60. package/dist/graph/node-decl.d.ts.map +1 -1
  61. package/dist/graph/node-decl.js +4 -1
  62. package/dist/graph/node-decl.js.map +1 -1
  63. package/dist/graph/nodes/test-case-contract-nodes.d.ts.map +1 -1
  64. package/dist/graph/nodes/test-case-contract-nodes.js +16 -3
  65. package/dist/graph/nodes/test-case-contract-nodes.js.map +1 -1
  66. package/dist/graph/nodes/test-case-nodes.d.ts +3 -0
  67. package/dist/graph/nodes/test-case-nodes.d.ts.map +1 -1
  68. package/dist/graph/nodes/test-case-nodes.js +33 -4
  69. package/dist/graph/nodes/test-case-nodes.js.map +1 -1
  70. package/dist/graph/nodes/unit-audit-nodes.d.ts.map +1 -1
  71. package/dist/graph/nodes/unit-audit-nodes.js +1 -0
  72. package/dist/graph/nodes/unit-audit-nodes.js.map +1 -1
  73. package/dist/graph/nodes/unit-contract-node.d.ts.map +1 -1
  74. package/dist/graph/nodes/unit-contract-node.js +8 -0
  75. package/dist/graph/nodes/unit-contract-node.js.map +1 -1
  76. package/dist/graph/test-case-results.d.ts +1 -0
  77. package/dist/graph/test-case-results.d.ts.map +1 -1
  78. package/dist/graph/test-case-results.js +27 -3
  79. package/dist/graph/test-case-results.js.map +1 -1
  80. package/dist/graph/test-case-satisfied.d.ts +5 -4
  81. package/dist/graph/test-case-satisfied.d.ts.map +1 -1
  82. package/dist/graph/test-case-satisfied.js +4 -0
  83. package/dist/graph/test-case-satisfied.js.map +1 -1
  84. package/dist/graph/test-case-state-shape.d.ts +7 -1
  85. package/dist/graph/test-case-state-shape.d.ts.map +1 -1
  86. package/dist/graph/unit-results-freshness.d.ts +29 -0
  87. package/dist/graph/unit-results-freshness.d.ts.map +1 -0
  88. package/dist/graph/unit-results-freshness.js +213 -0
  89. package/dist/graph/unit-results-freshness.js.map +1 -0
  90. package/dist/harness/audit.d.ts +3 -2
  91. package/dist/harness/audit.d.ts.map +1 -1
  92. package/dist/harness/audit.js +4 -17
  93. package/dist/harness/audit.js.map +1 -1
  94. package/dist/harness/catalog/gate-rules.yaml +1 -1
  95. package/dist/harness/defect-draft.d.ts.map +1 -1
  96. package/dist/harness/defect-draft.js +12 -2
  97. package/dist/harness/defect-draft.js.map +1 -1
  98. package/dist/harness/defects.d.ts +14 -0
  99. package/dist/harness/defects.d.ts.map +1 -1
  100. package/dist/harness/defects.js +14 -10
  101. package/dist/harness/defects.js.map +1 -1
  102. package/dist/harness/flow-check.d.ts +9 -0
  103. package/dist/harness/flow-check.d.ts.map +1 -1
  104. package/dist/harness/flow-check.js +11 -0
  105. package/dist/harness/flow-check.js.map +1 -1
  106. package/dist/harness/gates/audit-gate-verdict.d.ts.map +1 -1
  107. package/dist/harness/gates/audit-gate-verdict.js +2 -1
  108. package/dist/harness/gates/audit-gate-verdict.js.map +1 -1
  109. package/dist/harness/gates/audit-input-hash.d.ts +2 -0
  110. package/dist/harness/gates/audit-input-hash.d.ts.map +1 -1
  111. package/dist/harness/gates/audit-input-hash.js +30 -2
  112. package/dist/harness/gates/audit-input-hash.js.map +1 -1
  113. package/dist/harness/gates/audit-report-verification.js +1 -1
  114. package/dist/harness/gates/audit-report-verification.js.map +1 -1
  115. package/dist/harness/gates/delivery-checklist.d.ts +3 -0
  116. package/dist/harness/gates/delivery-checklist.d.ts.map +1 -1
  117. package/dist/harness/gates/delivery-checklist.js +37 -4
  118. package/dist/harness/gates/delivery-checklist.js.map +1 -1
  119. package/dist/harness/gates/in-run-decision-check.d.ts.map +1 -1
  120. package/dist/harness/gates/in-run-decision-check.js +21 -1
  121. package/dist/harness/gates/in-run-decision-check.js.map +1 -1
  122. package/dist/harness/journey.d.ts +21 -0
  123. package/dist/harness/journey.d.ts.map +1 -1
  124. package/dist/harness/journey.js +61 -11
  125. package/dist/harness/journey.js.map +1 -1
  126. package/dist/harness/next-step.d.ts +17 -0
  127. package/dist/harness/next-step.d.ts.map +1 -1
  128. package/dist/harness/next-step.js +19 -0
  129. package/dist/harness/next-step.js.map +1 -1
  130. package/dist/harness/triage-manual-classification.d.ts +32 -0
  131. package/dist/harness/triage-manual-classification.d.ts.map +1 -0
  132. package/dist/harness/triage-manual-classification.js +56 -0
  133. package/dist/harness/triage-manual-classification.js.map +1 -0
  134. package/dist/harness/unit-paths.d.ts +8 -0
  135. package/dist/harness/unit-paths.d.ts.map +1 -1
  136. package/dist/harness/unit-paths.js +23 -1
  137. package/dist/harness/unit-paths.js.map +1 -1
  138. package/dist/hooks/guard-tty-spoof-rule.d.ts +3 -1
  139. package/dist/hooks/guard-tty-spoof-rule.d.ts.map +1 -1
  140. package/dist/hooks/guard-tty-spoof-rule.js +3 -2
  141. package/dist/hooks/guard-tty-spoof-rule.js.map +1 -1
  142. package/dist/hooks/hand-back-core.d.ts +1 -1
  143. package/dist/hooks/hand-back-core.d.ts.map +1 -1
  144. package/dist/hooks/hand-back-core.js +4 -2
  145. package/dist/hooks/hand-back-core.js.map +1 -1
  146. package/dist/hooks/session-start-unit-state-hook.d.ts +2 -1
  147. package/dist/hooks/session-start-unit-state-hook.d.ts.map +1 -1
  148. package/dist/hooks/session-start-unit-state-hook.js +4 -1
  149. package/dist/hooks/session-start-unit-state-hook.js.map +1 -1
  150. package/dist/hooks/stop-next-step-hook.d.ts.map +1 -1
  151. package/dist/hooks/stop-next-step-hook.js +1 -0
  152. package/dist/hooks/stop-next-step-hook.js.map +1 -1
  153. package/dist/orchestrator/templates/ai-src/commands/delivery.md +2 -0
  154. package/dist/orchestrator/templates/ai-src/commands/review.md +2 -0
  155. package/dist/orchestrator/templates/ai-src/partials/waiting-for-you.claude.md +11 -0
  156. package/dist/orchestrator/templates/ai-src/partials/waiting-for-you.codex.md +11 -0
  157. package/dist/orchestrator/templates/ai-src/partials/waiting-for-you.copilot.md +11 -0
  158. package/package.json +3 -3
  159. package/src/cli/commands/contract-derive-command.ts +1 -0
  160. package/src/cli/commands/delivery.ts +20 -3
  161. package/src/cli/commands/generate.ts +3 -1
  162. package/src/cli/commands/next.ts +14 -3
  163. package/src/cli/commands/triage.ts +38 -2
  164. package/src/cli/commands/update.ts +6 -2
  165. package/src/cli/index.ts +4 -0
  166. package/src/cli/json-error-on-exit.ts +72 -0
  167. package/src/cli/waiting-for-you-block.ts +23 -0
  168. package/src/contract/derive-free-feature.ts +21 -0
  169. package/src/decisions/decision-schema.ts +2 -1
  170. package/src/decisions/legacy-waiver-migration.ts +5 -1
  171. package/src/graph/board-human-actions.ts +80 -0
  172. package/src/graph/evaluate-graph.ts +37 -8
  173. package/src/graph/human-action.ts +33 -0
  174. package/src/graph/manual-triage-decisions.ts +55 -0
  175. package/src/graph/node-decl.ts +11 -0
  176. package/src/graph/nodes/test-case-contract-nodes.ts +20 -4
  177. package/src/graph/nodes/test-case-nodes.ts +37 -5
  178. package/src/graph/nodes/unit-audit-nodes.ts +2 -1
  179. package/src/graph/nodes/unit-contract-node.ts +12 -1
  180. package/src/graph/test-case-results.ts +25 -4
  181. package/src/graph/test-case-satisfied.ts +7 -4
  182. package/src/graph/test-case-state-shape.ts +7 -2
  183. package/src/graph/unit-results-freshness.ts +165 -0
  184. package/src/harness/audit.ts +4 -13
  185. package/src/harness/catalog/gate-rules.yaml +1 -1
  186. package/src/harness/defect-draft.ts +13 -2
  187. package/src/harness/defects.ts +22 -9
  188. package/src/harness/flow-check.ts +11 -0
  189. package/src/harness/gates/audit-gate-verdict.ts +2 -1
  190. package/src/harness/gates/audit-input-hash.ts +27 -3
  191. package/src/harness/gates/audit-report-verification.ts +2 -2
  192. package/src/harness/gates/delivery-checklist.ts +37 -5
  193. package/src/harness/gates/in-run-decision-check.ts +22 -1
  194. package/src/harness/journey.ts +79 -8
  195. package/src/harness/next-step.ts +31 -1
  196. package/src/harness/triage-manual-classification.ts +76 -0
  197. package/src/harness/unit-paths.ts +19 -0
  198. package/src/hooks/guard-tty-spoof-rule.ts +6 -3
  199. package/src/hooks/hand-back-core.ts +4 -2
  200. package/src/hooks/session-start-unit-state-hook.ts +4 -1
  201. package/src/hooks/stop-next-step-hook.ts +1 -0
  202. package/src/orchestrator/templates/ai-src/commands/delivery.md +2 -0
  203. package/src/orchestrator/templates/ai-src/commands/review.md +2 -0
  204. package/src/orchestrator/templates/ai-src/partials/waiting-for-you.claude.md +11 -0
  205. package/src/orchestrator/templates/ai-src/partials/waiting-for-you.codex.md +11 -0
  206. package/src/orchestrator/templates/ai-src/partials/waiting-for-you.copilot.md +11 -0
@@ -243,6 +243,52 @@ function computeNext(r: JourneyReport, unit: string): string {
243
243
  * A read-only checkout gets the same board without throwing.
244
244
  */
245
245
  export function runJourney(projectRoot: string, unit: string): JourneyReport {
246
+ const r = reconcileJourney(projectRoot, unit);
247
+ try {
248
+ commitWaiverSync(projectRoot, unit, r.slug, r.sync, r.statePath, JSON.stringify(r.next, null, 2));
249
+ } catch (err) {
250
+ if (!(err instanceof DecisionConflictError)) throw err;
251
+ const rel = path.relative(projectRoot, err.path).split(path.sep).join('/');
252
+ if (!r.decisionFindings.some((f) => f.path === rel)) r.decisionFindings.push({ rule: 'decision.mutated', path: rel, message: err.message });
253
+ }
254
+ return finishReport(r, unit);
255
+ }
256
+
257
+ /** A waiver the board asks a human to give again: its evidence moved (stale), or git HEAD does not hold it (untrusted). */
258
+ export interface WaiverToRedecide { obligation: string; title: string; reason: string; why: 'stale' | 'untrusted' }
259
+
260
+ /** What the board asks of a human, read without writing anything (`sungen next`'s "Waiting for you", #954). */
261
+ export interface JourneyHumanAsks {
262
+ report: JourneyReport;
263
+ redecide: WaiverToRedecide[];
264
+ /** OB-signoff: `pending` (never given), `stale` (given before the audit changed), `given`. */
265
+ signoff: { status: 'pending' | 'stale' | 'given'; at?: string };
266
+ /** `sungen journey --signoff` would be accepted now (assertCanSignOff holds). */
267
+ canSignOff: boolean;
268
+ }
269
+
270
+ /** The board's asks, read-only: no import, no dual-write, no state file — the same reconcile `runJourney` commits. */
271
+ export function readJourneyHumanAsks(projectRoot: string, unit: string): JourneyHumanAsks {
272
+ const r = reconcileJourney(projectRoot, unit);
273
+ const report = finishReport(r, unit);
274
+ let canSignOff = report.obligations.some((o) => o.id === SIGNOFF_OBLIGATION);
275
+ try { assertCanSignOff(report); } catch { canSignOff = false; }
276
+ return { report, redecide: r.redecide, signoff: r.signoff, canSignOff };
277
+ }
278
+
279
+ interface Reconciled {
280
+ report: JourneyReport;
281
+ slug: string;
282
+ statePath: string;
283
+ sync: ReturnType<typeof planWaiverSync>;
284
+ next: JourneyState;
285
+ decisionFindings: DecisionGateFinding[];
286
+ redecide: WaiverToRedecide[];
287
+ signoff: JourneyHumanAsks['signoff'];
288
+ }
289
+
290
+ /** Compute fresh, apply the waivers and the sign-off in force — read-only; `runJourney` commits the plan. */
291
+ function reconcileJourney(projectRoot: string, unit: string): Reconciled {
246
292
  const slug = reportSlug(unit);
247
293
  assertNoPendingMigration(projectRoot, slug);
248
294
  const report = computeFresh(projectRoot, unit);
@@ -250,9 +296,11 @@ export function runJourney(projectRoot: string, unit: string): JourneyReport {
250
296
  const state = loadState(sp) || { unit, auditHash: '', waivers: {} };
251
297
  const curHash = auditHashOf(projectRoot, slug);
252
298
  const sync = planWaiverSync(projectRoot, unit, slug, sp, state.waivers);
299
+ const redecide: WaiverToRedecide[] = [];
253
300
  for (const u of sync.untrusted) {
254
301
  const title = report.obligations.find((o) => o.id === u.obligation)?.title ?? u.obligation;
255
302
  const ignored = unwaivableWhy(u.obligation, unit);
303
+ if (!ignored) redecide.push({ obligation: u.obligation, title, reason: u.waiver.reason, why: 'untrusted' });
256
304
  report.needsYou.unshift({ text: ignored ? ignoredWaiverText(u.obligation, ignored, u.waiver.reason) : untrustedWaiverText(unit, slug, title, u), anchor: { vpId: u.obligation } });
257
305
  }
258
306
 
@@ -267,30 +315,33 @@ export function runJourney(projectRoot: string, unit: string): JourneyReport {
267
315
  ob.waivedReason = w.reason;
268
316
  ob.detail = `waived — ${w.reason}`;
269
317
  } else {
318
+ redecide.push({ obligation: ob.id, title: ob.title, reason: w.reason, why: 'stale' });
270
319
  report.needsYou.unshift({ text: `⚠️ Waiver on "${ob.title}" is STALE (evidence changed since ${w.at}) — re-decide. Was: ${w.reason}`, anchor: { vpId: ob.id } });
271
320
  }
272
321
  }
273
322
  // S5 — sign-off reconcile: a recorded sign-off satisfies OB-signoff while its evidence holds;
274
323
  // if the audit changed since, the sign-off is STALE → re-surface for re-review (anti-amnesia).
275
324
  const signoffOb = report.obligations.find((o) => o.id === 'OB-signoff');
325
+ let signoff: Reconciled['signoff'] = { status: 'pending' };
276
326
  if (signoffOb && state.signoff) {
277
327
  if (state.signoff.auditHashAtSignoff === curHash) {
328
+ signoff = { status: 'given', at: state.signoff.at };
278
329
  signoffOb.status = 'satisfied';
279
330
  signoffOb.detail = `signed off${state.signoff.by ? ' by ' + state.signoff.by : ''}${state.signoff.recordedBy ? ` (recorded by ${state.signoff.recordedBy})` : ''} at ${state.signoff.at}`;
280
331
  } else {
332
+ signoff = { status: 'stale', at: state.signoff.at };
281
333
  report.needsYou.unshift({ text: `⚠️ Sign-off is STALE (suite changed since ${state.signoff.at}) — re-review and sign off again.`, anchor: { vpId: 'OB-signoff' } });
282
334
  }
283
335
  }
284
336
  // Phase-03 carry-over: a decision that does not verify is a FINDING the gate blocks on, not a crash.
285
337
  const decisionFindings = journeyDecisionFindings(projectRoot, unitOverrides(projectRoot, unit));
286
338
  const next: JourneyState = { unit, auditHash: curHash, waivers: sync.stateWaivers, signoff: state.signoff };
287
- try {
288
- commitWaiverSync(projectRoot, unit, slug, sync, sp, JSON.stringify(next, null, 2));
289
- } catch (err) {
290
- if (!(err instanceof DecisionConflictError)) throw err;
291
- const rel = path.relative(projectRoot, err.path).split(path.sep).join('/');
292
- if (!decisionFindings.some((f) => f.path === rel)) decisionFindings.push({ rule: 'decision.mutated', path: rel, message: err.message });
293
- }
339
+ return { report, slug, statePath: sp, sync, next, decisionFindings, redecide, signoff };
340
+ }
341
+
342
+ /** The decision findings on the board, then the next suggestion — after the waivers and the sign-off. */
343
+ function finishReport(r: Reconciled, unit: string): JourneyReport {
344
+ const { report, decisionFindings } = r;
294
345
  if (decisionFindings.length) {
295
346
  report.decisionFindings = decisionFindings;
296
347
  for (const f of [...decisionFindings].reverse()) report.needsYou.unshift({ text: decisionFindingText(f), anchor: { file: f.path } });
@@ -408,11 +459,31 @@ export function writeJourneyFileBestEffort(file: string, text: string): string |
408
459
 
409
460
  const ICON: Record<ObStatus, string> = { satisfied: '✅', 'needs-work': '⚠️ ', pending: '⏳', waived: '🚫', overridden: '🔓' };
410
461
 
462
+ /** `ms` as a person reads a duration: `850 ms`, `45 s`, `8 min 40 s`. */
463
+ function elapsedLabel(ms: number): string {
464
+ if (ms < 1000) return `${ms} ms`;
465
+ const s = Math.round(ms / 1000);
466
+ return s < 60 ? `${s} s` : `${Math.floor(s / 60)} min${s % 60 ? ` ${s % 60} s` : ''}`;
467
+ }
468
+
469
+ /**
470
+ * A ledger step as the board shows it (#939 item 8). A step recorded with its elapsed milliseconds in the
471
+ * NAME (`--step "viewpoint 45000"`, the time meant for `--ms`) printed as a bare number; it reads
472
+ * `viewpoint (45 s)` now, and `timed` says the line needs its legend.
473
+ */
474
+ function phaseLabel(step: string): { label: string; timed: boolean } {
475
+ const m = step.match(/^(.*\S)\s+(\d+)$/);
476
+ return m ? { label: `${m[1]} (${elapsedLabel(Number(m[2]))})`, timed: true } : { label: step, timed: false };
477
+ }
478
+
411
479
  export function renderJourneyBoard(r: JourneyReport): string {
412
480
  const L: string[] = [];
413
481
  L.push(`# Journey — ${r.unit}`);
414
482
  L.push('');
415
- L.push(`📍 **You are here:** ${r.youAreHere}` + (r.phasesDone.length ? ` (phases: ${r.phasesDone.join(' → ')})` : ''));
483
+ const phases = r.phasesDone.map(phaseLabel);
484
+ const legend = phases.some((p) => p.timed) || phaseLabel(r.youAreHere).timed
485
+ ? ` — a time is that phase's elapsed time, from the ledger (\`sungen ledger report --screen ${r.unit}\`)` : '';
486
+ L.push(`📍 **You are here:** ${phaseLabel(r.youAreHere).label}` + (phases.length ? ` (phases: ${phases.map((p) => p.label).join(' → ')})${legend}` : ''));
416
487
  if (r.gateStatus) L.push(` gate: **${r.gateStatus}** · score: ${r.score ?? '—'}/10`);
417
488
  L.push('');
418
489
  L.push('## What must still be true');
@@ -19,7 +19,9 @@ import * as path from 'path';
19
19
  import { reportSlug } from './unit-paths';
20
20
  import { checkAssetsDrift } from '../orchestrator/assets-drift';
21
21
  import type { HeadSnapshot } from '../contract/contract-git';
22
- import { evaluateGraph, EvaluateOptions } from '../graph/evaluate-graph';
22
+ import { boardHumanActions } from '../graph/board-human-actions';
23
+ import { evaluateGraph, evaluateHumanActions, EvaluateOptions } from '../graph/evaluate-graph';
24
+ import type { HumanAction } from '../graph/human-action';
23
25
  import { CORE_NODES } from '../graph/nodes/core-node-catalog';
24
26
  import type { TestCaseState } from '../graph/test-case-state-shape';
25
27
  import { testCaseStates } from '../graph/test-case-states';
@@ -27,6 +29,7 @@ import {
27
29
  countFailedResults, countScenarios, hasDeliverableFor, hasResolvedSelector, isCompiled, readIfExists, unitResultFiles,
28
30
  } from '../graph/unit-artifact-probes';
29
31
  import { AuditNotCounted, ContractFacts, ContractSummary, readContractFacts, readTrustedAudit } from '../graph/unit-state-facts';
32
+ import { ResultsFreshness, resultsFreshness } from '../graph/unit-results-freshness';
30
33
 
31
34
  export interface NextStep {
32
35
  /** The command to run, as the operator would type it. */
@@ -89,7 +92,20 @@ export interface UnitState {
89
92
  contract?: ContractSummary;
90
93
  /** Per-test-case state (DOS-11.1); absent when not read from disk or unreadable. */
91
94
  testCases?: TestCaseState[];
95
+ /** Which run the results come from and what they are older than (#942); absent without results. Advisory, decides no step. */
96
+ results?: ResultsFreshness;
92
97
  steps: NextStep[];
98
+ /**
99
+ * Every pending HUMAN-ONLY action ("Waiting for you", #954): the frontier's decisions (deriveHumanActions)
100
+ * and the board's asks (sign-off, a waiver to give again, a decision recorded during the run). Set by
101
+ * readUnitState; commands canonical (`sungen …`). An agent presents them and never runs them.
102
+ */
103
+ humanActions?: HumanAction[];
104
+ /**
105
+ * The title of the blocking step that cut the frontier: past it only actions that do not depend on it
106
+ * are listed (sign-off, accept-in-run and the first contract approval wait). Absent when nothing cuts.
107
+ */
108
+ humanActionsHeldBy?: string;
93
109
  }
94
110
 
95
111
  export interface ReadUnitStateOptions {
@@ -162,7 +178,16 @@ export function readUnitState(
162
178
  state.testCases = testCaseStates(projectRoot, unit, { unitDir, auditFindings: state.audit?.findings ?? [] })
163
179
  .map((tc) => (contract?.cases.has(tc.id) ? { ...tc, contract: contract.cases.get(tc.id) } : tc));
164
180
  } catch { /* an unparseable .feature — the unit-level nodes still answer, as before test-case state */ }
181
+ try {
182
+ const results = resultsFreshness(projectRoot, unitDir, unit);
183
+ if (results) state.results = results;
184
+ } catch { /* advisory: results that cannot be dated add nothing */ }
165
185
  state.steps = deriveSteps(state);
186
+ const graph = evaluateHumanActions(CORE_NODES, state, state.testCases);
187
+ const seen = new Set<string>();
188
+ state.humanActions = [...graph.actions, ...boardHumanActions(projectRoot, unitDir, state, graph.cut)]
189
+ .filter((a) => !seen.has(a.command) && Boolean(seen.add(a.command)));
190
+ if (graph.heldBy) state.humanActionsHeldBy = graph.heldBy;
166
191
  return state;
167
192
  }
168
193
 
@@ -174,3 +199,8 @@ export function readUnitState(
174
199
  export function deriveSteps(s: UnitState, opts: EvaluateOptions = {}): NextStep[] {
175
200
  return evaluateGraph(CORE_NODES, s, s.testCases, opts);
176
201
  }
202
+
203
+ /** The human-only actions of the same frontier (#954) — the graph's part of `humanActions`, without the board. */
204
+ export function deriveHumanActions(s: UnitState): HumanAction[] {
205
+ return evaluateHumanActions(CORE_NODES, s, s.testCases).actions;
206
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * `sungen triage --screen <u> --case <id> --as product|test-defect|environment --reason "…"` (#928):
3
+ * classify one red by hand — the one `sungen triage` left unclassified, or one it got wrong — as a
4
+ * `triage-classification` decision in the unit's `decisions/` (read back by graph/manual-triage-decisions.ts).
5
+ *
6
+ * validated first the class, a reason, a case that exists, is red and is not exempt — before any
7
+ * prompt, so a human never confirms something that is then rejected
8
+ * product stricter than any automatic class (it leads to a QA decision): anyone may record it
9
+ * test-defect, can hide a product defect behind "fix the test" / "re-run": a human types a
10
+ * environment confirmation on a terminal (DOS-13.4); without one it is refused, nothing is
11
+ * written and the exact command is printed. Only after the typed phrase does the
12
+ * entry carry `humanConfirmed: true`, and a reader ignores one without it
13
+ * bound evidence_hash = the case's red as it reads now; a re-run voids the classification
14
+ */
15
+ import type { AppendResult } from '../decisions/append-decision';
16
+ import { appendDecision } from '../decisions/append-decision';
17
+ import type { DecisionDraft } from '../decisions/decision-schema';
18
+ import { gitUserName } from '../decisions/decision-source';
19
+ import { ConfirmationIO, formatCommand, requireTypedConfirmation } from '../decisions/human-confirmation';
20
+ import { resolveUnitCandidates } from '../cli/resolve-unit';
21
+ import { HUMAN_ONLY_TRIAGE, MANUAL_TRIAGE_AS, ManualTriageClass, TRIAGE_DECISION_KIND } from '../graph/manual-triage-decisions';
22
+ import { exemptionOf } from '../graph/test-case-satisfied';
23
+ import { testCaseStates } from '../graph/test-case-states';
24
+ import { unitScopeOfDir } from './gates/unit-gate-overrides';
25
+
26
+ export interface ClassifyRedCaseInput {
27
+ projectRoot: string;
28
+ unit: string;
29
+ caseId: string;
30
+ /** product | test-defect | environment */
31
+ as: string;
32
+ reason?: string;
33
+ io: ConfirmationIO;
34
+ }
35
+
36
+ export interface ClassifyRedCaseResult extends AppendResult { caseId: string; class: ManualTriageClass }
37
+
38
+ export async function classifyRedCase(i: ClassifyRedCaseInput): Promise<ClassifyRedCaseResult> {
39
+ const cls = Object.prototype.hasOwnProperty.call(MANUAL_TRIAGE_AS, i.as) ? MANUAL_TRIAGE_AS[i.as] : undefined;
40
+ if (!cls) throw new Error(`--as must be one of ${Object.keys(MANUAL_TRIAGE_AS).join(', ')} (got "${i.as}")`);
41
+ const reason = (i.reason ?? '').trim();
42
+ if (!reason) throw new Error('--reason is required: a classification records WHY this red is what you say it is');
43
+ const found = resolveUnitCandidates(i.unit, i.projectRoot);
44
+ if (found.length !== 1) throw new Error(`"${i.unit}" does not name exactly one unit under qa/screens, qa/flows or qa/api`);
45
+ const unitDir = found[0].dir;
46
+ const scope = unitScopeOfDir(i.projectRoot, unitDir);
47
+ if (!scope) throw new Error(`"${i.unit}" has no decisions scope`);
48
+ const cases = testCaseStates(i.projectRoot, i.unit, { unitDir, auditFindings: [] });
49
+ const tc = cases.find((c) => c.id === i.caseId);
50
+ if (!tc) {
51
+ const known = cases.slice(0, 8).map((c) => c.id).join(', ');
52
+ throw new Error(`no test case "${i.caseId}" in ${i.unit}${known ? ` — known: ${known}${cases.length > 8 ? ', …' : ''}` : ''}`);
53
+ }
54
+ if (tc.result !== 'failed' || !tc.evidence) throw new Error(`${tc.id} has no red result to classify (result: ${tc.result})`);
55
+ const exempt = exemptionOf(tc);
56
+ if (exempt) throw new Error(`${tc.id} is exempt (${exempt}) — it needs no classification`);
57
+
58
+ const human = HUMAN_ONLY_TRIAGE.has(cls);
59
+ if (human) {
60
+ await requireTypedConfirmation({
61
+ what: `classify the red ${tc.id} of ${i.unit} as ${cls}`,
62
+ phrase: tc.id,
63
+ command: formatCommand(['sungen', 'triage', found[0].kind === 'api' ? '--api' : '--screen', i.unit, '--case', tc.id, '--as', i.as, '--reason', reason]),
64
+ summary: [`case: ${tc.title}`, `automatic triage: ${tc.triage ? `${tc.triage.class} (${tc.triage.ruleId})` : 'none current'}`, `reason: ${reason}`,
65
+ `recorded by: ${gitUserName(i.projectRoot)}`, `as ${cls} it leaves the product-defect path — confirm only after reading its evidence (trace, error)`,
66
+ 'it stops counting as soon as the case runs again'],
67
+ io: i.io,
68
+ });
69
+ }
70
+ const draft: DecisionDraft = {
71
+ kind: TRIAGE_DECISION_KIND, anchors: [], text: `${tc.id} is ${cls}: ${tc.title}`, reason,
72
+ payload: { case: tc.id, class: cls, ...(human ? { humanConfirmed: true } : {}) },
73
+ source: { by: gitUserName(i.projectRoot), where: 'cli' }, valid_from: new Date().toISOString(), visibility: 'internal', evidence_hash: tc.evidence,
74
+ };
75
+ return { ...appendDecision(i.projectRoot, scope, draft), caseId: tc.id, class: cls };
76
+ }
@@ -49,3 +49,22 @@ export function featureFilesFor(unitDir: string, unit: string): string[] {
49
49
  ...names.filter((n) => n !== canonicalName),
50
50
  ].map((n) => path.join(dir, n));
51
51
  }
52
+
53
+ /**
54
+ * The catalog-resolution id for a unit dir (relative to qa/): screen · flows/<flow> · api/<area> ·
55
+ * api/flows/<flow>; a bare screen is its basename. Shared by the audit, which scores and links the
56
+ * unit under this id, and its inputsHash, which reads what the audit reads under the same id.
57
+ */
58
+ export function catalogIdFromScreenDir(screenDir: string): string {
59
+ const parts = screenDir.split(path.sep);
60
+ const qa = parts.lastIndexOf('qa');
61
+ if (qa >= 0) {
62
+ if (parts[qa + 1] === 'api' && parts[qa + 2] === 'flows' && parts[qa + 3]) return `api/flows/${parts[qa + 3]}`;
63
+ if (parts[qa + 1] === 'api' && parts[qa + 2]) return `api/${parts[qa + 2]}`;
64
+ if (parts[qa + 1] === 'flows' && parts[qa + 2]) return `flows/${parts[qa + 2]}`;
65
+ }
66
+ return path.basename(screenDir);
67
+ }
68
+
69
+ /** A screen unit — the only kind a sibling flow credits (TQ-4); flows and api units are not. */
70
+ export const isScreenUnitId = (catalogId: string): boolean => !/^(flows|api)\//.test(catalogId);
@@ -2,7 +2,9 @@
2
2
  * Guard rule `tty-spoof` (phase 06, M5): ASK before an agent runs a human-confirmed sungen command
3
3
  * through a terminal emulator.
4
4
  *
5
- * `contract approve`, `journey --waive`, `journey --decide` and `journey --signoff` refuse without a TTY (DOS-13.4), and
5
+ * `contract approve`, `journey --waive`, `journey --decide`, `journey --signoff`, `triage --as test-defect|environment`
6
+ * (#928: a red classified away from the product-defect path) and `delivery --accept-in-run` (delivering past
7
+ * decisions recorded during the run) refuse without a TTY (DOS-13.4), and
6
8
  * an agent's Bash has none — unless it borrows one: `script`, `expect`, `unbuffer`, or a pty from
7
9
  * Python/Perl/zsh. Then the prompt sees a "terminal" and a piped phrase reads as a human typing it.
8
10
  * This rule spots the pair in the raw command (quotes included, so `bash -c "…"` and `expect -c '…'`
@@ -13,7 +15,7 @@
13
15
  import type { GuardRule } from './guard-rules';
14
16
 
15
17
  const TTY_EMULATOR = /\b(?:script|unbuffer|expect|pty|zpty|openpty|forkpty|ptyprocess)\b/i;
16
- const HUMAN_GATED = /\bsungen\b[\s\S]*?\b(?:contract['",\s]+approve\b|journey\b[\s\S]*?--(?:waive|decide|signoff)\b)/i;
18
+ const HUMAN_GATED = /\bsungen\b[\s\S]*?\b(?:contract['",\s]+approve\b|journey\b[\s\S]*?--(?:waive|decide|signoff)\b|triage\b[\s\S]*?--as[\s='",]+(?:test-defect|environment)\b|delivery\b[\s\S]*?--accept-in-run\b)/i;
17
19
 
18
20
  export const ttySpoof: GuardRule = {
19
21
  id: 'tty-spoof',
@@ -23,7 +25,8 @@ export const ttySpoof: GuardRule = {
23
25
  if (!cmd || !TTY_EMULATOR.test(cmd) || !HUMAN_GATED.test(cmd)) return null;
24
26
  return {
25
27
  status: 'ask',
26
- askReason: 'sungen: this runs a human-confirmed sungen action (`contract approve` / `journey --waive|--decide|--signoff`) through a terminal '
28
+ askReason: 'sungen: this runs a human-confirmed sungen action (`contract approve` / `journey --waive|--decide|--signoff` / '
29
+ + '`triage --as test-defect|environment` / `delivery --accept-in-run`) through a terminal '
27
30
  + 'emulator (script / expect / unbuffer / pty). Those confirmations exist so a PERSON at a terminal decides — allow only if you '
28
31
  + 'are that person and asked for exactly this; otherwise run the command yourself in your own terminal.',
29
32
  };
@@ -11,6 +11,7 @@
11
11
  * ended in silence. The state now starts the moment parsing does; the action only refines it.
12
12
  */
13
13
  import { sungenInvocation, withProjectInvocation } from '../cli/project-sungen-invocation';
14
+ import { waitingForYouLines } from '../cli/waiting-for-you-block';
14
15
  import { resolveUnitCandidates } from '../cli/resolve-unit';
15
16
  import { readUnitState, NextStep, UnitState } from '../harness/next-step';
16
17
  import { NO_OP, HookContext, HookInput, HookResult } from './hook-result-contract';
@@ -101,12 +102,13 @@ export function locateUnitState(ctx: HookContext, preferred?: string): { root: s
101
102
  return unit ? { root, unit, state: readUnitState(root, unit.dir, unit.name, unit.kind) } : null;
102
103
  }
103
104
 
104
- /** Hook core: the next steps for the session's unit (input.unit, else the nearest) as context. */
105
+ /** Hook core: the next steps for the session's unit (input.unit, else the nearest) as context, then what waits for a human (#954). */
105
106
  export function run(input: HookInput, ctx: HookContext): HookResult {
106
107
  const found = locateUnitState(ctx, typeof input.unit === 'string' ? input.unit : undefined);
107
108
  if (!found || found.state.steps.length === 0) return NO_OP;
108
109
  return {
109
110
  status: 'context',
110
- output: [`${handBackLine(found.unit.name, sungenInvocation(found.root))} — derived from what the project holds now:`, ...formatSteps(found.state.steps, 4, found.root)].join('\n'),
111
+ output: [`${handBackLine(found.unit.name, sungenInvocation(found.root))} — derived from what the project holds now:`, ...formatSteps(found.state.steps, 4, found.root),
112
+ ...waitingForYouLines(found.state.humanActions, found.root, found.state.humanActionsHeldBy)].join('\n'),
111
113
  };
112
114
  }
@@ -5,11 +5,13 @@
5
5
  * After `/clear` or a context compaction the agent has lost the thread: it re-derives the state
6
6
  * from memory, or worse, re-runs work that is already done. This injects what `sungen next`
7
7
  * derives for the session's unit (the one cwd sits in, else the most recently active): what the
8
- * project already holds — stated as "do not redo" — the audit verdict, and the next steps.
8
+ * project already holds — stated as "do not redo" — the audit verdict, the next steps, and what waits
9
+ * for a human (#954).
9
10
  */
10
11
  import { NO_OP, HookMeta, SungenHook } from './hook-result-contract';
11
12
  import { formatSteps, locateUnitState } from './hand-back-core';
12
13
  import { sungenInvocation } from '../cli/project-sungen-invocation';
14
+ import { waitingForYouLines } from '../cli/waiting-for-you-block';
13
15
  import { listUnits } from './sungen-project-root';
14
16
  import type { UnitState } from '../harness/next-step';
15
17
 
@@ -48,6 +50,7 @@ export const sessionStartUnitStateHook: SungenHook = {
48
50
  state.audit ? `Audit: ${state.audit.overall}/10 [${state.audit.gateStatus}] · ${state.audit.findings.length} finding(s).` : '',
49
51
  `Next (\`${sungen} next ${unit.name}\`, derived from the project state):`,
50
52
  ...formatSteps(state.steps, 4, root),
53
+ ...waitingForYouLines(state.humanActions, root, state.humanActionsHeldBy),
51
54
  input.source === 'compact' ? 'Context was compacted: re-read the unit\'s files before acting on them.' : '',
52
55
  others > 0 ? `Working on another unit? Ask \`${sungen} next <unit>\` (or \`${sungen} next\` for all).` : '',
53
56
  ];
@@ -30,6 +30,7 @@ export const stopNextStepHook: SungenHook = {
30
30
  output: [
31
31
  '[sungen] This turn ran sungen work but ended without the next-step hand-back.',
32
32
  'Hand back now: present these steps to the user with AskUserQuestion and stop — do not run them yourself.',
33
+ ...(/Waiting for you/.test(core.output) ? ['Quote the "Waiting for you" block verbatim: the user runs those commands in their own terminal (`! <command>`); never run them.'] : []),
33
34
  core.output,
34
35
  ].join('\n'),
35
36
  };
@@ -237,3 +237,5 @@ sungen delivery [names...] # matrix (default; needs the map) → XLSX onl
237
237
  Outputs: `qa/deliverables/<unit>-testcases.xlsx` (Overview + Auto + Manual + Coverage sheets) by default;
238
238
  `--format csv` writes `<unit>-testcases.csv` instead (flat, `Level` column `item|variant`),
239
239
  `--format both` writes both. Legacy mode writes the classic files instead.
240
+
241
+ <!-- include: waiting-for-you -->
@@ -97,3 +97,5 @@ You are an **independent QA Reviewer** — you did not author these tests. You d
97
97
  5. **Trace + next** — `sungen trace --screen ${input:name}` (human-loop focus), then offer:
98
98
  - **`/sungen-run-test ${input:name}`** (Recommended) · **`/sungen-delivery ${input:name}`** · **`/sungen-create-test ${input:name}`** · Done.
99
99
  {{/cap}}
100
+
101
+ <!-- include: waiting-for-you -->
@@ -0,0 +1,11 @@
1
+ <!-- sungen:waiting-for-you v1 -->
2
+ ## Waiting for you — the commands only the QA runs
3
+
4
+ Right before the hand-back question, run `sungen next {{unitArg}}` and quote its **⏳ Waiting for you**
5
+ block **verbatim** — every command exactly as printed, each with its reason. Those commands approve,
6
+ sign off, waive, classify a red, accept in-run decisions or re-run once the environment is up: they are
7
+ the QA's alone, and most refuse without a person typing a confirmation. Tell the QA to run each one in
8
+ their own terminal — in Claude Code, type `! <command>` in the prompt (a `/sungen:…` command is typed
9
+ as is). **Never run them yourself**, and never pipe or type a confirmation into them. When `sungen next`
10
+ prints no such block, say that nothing is waiting for the QA.
11
+ <!-- /sungen:waiting-for-you -->
@@ -0,0 +1,11 @@
1
+ <!-- sungen:waiting-for-you v1 -->
2
+ ## Waiting for you — the commands only the QA runs
3
+
4
+ Right before the hand-back list, run `sungen next {{unitArg}}` and quote its **⏳ Waiting for you**
5
+ block **verbatim** — every command exactly as printed, each with its reason. Those commands approve,
6
+ sign off, waive, classify a red, accept in-run decisions or re-run once the environment is up: they are
7
+ the QA's alone, and most refuse without a person typing a confirmation. Tell the QA to run each one
8
+ themselves, in their own terminal (a slash command is typed as is). **Never run them yourself**, and
9
+ never pipe or type a confirmation into them. When `sungen next` prints no such block, say that nothing
10
+ is waiting for the QA.
11
+ <!-- /sungen:waiting-for-you -->
@@ -0,0 +1,11 @@
1
+ <!-- sungen:waiting-for-you v1 -->
2
+ ## Waiting for you — the commands only the QA runs
3
+
4
+ Right before the hand-back list, run `sungen next {{unitArg}}` and quote its **⏳ Waiting for you**
5
+ block **verbatim** — every command exactly as printed, each with its reason. Those commands approve,
6
+ sign off, waive, classify a red, accept in-run decisions or re-run once the environment is up: they are
7
+ the QA's alone, and most refuse without a person typing a confirmation. Tell the QA to run each one
8
+ themselves, in their own terminal (a slash command is typed as is). **Never run them yourself**, and
9
+ never pipe or type a confirmation into them. When `sungen next` prints no such block, say that nothing
10
+ is waiting for the QA.
11
+ <!-- /sungen:waiting-for-you -->