@aipper/aiws 0.0.19 → 0.0.21

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.
@@ -320,6 +320,412 @@ function splitDeclaredValues(s) {
320
320
  .filter(Boolean);
321
321
  }
322
322
 
323
+ /**
324
+ * @param {string} p
325
+ */
326
+ function normalizeSlashes(p) {
327
+ return String(p || "").replaceAll("\\", "/");
328
+ }
329
+
330
+ /**
331
+ * Extract bullet lines under a markdown "## ..." heading.
332
+ *
333
+ * @param {string} text
334
+ * @param {RegExp} headingRe
335
+ * @param {{ max?: number }} [options]
336
+ * @returns {string[]} trimmed bullet lines like "- foo"
337
+ */
338
+ function extractBulletsUnderHeading(text, headingRe, options) {
339
+ const max = typeof options?.max === "number" ? options.max : 5;
340
+ const lines = String(text || "").split("\n");
341
+ let inSection = false;
342
+ /** @type {string[]} */
343
+ const out = [];
344
+ for (const raw of lines) {
345
+ const line = String(raw || "");
346
+ const trimmed = line.trim();
347
+ if (!inSection) {
348
+ if (headingRe.test(trimmed)) inSection = true;
349
+ continue;
350
+ }
351
+ if (/^##\s+/.test(trimmed)) break;
352
+ if (trimmed.startsWith("-")) {
353
+ out.push(trimmed);
354
+ if (out.length >= max) break;
355
+ }
356
+ }
357
+ return out;
358
+ }
359
+
360
+ /**
361
+ * @param {string} bulletLine
362
+ */
363
+ function isMeaningfulBullet(bulletLine) {
364
+ const s = String(bulletLine || "").trim();
365
+ if (!s.startsWith("-")) return false;
366
+ if (s.includes("WS:TODO")) return false;
367
+ if (s.includes("<!--")) return false;
368
+ if (s === "-" || s === "- (none)" || s === "- (missing)") return false;
369
+ return true;
370
+ }
371
+
372
+ /**
373
+ * Find an archived change by ID in the archive directory.
374
+ * @param {string} archiveDir
375
+ * @param {string} changeId
376
+ * @returns {Promise<string | null>} Full path to archived change dir, or null if not found.
377
+ */
378
+ async function findArchivedChange(archiveDir, changeId) {
379
+ if (!(await pathExists(archiveDir))) return null;
380
+ try {
381
+ const entries = await fs.readdir(archiveDir, { withFileTypes: true });
382
+ for (const e of entries) {
383
+ if (!e.isDirectory()) continue;
384
+ // Archive dirs are named like: 2026-03-12-<change-id> or 2026-03-12-<change-id>-<timestamp>
385
+ if (e.name.endsWith(`-${changeId}`) || e.name.includes(`-${changeId}-`)) {
386
+ return path.join(archiveDir, e.name);
387
+ }
388
+ }
389
+ } catch {
390
+ // ignore
391
+ }
392
+ return null;
393
+ }
394
+
395
+ /**
396
+ * Extract a brief summary from handoff.md content.
397
+ * @param {string} text
398
+ * @returns {string}
399
+ */
400
+ function extractHandoffSummary(text) {
401
+ // Try to extract "本次完成" or "What Changed" section
402
+ const lines = String(text || "").split("\n");
403
+ let inSection = false;
404
+ const summary = [];
405
+ for (const line of lines) {
406
+ if (/^##\s*(本次完成|What Changed|Completed)/i.test(line)) {
407
+ inSection = true;
408
+ continue;
409
+ }
410
+ if (inSection && /^##/.test(line)) break;
411
+ if (inSection && line.trim().startsWith("-")) {
412
+ summary.push(line.trim());
413
+ if (summary.length >= 3) break;
414
+ }
415
+ }
416
+ return summary.join(" ");
417
+ }
418
+
419
+ /**
420
+ * Check Depends_On dependencies and print handoff summaries.
421
+ * @param {string} gitRoot - The git root directory (main or worktree)
422
+ * @param {string} changeId
423
+ * @param {string} changeDir - The change directory (may be in worktree)
424
+ */
425
+ async function checkDependenciesAndPrintHandoff(gitRoot, changeId, changeDir) {
426
+ const proposalPath = path.join(changeDir, "proposal.md");
427
+ if (!(await pathExists(proposalPath))) return;
428
+
429
+ const proposalText = await readText(proposalPath);
430
+ const dependsOn = extractId("Depends_On", proposalText);
431
+ if (!dependsOn) return;
432
+
433
+ const deps = splitDeclaredValues(dependsOn).filter((d) => d && d !== changeId);
434
+ if (deps.length === 0) return;
435
+ const archiveDir = path.join(gitRoot, "changes", "archive");
436
+
437
+ for (const dep of deps) {
438
+ const depDir = changeDirAbs(gitRoot, dep);
439
+ const depArchived = await findArchivedChange(archiveDir, dep);
440
+ if (!depArchived && !(await pathExists(depDir))) {
441
+ console.error(`warn: Depends_On "${dep}" not found (neither active nor archived)`);
442
+ console.error(`hint: if you are using --worktree, ensure the dependency is archived under changes/archive/ and committed to HEAD in this worktree.`);
443
+ } else if (!depArchived) {
444
+ console.error(`warn: Depends_On "${dep}" is not yet archived (still active at changes/${dep})`);
445
+ } else {
446
+ // Dependency is archived, check for handoff.md
447
+ const handoffPath = path.join(depArchived, "handoff.md");
448
+ if (await pathExists(handoffPath)) {
449
+ console.log(`info: reading handoff from dependency "${dep}"`);
450
+ const handoffText = await readText(handoffPath);
451
+ const summary = extractHandoffSummary(handoffText);
452
+ if (summary) {
453
+ console.log(` ${summary}`);
454
+ }
455
+ } else {
456
+ console.error(`warn: dependency "${dep}" is archived but missing handoff.md: ${path.relative(gitRoot, handoffPath)}`);
457
+ }
458
+ }
459
+ }
460
+ }
461
+
462
+ /**
463
+ * Generate handoff.md content for a completed change.
464
+ * @param {string} gitRoot
465
+ * @param {string} changeDir - The archived change directory
466
+ * @param {string} changeId
467
+ * @returns {Promise<string>}
468
+ */
469
+ async function generateHandoffContent(gitRoot, changeDir, changeId) {
470
+ const proposalPath = path.join(changeDir, "proposal.md");
471
+ const designPath = path.join(changeDir, "design.md");
472
+
473
+ let reqId = "";
474
+ let problemId = "";
475
+ let blocks = "";
476
+ let goal = "";
477
+ let baseBranch = "main";
478
+ /** @type {string[]} */
479
+ const decisions = [];
480
+
481
+ if (await pathExists(proposalPath)) {
482
+ const text = await readText(proposalPath);
483
+ reqId = extractId("Req_ID", text);
484
+ problemId = extractId("Problem_ID", text);
485
+ blocks = extractId("Blocks", text);
486
+ const declaredBase = extractId("Base_Branch", text);
487
+ if (declaredBase) baseBranch = declaredBase;
488
+ // Extract goal from 目标 section
489
+ const goalMatch = text.match(/\*\*目标[::]\*\*\s*\n([\s\S]*?)(?=\n\*\*非目标|$)/);
490
+ if (goalMatch) {
491
+ const goalLines = goalMatch[1].split("\n").filter((l) => l.trim().startsWith("-")).slice(0, 3);
492
+ goal = goalLines.map((l) => l.trim()).join("\n");
493
+ }
494
+ }
495
+
496
+ // Get changed files from git diff if possible
497
+ let changedFiles = [];
498
+ try {
499
+ const metaPath = path.join(changeDir, ".ws-change.json");
500
+ if (await pathExists(metaPath)) {
501
+ const meta = JSON.parse(await readText(metaPath));
502
+ if (meta && typeof meta === "object" && meta.base_branch) baseBranch = String(meta.base_branch || "").trim() || baseBranch;
503
+ }
504
+
505
+ const changeBranch = `change/${changeId}`;
506
+ const hasChangeBranch = await runCommand("git", ["show-ref", "--verify", "--quiet", `refs/heads/${changeBranch}`], { cwd: gitRoot }).then((r) => r.code === 0);
507
+ const cur = await currentBranch(gitRoot);
508
+ const diffTarget = hasChangeBranch ? changeBranch : cur === changeBranch ? "HEAD" : "";
509
+ if (diffTarget) {
510
+ const diff = await runCommand("git", ["diff", "--name-only", `${baseBranch}...${diffTarget}`], { cwd: gitRoot });
511
+ if (diff.code === 0 && diff.stdout) {
512
+ changedFiles = diff.stdout.split("\n").filter(Boolean).slice(0, 20);
513
+ }
514
+ }
515
+ } catch {
516
+ // ignore
517
+ }
518
+
519
+ try {
520
+ if (await pathExists(designPath)) {
521
+ const designText = await readText(designPath);
522
+ decisions.push(...extractBulletsUnderHeading(designText, /^##\s*Decisions\s*$/i, { max: 12 }).filter(isMeaningfulBullet).slice(0, 8));
523
+ decisions.push(...extractBulletsUnderHeading(designText, /^##\s*关键决策\s*$/i, { max: 12 }).filter(isMeaningfulBullet).slice(0, 8));
524
+ } else if (await pathExists(proposalPath)) {
525
+ const proposalText = await readText(proposalPath);
526
+ const fromProposal = extractBulletsUnderHeading(proposalText, /^##\s*方案概述\b.*$/i, { max: 10 }).filter(isMeaningfulBullet).slice(0, 6);
527
+ for (const b of fromProposal) decisions.push(`- (from proposal) ${b.replace(/^-+\s*/, "")}`);
528
+ }
529
+ } catch {
530
+ // ignore
531
+ }
532
+
533
+ const lines = [
534
+ `# Handoff: ${changeId}`,
535
+ "",
536
+ `> Archived: ${nowIsoUtc()}`,
537
+ "",
538
+ "## 本次完成",
539
+ "",
540
+ ];
541
+
542
+ if (goal) {
543
+ lines.push(goal);
544
+ } else {
545
+ lines.push("- (see proposal.md for details)");
546
+ }
547
+
548
+ lines.push("");
549
+ lines.push("## 改动文件");
550
+ lines.push("");
551
+ if (changedFiles.length > 0) {
552
+ for (const f of changedFiles) {
553
+ lines.push(`- ${f}`);
554
+ }
555
+ if (changedFiles.length === 20) {
556
+ lines.push("- ...(truncated)");
557
+ }
558
+ } else {
559
+ lines.push("- (see git log for details)");
560
+ }
561
+
562
+ lines.push("");
563
+ lines.push("## 关键决策");
564
+ lines.push("");
565
+ if (decisions.length > 0) {
566
+ for (const d of decisions) lines.push(d);
567
+ } else {
568
+ lines.push("- (missing) add decisions to changes/<id>/design.md#Decisions");
569
+ }
570
+
571
+ lines.push("");
572
+ lines.push("## 下一步建议");
573
+ lines.push("");
574
+ if (blocks) {
575
+ const blockIds = splitDeclaredValues(blocks);
576
+ for (const b of blockIds) {
577
+ lines.push(`- 可以开始: ${b}`);
578
+ }
579
+ } else {
580
+ lines.push("- (no Blocks declared)");
581
+ }
582
+
583
+ lines.push("");
584
+ lines.push("## 绑定");
585
+ lines.push("");
586
+ lines.push(`- Change_ID: ${changeId}`);
587
+ if (reqId) lines.push(`- Req_ID: ${reqId}`);
588
+ if (problemId) lines.push(`- Problem_ID: ${problemId}`);
589
+
590
+ return lines.join("\n") + "\n";
591
+ }
592
+
593
+ /**
594
+ * Evidence_Path is user-declared; we treat it as best-effort hints, not hard gates.
595
+ *
596
+ * @param {string} gitRoot
597
+ * @param {string} changeId
598
+ * @param {string[]} evidencePaths
599
+ * @returns {Promise<{
600
+ * entries: Array<{rel: string, abs: string, exists: boolean, kind: string, isAbsolute: boolean}>,
601
+ * counts: { total: number, exists: number, missing: number, tmp: number, persistent: number, other: number, absolute: number },
602
+ * missing: string[]
603
+ * }>}
604
+ */
605
+ async function analyzeEvidencePaths(gitRoot, changeId, evidencePaths) {
606
+ const changePrefix = `changes/${changeId}/`;
607
+ const evidencePrefix = `changes/${changeId}/evidence/`;
608
+ const reviewPrefix = `changes/${changeId}/review/`;
609
+
610
+ const entries = await Promise.all(
611
+ (evidencePaths || []).map(async (raw) => {
612
+ const rel = String(raw || "").trim();
613
+ const isAbsolute = path.isAbsolute(rel);
614
+ const abs = isAbsolute ? rel : path.join(gitRoot, rel);
615
+ const exists = rel ? await pathExists(abs) : false;
616
+
617
+ const relNorm = normalizeSlashes(rel);
618
+ let kind = "other";
619
+ if (relNorm.startsWith(".agentdocs/tmp/") || relNorm.startsWith(".agentdocs/")) kind = "tmp";
620
+ else if (relNorm.startsWith(evidencePrefix) || relNorm.startsWith(reviewPrefix) || relNorm.startsWith(changePrefix)) kind = "persistent";
621
+
622
+ return { rel, abs: path.resolve(abs), exists, kind, isAbsolute };
623
+ }),
624
+ );
625
+
626
+ const missing = entries.filter((e) => e.rel && !e.exists).map((e) => e.rel);
627
+ const counts = {
628
+ total: entries.filter((e) => e.rel).length,
629
+ exists: entries.filter((e) => e.rel && e.exists).length,
630
+ missing: missing.length,
631
+ tmp: entries.filter((e) => e.rel && e.kind === "tmp").length,
632
+ persistent: entries.filter((e) => e.rel && e.kind === "persistent").length,
633
+ other: entries.filter((e) => e.rel && e.kind === "other").length,
634
+ absolute: entries.filter((e) => e.rel && e.isAbsolute).length,
635
+ };
636
+
637
+ return { entries: entries.filter((e) => e.rel), counts, missing };
638
+ }
639
+
640
+ /**
641
+ * @param {string[]} a
642
+ * @param {string[]} b
643
+ */
644
+ function mergeDeclaredValues(a, b) {
645
+ const seen = new Set();
646
+ /** @type {string[]} */
647
+ const out = [];
648
+ for (const raw of [...(a || []), ...(b || [])]) {
649
+ const v = String(raw || "").trim().replace(/^`+/, "").replace(/`+$/, "").trim();
650
+ if (!v) continue;
651
+ if (seen.has(v)) continue;
652
+ seen.add(v);
653
+ out.push(v);
654
+ }
655
+ return out;
656
+ }
657
+
658
+ /**
659
+ * @param {string[]} values
660
+ */
661
+ function formatDeclaredValues(values) {
662
+ return (values || []).join(", ");
663
+ }
664
+
665
+ /**
666
+ * Replace or insert a simple "ID: value" style line in Markdown.
667
+ *
668
+ * @param {string} text
669
+ * @param {string[]} labelCandidates
670
+ * @param {string} value
671
+ * @param {{ insertAfterLabels?: string[] }} options
672
+ */
673
+ function upsertIdLine(text, labelCandidates, value, options) {
674
+ const src = String(text || "");
675
+ const labels = Array.isArray(labelCandidates) ? labelCandidates : [];
676
+ for (const label of labels) {
677
+ const re = new RegExp(`^(.*${escapeRegExp(label)}.*?[:=][ \\t]*)(.*)$`, "m");
678
+ const m = re.exec(src);
679
+ if (!m) continue;
680
+ const prefix = m[1] || "";
681
+ const replaced = src.replace(re, `${prefix}${value}`);
682
+ return { ok: true, changed: replaced !== src, text: replaced, mode: "replaced", label };
683
+ }
684
+
685
+ // Insert near the top (best-effort), after a nearby label if present.
686
+ const insertAfter = Array.isArray(options?.insertAfterLabels) ? options.insertAfterLabels : [];
687
+ const lines = src.split(/\r?\n/);
688
+ let idx = 0;
689
+ for (let i = 0; i < Math.min(lines.length, 80); i++) {
690
+ const line = lines[i] || "";
691
+ if (insertAfter.some((l) => line.includes(l))) idx = i + 1;
692
+ }
693
+ const insertedLabel = labels[0] || "Evidence_Path";
694
+ const newLine = `- ${insertedLabel}: ${value}`;
695
+ lines.splice(idx, 0, newLine);
696
+ const inserted = lines.join("\n");
697
+ return { ok: true, changed: inserted !== src, text: inserted, mode: "inserted", label: labels[0] || "" };
698
+ }
699
+
700
+ /**
701
+ * Special-case insertion for proposal.md template style.
702
+ *
703
+ * @param {string} proposalText
704
+ * @param {string} value
705
+ */
706
+ function upsertProposalEvidencePath(proposalText, value) {
707
+ const src = String(proposalText || "");
708
+ const re = new RegExp(`^(.*${escapeRegExp("Evidence_Path")}.*?[:=][ \\t]*)(.*)$`, "m");
709
+ if (re.test(src)) {
710
+ const m = re.exec(src);
711
+ const prefix = m?.[1] || "";
712
+ const out = src.replace(re, `${prefix}${value}`);
713
+ return { changed: out !== src, text: out, mode: "replaced" };
714
+ }
715
+ // Insert right after Plan_File binding if possible.
716
+ const lines = src.split(/\r?\n/);
717
+ let idx = 0;
718
+ for (let i = 0; i < Math.min(lines.length, 120); i++) {
719
+ if ((lines[i] || "").includes("Plan_File")) {
720
+ idx = i + 1;
721
+ break;
722
+ }
723
+ }
724
+ lines.splice(idx, 0, `- \`Evidence_Path\` = ${value}`);
725
+ const inserted = lines.join("\n");
726
+ return { changed: inserted !== src, text: inserted, mode: "inserted" };
727
+ }
728
+
323
729
  /**
324
730
  * @param {string} changeId
325
731
  */
@@ -327,6 +733,16 @@ function planVerifyHint(changeId) {
327
733
  return `执行前质量门(优先):\`aiws change validate ${changeId} --strict\`(AI 工具中等价于 \`$ws-plan-verify\`)`;
328
734
  }
329
735
 
736
+ /**
737
+ * @param {string[]} blockersStrict
738
+ * @param {{ unchecked: number }} tasks
739
+ */
740
+ function inferChangePhase(blockersStrict, tasks) {
741
+ if ((blockersStrict || []).length > 0) return "planning";
742
+ if ((tasks?.unchecked || 0) > 0) return "dev";
743
+ return "deliver";
744
+ }
745
+
330
746
  /**
331
747
  * Compute change status as JSON-friendly object (used by dashboard and CLI).
332
748
  *
@@ -364,6 +780,7 @@ export async function computeChangeStatus(gitRoot, changeId) {
364
780
  const planFile = proposal.state === "ok" ? extractId("Plan_File", proposal.text) || extractId("Plan file", proposal.text) : "";
365
781
  const evidencePath = proposal.state === "ok" ? extractId("Evidence_Path", proposal.text) || extractId("Evidence_Path(s)", proposal.text) : "";
366
782
  const evidencePaths = splitDeclaredValues(evidencePath);
783
+ const evidence = await analyzeEvidencePaths(gitRoot, changeId, evidencePaths);
367
784
  const taskProgress = tasks.state === "ok" ? checkboxStats(tasks.text) : { total: 0, done: 0, unchecked: 0, hasCheckboxes: false };
368
785
 
369
786
  const curTruth = await snapshotTruthShaOnly(gitRoot);
@@ -399,16 +816,35 @@ export async function computeChangeStatus(gitRoot, changeId) {
399
816
  blockersStrict.push("proposal.md missing attribution (Req_ID or Problem_ID)");
400
817
  }
401
818
 
819
+ if (proposal.state === "ok" && !contractRow) blockersStrict.push("proposal.md missing Contract_Row binding");
820
+
821
+ if (proposal.state === "ok") {
822
+ const planFiles = splitDeclaredValues(planFile);
823
+ if (planFiles.length !== 1) blockersStrict.push("proposal.md Plan_File must contain exactly one plan path");
824
+ else {
825
+ const planRel = String(planFiles[0] || "").replace(/^\.\//, "");
826
+ if (path.isAbsolute(planRel)) blockersStrict.push("proposal.md Plan_File must be workspace-relative (not absolute)");
827
+ else {
828
+ if (!planRel.startsWith("plan/")) blockersStrict.push("proposal.md Plan_File should be under plan/ (recommended)");
829
+ if (!(await pathExists(path.join(gitRoot, planRel)))) blockersStrict.push(`proposal.md Plan_File missing: ${planRel}`);
830
+ }
831
+ }
832
+ }
833
+
834
+ if (proposal.state === "ok" && evidencePaths.length === 0) blockersStrict.push("proposal.md missing Evidence_Path binding");
835
+
402
836
  if (!taskProgress.hasCheckboxes) blockersStrict.push("tasks.md has no checkbox tasks ('- [ ]' or '- [x]')");
403
837
  if (driftFiles.length > 0) blockersStrict.push(`truth drift vs ${baselineLabel} baseline (run \`aiws change sync ${changeId}\`)`);
404
838
 
405
839
  blockersArchive.push(...blockersStrict);
406
840
  if (taskProgress.unchecked > 0) blockersArchive.push(`tasks.md still has unchecked tasks (${taskProgress.unchecked} items)`);
841
+ const phase = inferChangePhase(blockersStrict, taskProgress);
407
842
 
408
843
  return {
409
844
  ok: true,
410
845
  changeId,
411
846
  dir: path.relative(gitRoot, changeDir),
847
+ phase,
412
848
  metaState,
413
849
  reqId,
414
850
  probId,
@@ -417,6 +853,7 @@ export async function computeChangeStatus(gitRoot, changeId) {
417
853
  planFile,
418
854
  evidencePaths,
419
855
  },
856
+ evidence,
420
857
  tasks: taskProgress,
421
858
  baselineLabel,
422
859
  baselineAt,
@@ -483,7 +920,7 @@ function groupCheckMessages(errors, warnings) {
483
920
  *
484
921
  * @param {string} gitRoot
485
922
  * @param {string} changeId
486
- * @param {{ strict: boolean, allowTruthDrift: boolean }} options
923
+ * @param {{ strict: boolean, allowTruthDrift: boolean, checkEvidence?: boolean, checkScope?: boolean }} options
487
924
  */
488
925
  export async function validateChangeArtifacts(gitRoot, changeId, options) {
489
926
  assertValidChangeId(changeId);
@@ -493,6 +930,8 @@ export async function validateChangeArtifacts(gitRoot, changeId, options) {
493
930
  const args = [...checker.args, "--workspace-root", gitRoot, "--change-id", changeId];
494
931
  if (options.strict) args.push("--strict");
495
932
  if (options.allowTruthDrift) args.push("--allow-truth-drift");
933
+ if (options.checkEvidence) args.push("--check-evidence");
934
+ if (options.checkScope) args.push("--check-scope");
496
935
 
497
936
  const res = await runPython(gitRoot, ["-u", ...args]);
498
937
  const parsed = parseChangeCheckerOutput(res.stdout, res.stderr);
@@ -546,6 +985,69 @@ async function fileState(changeDir, rel) {
546
985
  return { state: "ok", wsTodo: countWsTodo(text), placeholders: countPlaceholders(text), abs, text };
547
986
  }
548
987
 
988
+ /**
989
+ * Append a change lifecycle event into changes/<id>/metrics.json.
990
+ *
991
+ * @param {string} gitRoot
992
+ * @param {string} changeId
993
+ * @param {string} type
994
+ * @param {any} payload
995
+ */
996
+ async function appendMetricsEvent(gitRoot, changeId, type, payload) {
997
+ const changeDir = changeDirAbs(gitRoot, changeId);
998
+ const metricsAbs = path.join(changeDir, "metrics.json");
999
+ /** @type {{ version: number, change_id: string, events: any[], updated_at?: string } | null} */
1000
+ let cur = null;
1001
+ if (await pathExists(metricsAbs)) {
1002
+ try {
1003
+ cur = JSON.parse(await readText(metricsAbs));
1004
+ } catch {
1005
+ cur = null;
1006
+ }
1007
+ }
1008
+ if (!cur || typeof cur !== "object") {
1009
+ cur = { version: 1, change_id: changeId, events: [] };
1010
+ }
1011
+ if (!Array.isArray(cur.events)) cur.events = [];
1012
+ cur.events.push({ type, timestamp: nowIsoUtc(), payload: payload ?? null });
1013
+ cur.events = cur.events.slice(-200);
1014
+ cur.updated_at = nowIsoUtc();
1015
+ await writeText(metricsAbs, JSON.stringify(cur, null, 2) + "\n");
1016
+ }
1017
+
1018
+ /**
1019
+ * @param {string} absDir
1020
+ * @param {(name: string) => boolean} predicate
1021
+ */
1022
+ async function findLatestFileByMtime(absDir, predicate) {
1023
+ if (!(await pathExists(absDir))) return "";
1024
+ const entries = await fs.readdir(absDir, { withFileTypes: true });
1025
+ /** @type {{ abs: string, mtimeMs: number } | null} */
1026
+ let best = null;
1027
+ for (const e of entries) {
1028
+ if (!e.isFile()) continue;
1029
+ if (!predicate(e.name)) continue;
1030
+ const abs = path.join(absDir, e.name);
1031
+ let st;
1032
+ try {
1033
+ st = await fs.stat(abs);
1034
+ } catch {
1035
+ continue;
1036
+ }
1037
+ const mtimeMs = Number(st.mtimeMs || 0);
1038
+ if (!best || mtimeMs > best.mtimeMs) best = { abs, mtimeMs };
1039
+ }
1040
+ return best ? best.abs : "";
1041
+ }
1042
+
1043
+ /**
1044
+ * @param {string} gitRoot
1045
+ * @param {string} absPath
1046
+ */
1047
+ function relFromRoot(gitRoot, absPath) {
1048
+ return normalizeSlashes(path.relative(gitRoot, absPath));
1049
+ }
1050
+
549
1051
  /**
550
1052
  * @param {string} gitRoot
551
1053
  */
@@ -884,6 +1386,13 @@ async function changeNewAtGitRoot(gitRoot, options) {
884
1386
  meta.base_branch_set_at = createdAt;
885
1387
  }
886
1388
  await writeText(path.join(changeDir, ".ws-change.json"), JSON.stringify(meta, null, 2) + "\n");
1389
+ await appendMetricsEvent(gitRoot, changeId, "change_new", {
1390
+ title,
1391
+ created_at: createdAt,
1392
+ base_branch: baseBranch || "",
1393
+ templates: templates.resolvedFrom,
1394
+ no_design: options.noDesign === true,
1395
+ });
887
1396
 
888
1397
  console.log(`✓ aiws change new: ${changeId}`);
889
1398
  console.log(`dir: ${path.relative(gitRoot, changeDir)}`);
@@ -1048,6 +1557,18 @@ export async function changeStartCommand(options) {
1048
1557
  await hooksInstallCommand({ targetPath: gitRoot });
1049
1558
  }
1050
1559
 
1560
+ await appendMetricsEvent(destKey, changeId, "change_start", {
1561
+ mode: "worktree",
1562
+ worktree: destKey,
1563
+ branch,
1564
+ from_branch: startFromBranch || "",
1565
+ submodules: options.submodules === true,
1566
+ hooks: options.enableHooks === true,
1567
+ });
1568
+
1569
+ // Check Depends_On dependencies (worktree mode)
1570
+ await checkDependenciesAndPrintHandoff(destKey, changeId, changeDir);
1571
+
1051
1572
  console.log(`ok: change worktree ready: ${changeId}`);
1052
1573
  console.log(`worktree: ${destKey}`);
1053
1574
  console.log(`branch: ${branch}`);
@@ -1123,12 +1644,23 @@ export async function changeStartCommand(options) {
1123
1644
  await maybeRecordBaseBranch(changeDir, startFromBranch, branch);
1124
1645
  }
1125
1646
 
1647
+ // Check Depends_On dependencies (non-worktree mode)
1648
+ await checkDependenciesAndPrintHandoff(gitRoot, changeId, changeDir);
1649
+
1126
1650
  if (options.enableHooks) {
1127
1651
  await hooksInstallCommand({ targetPath: gitRoot });
1128
1652
  }
1129
1653
 
1130
1654
  const cur = await currentBranch(gitRoot);
1131
1655
  const curLabel = cur || "(detached)";
1656
+ await appendMetricsEvent(gitRoot, changeId, "change_start", {
1657
+ mode: effectiveNoSwitch ? "no-switch" : "switch",
1658
+ worktree: gitRoot,
1659
+ branch,
1660
+ from_branch: startFromBranch || "",
1661
+ current_branch: curLabel,
1662
+ hooks: options.enableHooks === true,
1663
+ });
1132
1664
  if (effectiveNoSwitch && cur !== branch) {
1133
1665
  console.log(`ok: prepared change: ${changeId} (branch: ${branch}${branchReady ? "" : " (pending)"}; current: ${curLabel})`);
1134
1666
  console.log("next:");
@@ -1269,6 +1801,8 @@ export async function changeFinishCommand(options) {
1269
1801
  throw new UserError("Failed to fast-forward merge change branch into target.", { details: `${merge.stderr || merge.stdout}${extra}` });
1270
1802
  }
1271
1803
 
1804
+ await appendMetricsEvent(gitRoot, changeId, "finish", { into, from: changeBranch });
1805
+
1272
1806
  console.log(`ok: finished change: ${changeId}`);
1273
1807
  console.log(`into: ${into}`);
1274
1808
  console.log(`from: ${changeBranch}`);
@@ -1289,15 +1823,34 @@ export async function changeStatusCommand(options) {
1289
1823
 
1290
1824
  const changeId = await resolveChangeId(gitRoot, options.changeId, { command: "status" });
1291
1825
  const st = await computeChangeStatus(gitRoot, changeId);
1826
+ const branch = await currentBranch(gitRoot);
1827
+ /** @type {{ changeWorktree?: string, targetWorktree?: string }} */
1828
+ const wtHint = {};
1829
+ try {
1830
+ const worktrees = await listGitWorktrees(gitRoot);
1831
+ const changeRef = `refs/heads/change/${changeId}`;
1832
+ const changeWt = worktrees.find((w) => String(w.branch || "") === changeRef);
1833
+ if (changeWt?.worktree && path.resolve(changeWt.worktree) !== path.resolve(gitRoot)) wtHint.changeWorktree = changeWt.worktree;
1834
+ } catch {
1835
+ // best-effort; ignore
1836
+ }
1292
1837
 
1293
1838
  console.log(`✓ aiws change status: ${st.changeId}`);
1294
1839
  console.log(`dir: ${st.dir}`);
1840
+ console.log(`phase: ${st.phase}`);
1841
+ console.log(`worktree: ${gitRoot}`);
1842
+ console.log(`branch: ${branch || "(detached HEAD)"}`);
1843
+ if (wtHint.changeWorktree) console.log(`note: change/<id> checked out in another worktree: ${wtHint.changeWorktree}`);
1295
1844
  console.log(`meta: ${st.metaState}`);
1296
1845
  if (st.reqId) console.log(`Req_ID: ${st.reqId}`);
1297
1846
  if (st.probId) console.log(`Problem_ID: ${st.probId}`);
1298
1847
  console.log(`tasks: ${st.tasks.done}/${st.tasks.total} (unchecked=${st.tasks.unchecked})`);
1299
1848
  console.log(`baseline: ${st.baselineLabel}${st.baselineAt ? ` (at=${st.baselineAt})` : ""}`);
1300
1849
  console.log(`drift: ${st.driftFiles.length > 0 ? st.driftFiles.join(", ") : "(none)"}`);
1850
+ if (st.evidence?.counts) {
1851
+ const c = st.evidence.counts;
1852
+ console.log(`evidence: declared=${c.total} (exists=${c.exists}, missing=${c.missing}, persistent=${c.persistent}, tmp=${c.tmp})`);
1853
+ }
1301
1854
 
1302
1855
  console.log("");
1303
1856
  console.log("Blockers (strict):");
@@ -1312,11 +1865,29 @@ export async function changeStatusCommand(options) {
1312
1865
  console.log("");
1313
1866
  console.log("Next (recommended):");
1314
1867
  console.log(`- ${planVerifyHint(st.changeId)}`);
1315
- if (st.blockersStrict.length === 0) {
1316
- console.log("- 质量门通过后再进入编码:在 AI 工具中运行 `$ws-dev`(小步实现 + 可复现验证)");
1317
- } else {
1868
+ if (st.blockersStrict.length > 0) {
1318
1869
  console.log("- 先修复 Blockers (strict) 后复跑质量门,再进入 `$ws-dev`");
1870
+ if (wtHint.changeWorktree) console.log(`- 若需要写代码:先切到 change worktree 再改动:\`cd ${wtHint.changeWorktree}\``);
1871
+ return;
1872
+ }
1873
+
1874
+ if (st.tasks.unchecked > 0) {
1875
+ console.log("- 继续开发:在 AI 工具中运行 `$ws-dev`(小步实现 + 可复现验证)");
1876
+ console.log("- 提交/交付前强制门禁:`aiws validate .`(可选落盘:`aiws validate . --stamp`)");
1877
+ console.log(`- (可选)状态快照:\`aiws change state ${st.changeId} --write\``);
1878
+ return;
1319
1879
  }
1880
+
1881
+ // deliver-ready hints
1882
+ if (st.evidence?.counts && st.evidence.counts.persistent === 0) {
1883
+ console.log("- 交付前建议生成持久证据:`changes/<id>/evidence/...`(并把路径回填到 proposal.md 的 Evidence_Path)");
1884
+ }
1885
+ if (st.evidence?.missing && st.evidence.missing.length > 0) {
1886
+ const show = st.evidence.missing.slice(0, 5);
1887
+ console.log(`- 交付前建议补齐缺失证据文件(missing=${st.evidence.missing.length}):${show.join(", ")}${st.evidence.missing.length > show.length ? ", ..." : ""}`);
1888
+ }
1889
+ console.log(`- (可选)状态快照:\`aiws change state ${st.changeId} --write\``);
1890
+ console.log("- 进入交付:在 AI 工具中运行 `$ws-deliver`(submodule 感知提交 + 门禁 + 最终 `$ws-finish`)");
1320
1891
  }
1321
1892
 
1322
1893
  /**
@@ -1330,6 +1901,7 @@ export async function changeNextCommand(options) {
1330
1901
 
1331
1902
  const changeId = await resolveChangeId(gitRoot, options.changeId, { command: "next" });
1332
1903
  assertValidChangeId(changeId);
1904
+ const branch = await currentBranch(gitRoot);
1333
1905
 
1334
1906
  const changeDir = changeDirAbs(gitRoot, changeId);
1335
1907
  if (!(await pathExists(changeDir))) throw new UserError(`Missing change dir: ${path.relative(gitRoot, changeDir)}`);
@@ -1355,6 +1927,26 @@ export async function changeNextCommand(options) {
1355
1927
  /** @type {string[]} */
1356
1928
  const actions = [];
1357
1929
 
1930
+ const inferred = inferChangeIdFromBranch(branch);
1931
+ if (!branch) {
1932
+ actions.push("当前为 detached HEAD:建议切到 `change/<change-id>` 分支后再继续(或显式传入 `<change-id>`)");
1933
+ } else if (inferred && inferred !== changeId) {
1934
+ actions.push(`当前分支为 \`${branch}\`(推断 change=${inferred}),但你在查看 change=${changeId}:建议先切换到 \`change/${changeId}\` 再执行开发/交付`);
1935
+ } else if (!inferred) {
1936
+ actions.push(`当前分支为 \`${branch}\`(非 change 分支):建议 \`aiws change start ${changeId} --hooks --switch\` 或 \`git switch change/${changeId}\``);
1937
+ }
1938
+
1939
+ try {
1940
+ const worktrees = await listGitWorktrees(gitRoot);
1941
+ const changeRef = `refs/heads/change/${changeId}`;
1942
+ const changeWt = worktrees.find((w) => String(w.branch || "") === changeRef);
1943
+ if (changeWt?.worktree && path.resolve(changeWt.worktree) !== path.resolve(gitRoot)) {
1944
+ actions.push(`change/${changeId} 分支在另一个 worktree:\`cd ${changeWt.worktree}\`(建议在该目录执行开发/交付相关命令)`);
1945
+ }
1946
+ } catch {
1947
+ // best-effort; ignore
1948
+ }
1949
+
1358
1950
  if (!meta) {
1359
1951
  actions.push(`补齐元信息并建立真值基线:\`aiws change sync ${changeId}\``);
1360
1952
  }
@@ -1382,6 +1974,33 @@ export async function changeNextCommand(options) {
1382
1974
  if (!(reqId || probId)) {
1383
1975
  actions.push("补齐归因:在 proposal.md 填写非空 `Req_ID` 或 `Problem_ID`(严格校验需要)");
1384
1976
  }
1977
+
1978
+ const contractRow = extractId("Contract_Row", proposal.text) || extractId("Contract_Row(s)", proposal.text);
1979
+ if (!contractRow) actions.push("补齐绑定:在 proposal.md 填写非空 `Contract_Row`(严格校验需要)");
1980
+
1981
+ const planFile = extractId("Plan_File", proposal.text) || extractId("Plan file", proposal.text);
1982
+ const planFiles = splitDeclaredValues(planFile);
1983
+ if (planFiles.length !== 1) actions.push("补齐绑定:proposal.md `Plan_File` 必须且只能包含 1 个 plan 路径(严格校验需要)");
1984
+ else {
1985
+ const planRel = String(planFiles[0] || "").replace(/^\.\//, "");
1986
+ if (path.isAbsolute(planRel)) actions.push("修正绑定:proposal.md `Plan_File` 必须是工作区相对路径(不要绝对路径)");
1987
+ else if (!(await pathExists(path.join(gitRoot, planRel)))) actions.push(`补齐计划文件:缺少 ${planRel}(或修正 proposal.md 的 Plan_File)`);
1988
+ }
1989
+
1990
+ const evidenceDecl = extractId("Evidence_Path", proposal.text) || extractId("Evidence_Path(s)", proposal.text);
1991
+ const evidencePaths = splitDeclaredValues(evidenceDecl);
1992
+ if (evidencePaths.length === 0) {
1993
+ actions.push("补齐绑定:在 proposal.md 填写非空 `Evidence_Path`(严格校验需要;建议优先写 `changes/<id>/evidence/...`)");
1994
+ } else {
1995
+ const evidence = await analyzeEvidencePaths(gitRoot, changeId, evidencePaths);
1996
+ if (evidence.counts.persistent === 0) {
1997
+ actions.push("交付前建议生成持久证据:`changes/<id>/evidence/...`(并把路径回填到 Evidence_Path;`.agentdocs/tmp/...` 可作为原始证据引用)");
1998
+ }
1999
+ if (evidence.missing.length > 0) {
2000
+ const show = evidence.missing.slice(0, 5);
2001
+ actions.push(`补齐缺失证据文件(missing=${evidence.missing.length}):${show.join(", ")}${evidence.missing.length > show.length ? ", ..." : ""}`);
2002
+ }
2003
+ }
1385
2004
  }
1386
2005
 
1387
2006
  const prog = tasks.state === "ok" ? checkboxStats(tasks.text) : { total: 0, done: 0, unchecked: 0, hasCheckboxes: false };
@@ -1400,15 +2019,487 @@ export async function changeNextCommand(options) {
1400
2019
  }
1401
2020
 
1402
2021
  console.log(`- ${planVerifyHint(changeId)}`);
1403
- console.log("- 若仍需继续编码,先通过质量门,再在 AI 工具中运行 `$ws-dev`");
1404
- console.log("- 生成交叉审计报告:在 AI 工具内运行 `/ws-review`(或按 AI_PROJECT.md 手工审计)");
2022
+ if (prog.unchecked > 0) {
2023
+ console.log("- 若仍需继续编码,先通过质量门,再在 AI 工具中运行 `$ws-dev`");
2024
+ } else {
2025
+ console.log("- 进入交付:在 AI 工具中运行 `$ws-deliver`(门禁 + submodule 感知提交 + 最终 `$ws-finish`)");
2026
+ console.log("- 交付前门禁(推荐落盘):`aiws validate . --stamp`");
2027
+ }
2028
+ console.log("- 审计与证据(推荐):在 AI 工具内运行 `/ws-review`(或按 AI_PROJECT.md 手工审计)");
1405
2029
  console.log(`- 归档:\`aiws change archive ${changeId}\``);
1406
2030
  }
1407
2031
 
2032
+ /**
2033
+ * @param {string} gitRoot
2034
+ * @param {string} changeId
2035
+ */
2036
+ async function computeChangeNextAdvice(gitRoot, changeId) {
2037
+ const st = await computeChangeStatus(gitRoot, changeId);
2038
+ const branch = await currentBranch(gitRoot);
2039
+ const inferred = inferChangeIdFromBranch(branch);
2040
+ const advice = {
2041
+ changeId,
2042
+ branch: branch || "",
2043
+ inferredChangeId: inferred || "",
2044
+ phase: st.phase,
2045
+ blockersStrict: st.blockersStrict,
2046
+ evidence: st.evidence?.counts || null,
2047
+ actions: [],
2048
+ prohibitions: [],
2049
+ recommended: [],
2050
+ };
2051
+
2052
+ if (!branch) {
2053
+ advice.actions.push("当前为 detached HEAD:建议切到 `change/<change-id>` 分支后再继续(或显式传入 `<change-id>`)");
2054
+ } else if (inferred && inferred !== changeId) {
2055
+ advice.actions.push(`当前分支为 \`${branch}\`(推断 change=${inferred}),但你在查看 change=${changeId}:建议先切换到 \`change/${changeId}\` 再执行开发/交付`);
2056
+ } else if (!inferred) {
2057
+ advice.actions.push(`当前分支为 \`${branch}\`(非 change 分支):建议 \`aiws change start ${changeId} --hooks --switch\` 或 \`git switch change/${changeId}\``);
2058
+ }
2059
+
2060
+ try {
2061
+ const worktrees = await listGitWorktrees(gitRoot);
2062
+ const changeRef = `refs/heads/change/${changeId}`;
2063
+ const changeWt = worktrees.find((w) => String(w.branch || "") === changeRef);
2064
+ if (changeWt?.worktree && path.resolve(changeWt.worktree) !== path.resolve(gitRoot)) {
2065
+ advice.actions.push(`change/${changeId} 分支在另一个 worktree:\`cd ${changeWt.worktree}\`(建议在该目录执行开发/交付相关命令)`);
2066
+ advice.prohibitions.push("不要在当前 worktree 继续写代码(很可能不在 change 分支上)");
2067
+ }
2068
+ } catch {
2069
+ // ignore
2070
+ }
2071
+
2072
+ if (st.metaState !== "ok") advice.actions.push(`补齐元信息并建立真值基线:\`aiws change sync ${changeId}\``);
2073
+ if (st.driftFiles.length > 0) {
2074
+ advice.actions.push("真值/合同已变化:先对齐 `AI_PROJECT.md` / `AI_WORKSPACE.md` / `REQUIREMENTS.md` 与 proposal/tasks");
2075
+ advice.actions.push(`确认后同步基线:\`aiws change sync ${changeId}\``);
2076
+ }
2077
+
2078
+ if (st.blockersStrict.some((b) => b.includes("proposal.md") && b.includes("WS:TODO"))) {
2079
+ advice.actions.push(`完善 proposal:\`$EDITOR ${path.join(changeDirAbs(gitRoot, changeId), "proposal.md")}\``);
2080
+ }
2081
+ if (st.blockersStrict.some((b) => b.includes("tasks.md") && b.includes("WS:TODO"))) {
2082
+ advice.actions.push(`完善 tasks:\`$EDITOR ${path.join(changeDirAbs(gitRoot, changeId), "tasks.md")}\``);
2083
+ }
2084
+ if (st.blockersStrict.some((b) => b.includes("proposal.md missing attribution"))) {
2085
+ advice.actions.push("补齐归因:在 proposal.md 填写非空 `Req_ID` 或 `Problem_ID`(严格校验需要)");
2086
+ }
2087
+ if (st.blockersStrict.some((b) => b.includes("missing Contract_Row"))) {
2088
+ advice.actions.push("补齐绑定:在 proposal.md 填写非空 `Contract_Row`(严格校验需要)");
2089
+ }
2090
+ if (st.blockersStrict.some((b) => b.includes("Plan_File"))) {
2091
+ advice.actions.push("补齐绑定:修正 proposal.md 的 `Plan_File`(严格校验需要;必须存在且仅 1 个)");
2092
+ }
2093
+ if (st.blockersStrict.some((b) => b.includes("missing Evidence_Path"))) {
2094
+ advice.actions.push("补齐绑定:在 proposal.md 填写非空 `Evidence_Path`(严格校验需要;建议优先写 `changes/<id>/evidence/...`)");
2095
+ }
2096
+ if (st.tasks.unchecked > 0) advice.actions.push(`完成未勾选任务(${st.tasks.unchecked} 项)`);
2097
+
2098
+ if (st.blockersStrict.length > 0 && advice.actions.length === 0) {
2099
+ advice.actions.push("先修复 Blockers (strict) 后复跑质量门,再进入 `$ws-dev`");
2100
+ }
2101
+
2102
+ if (advice.actions.length === 0) {
2103
+ if (st.tasks.unchecked > 0) {
2104
+ advice.recommended.push("继续开发:在 AI 工具中运行 `$ws-dev`(小步实现 + 可复现验证)");
2105
+ } else {
2106
+ advice.recommended.push("进入交付:在 AI 工具中运行 `$ws-deliver`(门禁 + submodule 感知提交 + 最终 `$ws-finish`)");
2107
+ if (advice.evidence && advice.evidence.persistent === 0) {
2108
+ advice.recommended.push("交付前建议生成持久证据并回填:`aiws change evidence <change-id>`");
2109
+ }
2110
+ }
2111
+ }
2112
+
2113
+ return advice;
2114
+ }
2115
+
2116
+ /**
2117
+ * aiws change state
2118
+ *
2119
+ * @param {{ changeId?: string, write: boolean }} options
2120
+ */
2121
+ export async function changeStateCommand(options) {
2122
+ const gitRoot = await resolveGitRoot(process.cwd());
2123
+ await ensureTruthFiles(gitRoot);
2124
+
2125
+ const changeId = await resolveChangeId(gitRoot, options.changeId, { command: "state" });
2126
+ assertValidChangeId(changeId);
2127
+
2128
+ const st = await computeChangeStatus(gitRoot, changeId);
2129
+ const advice = await computeChangeNextAdvice(gitRoot, changeId);
2130
+
2131
+ const now = nowIsoUtc();
2132
+ /** @type {string[]} */
2133
+ const lines = [];
2134
+ lines.push(`# AIWS STATE: ${changeId}`);
2135
+ lines.push("");
2136
+ lines.push(`Generated: ${now}`);
2137
+ lines.push("");
2138
+ lines.push("## Context");
2139
+ lines.push(`- Worktree: \`${gitRoot}\``);
2140
+ lines.push(`- Branch: \`${advice.branch || "(detached)"}\``);
2141
+ lines.push("");
2142
+ lines.push("## Phase");
2143
+ lines.push(`- Phase: \`${st.phase}\``);
2144
+ lines.push(`- Tasks: ${st.tasks.done}/${st.tasks.total} (unchecked=${st.tasks.unchecked})`);
2145
+ lines.push("");
2146
+ lines.push("## Bindings");
2147
+ if (st.reqId) lines.push(`- Req_ID: \`${st.reqId}\``);
2148
+ if (st.probId) lines.push(`- Problem_ID: \`${st.probId}\``);
2149
+ if (st.bindings?.contractRow) lines.push(`- Contract_Row: \`${st.bindings.contractRow}\``);
2150
+ if (st.bindings?.planFile) lines.push(`- Plan_File: \`${st.bindings.planFile}\``);
2151
+ lines.push("");
2152
+ lines.push("## Evidence");
2153
+ if (st.evidence?.counts) {
2154
+ const c = st.evidence.counts;
2155
+ lines.push(`- Declared: \`${c.total}\` (exists=\`${c.exists}\`, missing=\`${c.missing}\`, persistent=\`${c.persistent}\`, tmp=\`${c.tmp}\`)`);
2156
+ } else {
2157
+ lines.push("- (unknown)");
2158
+ }
2159
+ lines.push("");
2160
+ lines.push("## Blockers (strict)");
2161
+ if (st.blockersStrict.length === 0) lines.push("- (none)");
2162
+ else for (const b of st.blockersStrict) lines.push(`- ${b}`);
2163
+ lines.push("");
2164
+ lines.push("## Next");
2165
+ lines.push(`- ${planVerifyHint(changeId)}`);
2166
+ for (const a of advice.actions) lines.push(`- ${a}`);
2167
+ for (const r of advice.recommended) lines.push(`- ${r}`);
2168
+ if (advice.prohibitions.length > 0) {
2169
+ lines.push("");
2170
+ lines.push("## Do Not");
2171
+ for (const p of advice.prohibitions) lines.push(`- ${p}`);
2172
+ }
2173
+
2174
+ const out = lines.join("\n") + "\n";
2175
+ const dest = path.join(changeDirAbs(gitRoot, changeId), "STATE.md");
2176
+ if (options.write === true) {
2177
+ await writeText(dest, out);
2178
+ await appendMetricsEvent(gitRoot, changeId, "state_written", { path: path.relative(gitRoot, dest) });
2179
+ console.log(`ok: state written: ${path.relative(gitRoot, dest)}`);
2180
+ return;
2181
+ }
2182
+ process.stdout.write(out);
2183
+ }
2184
+
2185
+ /**
2186
+ * aiws metrics summary
2187
+ *
2188
+ * @param {{ since?: string }} options
2189
+ */
2190
+ export async function metricsSummaryCommand(options) {
2191
+ const gitRoot = await resolveGitRoot(process.cwd());
2192
+ await ensureTruthFiles(gitRoot);
2193
+
2194
+ const sinceRaw = String(options.since || "").trim();
2195
+ const since = sinceRaw ? new Date(`${sinceRaw}T00:00:00Z`).getTime() : 0;
2196
+ if (sinceRaw && Number.isNaN(since)) throw new UserError("Invalid --since (expected YYYY-MM-DD).", { details: `since=${sinceRaw}` });
2197
+
2198
+ const changesRoot = path.join(gitRoot, "changes");
2199
+ if (!(await pathExists(changesRoot))) {
2200
+ console.log("(no changes dir)");
2201
+ return;
2202
+ }
2203
+
2204
+ /** @type {Array<{ changeId: string, path: string, metrics: any }>} */
2205
+ const all = [];
2206
+ const scanDirs = [changesRoot, path.join(changesRoot, "archive")];
2207
+ for (const base of scanDirs) {
2208
+ if (!(await pathExists(base))) continue;
2209
+ const entries = await fs.readdir(base, { withFileTypes: true });
2210
+ for (const e of entries) {
2211
+ if (!e.isDirectory()) continue;
2212
+ const dir = path.join(base, e.name);
2213
+ const mAbs = path.join(dir, "metrics.json");
2214
+ if (!(await pathExists(mAbs))) continue;
2215
+ try {
2216
+ const m = JSON.parse(await readText(mAbs));
2217
+ const cid = String(m?.change_id || "").trim() || e.name;
2218
+ all.push({ changeId: cid, path: path.relative(gitRoot, mAbs), metrics: m });
2219
+ } catch {
2220
+ // ignore invalid
2221
+ }
2222
+ }
2223
+ }
2224
+
2225
+ if (all.length === 0) {
2226
+ console.log("(no metrics.json found)");
2227
+ return;
2228
+ }
2229
+
2230
+ /** @type {Record<string, number>} */
2231
+ const eventCounts = {};
2232
+ let strictValidations = 0;
2233
+ let strictPass = 0;
2234
+ let evidenceRuns = 0;
2235
+ let finishRuns = 0;
2236
+ /** @type {number[]} */
2237
+ const durations = [];
2238
+
2239
+ for (const row of all) {
2240
+ const events = Array.isArray(row.metrics?.events) ? row.metrics.events : [];
2241
+ const filtered = since
2242
+ ? events.filter((ev) => {
2243
+ const t = Date.parse(String(ev?.timestamp || ""));
2244
+ return Number.isFinite(t) && t >= since;
2245
+ })
2246
+ : events;
2247
+
2248
+ for (const ev of filtered) {
2249
+ const type = String(ev?.type || "unknown");
2250
+ eventCounts[type] = (eventCounts[type] || 0) + 1;
2251
+ if (type === "validate") {
2252
+ const p = ev?.payload || {};
2253
+ if (p.strict === true) {
2254
+ strictValidations += 1;
2255
+ if (p.ok === true) strictPass += 1;
2256
+ }
2257
+ }
2258
+ if (type === "evidence") evidenceRuns += 1;
2259
+ if (type === "finish") finishRuns += 1;
2260
+ }
2261
+
2262
+ // Cycle time (best-effort): change_new -> finish
2263
+ const tNew = events.find((e) => e?.type === "change_new")?.timestamp;
2264
+ const tFin = events.find((e) => e?.type === "finish")?.timestamp;
2265
+ if (tNew && tFin) {
2266
+ const a = Date.parse(String(tNew));
2267
+ const b = Date.parse(String(tFin));
2268
+ if (Number.isFinite(a) && Number.isFinite(b) && b >= a) durations.push(Math.floor((b - a) / 1000));
2269
+ }
2270
+ }
2271
+
2272
+ const avgSec = durations.length > 0 ? Math.floor(durations.reduce((x, y) => x + y, 0) / durations.length) : 0;
2273
+ const avgMin = avgSec ? Math.floor(avgSec / 60) : 0;
2274
+
2275
+ console.log(`AIWS Metrics Summary${sinceRaw ? ` (since ${sinceRaw})` : ""}`);
2276
+ console.log("================================================");
2277
+ console.log(`Total metric files: ${all.length}`);
2278
+ console.log("");
2279
+ console.log("Event counts:");
2280
+ for (const k of Object.keys(eventCounts).sort()) console.log(`- ${k}: ${eventCounts[k]}`);
2281
+ console.log("");
2282
+ console.log("Quality:");
2283
+ console.log(`- Strict validate pass rate: ${strictValidations > 0 ? `${strictPass}/${strictValidations}` : "(no data)"}`);
2284
+ console.log(`- Evidence runs: ${evidenceRuns}`);
2285
+ console.log(`- Finish runs: ${finishRuns}`);
2286
+ console.log("");
2287
+ console.log("Cycle time (best-effort):");
2288
+ console.log(`- Avg change_new -> finish: ${durations.length > 0 ? `${avgMin} min` : "(no data)"}`);
2289
+ }
2290
+
2291
+ /**
2292
+ * aiws change evidence
2293
+ *
2294
+ * @param {{ changeId?: string, noValidate: boolean, allowFail: boolean }} options
2295
+ */
2296
+ export async function changeEvidenceCommand(options) {
2297
+ const gitRoot = await resolveGitRoot(process.cwd());
2298
+ await ensureTruthFiles(gitRoot);
2299
+
2300
+ const changeId = await resolveChangeId(gitRoot, options.changeId, { command: "evidence" });
2301
+ assertValidChangeId(changeId);
2302
+
2303
+ const changeDir = changeDirAbs(gitRoot, changeId);
2304
+ if (!(await pathExists(changeDir))) throw new UserError(`Missing change dir: ${path.relative(gitRoot, changeDir)}`);
2305
+
2306
+ const proposal = await fileState(changeDir, "proposal.md");
2307
+ if (proposal.state !== "ok") throw new UserError("proposal.md is required for evidence generation.", { details: path.relative(gitRoot, proposal.abs) });
2308
+
2309
+ const planDecl = extractId("Plan_File", proposal.text) || extractId("Plan file", proposal.text);
2310
+ const planFiles = splitDeclaredValues(planDecl).map((p) => String(p || "").replace(/^\.\//, ""));
2311
+ const planRel = planFiles.length === 1 ? planFiles[0] : "";
2312
+ const planAbs = planRel ? path.join(gitRoot, planRel) : "";
2313
+ const planText = planAbs && (await pathExists(planAbs)) ? await readText(planAbs) : "";
2314
+
2315
+ const now = nowStampUtc();
2316
+ const evidenceDir = path.join(changeDir, "evidence");
2317
+ const reviewDir = path.join(changeDir, "review");
2318
+ await ensureDir(evidenceDir);
2319
+ await ensureDir(reviewDir);
2320
+
2321
+ /** @type {string[]} */
2322
+ const created = [];
2323
+
2324
+ const branch = await currentBranch(gitRoot);
2325
+
2326
+ const status = await computeChangeStatus(gitRoot, changeId);
2327
+ const statusOut = {
2328
+ generated_at: nowIsoUtc(),
2329
+ ws_root: gitRoot,
2330
+ change_id: changeId,
2331
+ branch: branch || "",
2332
+ phase: status.phase,
2333
+ tasks: status.tasks,
2334
+ bindings: status.bindings,
2335
+ truth: {
2336
+ baseline: { label: status.baselineLabel, at: status.baselineAt },
2337
+ drift_files: status.driftFiles,
2338
+ },
2339
+ evidence: status.evidence?.counts || null,
2340
+ note: "aiws change evidence status snapshot; does not contain secrets.",
2341
+ };
2342
+ const statusPath = path.join(evidenceDir, `change-status-${now}.json`);
2343
+ await writeText(statusPath, JSON.stringify(statusOut, null, 2) + "\n");
2344
+ created.push(relFromRoot(gitRoot, statusPath));
2345
+
2346
+ /** @type {any | null} */
2347
+ let validateRes = null;
2348
+ let validateFailed = false;
2349
+ /** @type {string} */
2350
+ let validatePathForError = "";
2351
+ if (!options.noValidate) {
2352
+ validateRes = await validateChangeArtifacts(gitRoot, changeId, { strict: true, allowTruthDrift: false });
2353
+ const validatePath = path.join(evidenceDir, `change-validate-strict-${now}.json`);
2354
+ await writeText(validatePath, JSON.stringify(validateRes, null, 2) + "\n");
2355
+ created.push(relFromRoot(gitRoot, validatePath));
2356
+ validateFailed = validateRes.ok !== true;
2357
+ validatePathForError = validatePath;
2358
+ }
2359
+
2360
+ const validateStampDir = path.join(gitRoot, ".agentdocs", "tmp", "aiws-validate");
2361
+ const latestValidateStamp = await findLatestFileByMtime(validateStampDir, (n) => n.endsWith(".json"));
2362
+ if (latestValidateStamp) {
2363
+ const dst = path.join(evidenceDir, `aiws-validate-stamp-${now}.json`);
2364
+ await fs.copyFile(latestValidateStamp, dst);
2365
+ created.push(relFromRoot(gitRoot, dst));
2366
+ }
2367
+
2368
+ const syncStampDir = path.join(gitRoot, ".agentdocs", "tmp", "change-sync");
2369
+ const latestSyncStamp = await findLatestFileByMtime(syncStampDir, (n) => n.endsWith(`-${changeId}.json`));
2370
+ if (latestSyncStamp) {
2371
+ const dst = path.join(evidenceDir, `change-sync-stamp-${now}.json`);
2372
+ await fs.copyFile(latestSyncStamp, dst);
2373
+ created.push(relFromRoot(gitRoot, dst));
2374
+ }
2375
+
2376
+ const reviewAbs = path.join(reviewDir, "codex-review.md");
2377
+ if (!(await pathExists(reviewAbs))) {
2378
+ const tmpReview = path.join(gitRoot, ".agentdocs", "tmp", "review", "codex-review.md");
2379
+ if (await pathExists(tmpReview)) {
2380
+ await fs.copyFile(tmpReview, reviewAbs);
2381
+ }
2382
+ }
2383
+ if (await pathExists(reviewAbs)) created.push(relFromRoot(gitRoot, reviewAbs));
2384
+
2385
+ // Collect all review files (support multiple reviewers)
2386
+ if (await pathExists(reviewDir)) {
2387
+ try {
2388
+ const reviewEntries = await fs.readdir(reviewDir, { withFileTypes: true });
2389
+ for (const e of reviewEntries) {
2390
+ if (!e.isFile()) continue;
2391
+ if (e.name === "codex-review.md") continue; // already added
2392
+ if (e.name.endsWith(".md")) {
2393
+ created.push(relFromRoot(gitRoot, path.join(reviewDir, e.name)));
2394
+ }
2395
+ }
2396
+ } catch {
2397
+ // ignore
2398
+ }
2399
+ }
2400
+
2401
+ // Delivery summary (persistent, human-readable).
2402
+ const summaryAbs = path.join(evidenceDir, `delivery-summary-${now}.md`);
2403
+ /** @type {string[]} */
2404
+ const summaryLines = [];
2405
+ summaryLines.push(`# Delivery Summary: ${changeId}`);
2406
+ summaryLines.push("");
2407
+ summaryLines.push(`Generated: ${nowIsoUtc()}`);
2408
+ summaryLines.push("");
2409
+ summaryLines.push("## Context");
2410
+ summaryLines.push(`- Worktree: \`${gitRoot}\``);
2411
+ summaryLines.push(`- Branch: \`${branch || "(detached)"}\``);
2412
+ summaryLines.push("");
2413
+ summaryLines.push("## Status");
2414
+ summaryLines.push(`- Phase: \`${status.phase}\``);
2415
+ summaryLines.push(`- Tasks: ${status.tasks.done}/${status.tasks.total} (unchecked=${status.tasks.unchecked})`);
2416
+ summaryLines.push(`- Truth drift: ${status.driftFiles.length > 0 ? status.driftFiles.join(", ") : "(none)"}`);
2417
+ summaryLines.push("");
2418
+ summaryLines.push("## Bindings");
2419
+ if (status.reqId) summaryLines.push(`- Req_ID: \`${status.reqId}\``);
2420
+ if (status.probId) summaryLines.push(`- Problem_ID: \`${status.probId}\``);
2421
+ if (status.bindings?.contractRow) summaryLines.push(`- Contract_Row: \`${status.bindings.contractRow}\``);
2422
+ if (status.bindings?.planFile) summaryLines.push(`- Plan_File: \`${status.bindings.planFile}\``);
2423
+ summaryLines.push("");
2424
+ summaryLines.push("## Evidence (Created/Collected)");
2425
+ if (created.length === 0) summaryLines.push("- (none)");
2426
+ else for (const p of created) summaryLines.push(`- \`${p}\``);
2427
+ summaryLines.push("");
2428
+ summaryLines.push("## Quality Gate");
2429
+ if (options.noValidate) {
2430
+ summaryLines.push("- Strict validation: (skipped via --no-validate)");
2431
+ } else if (validateRes) {
2432
+ summaryLines.push(`- Strict validation ok: \`${validateRes.ok === true}\``);
2433
+ summaryLines.push(`- Errors: \`${Array.isArray(validateRes.errors) ? validateRes.errors.length : 0}\``);
2434
+ summaryLines.push(`- Warnings: \`${Array.isArray(validateRes.warnings) ? validateRes.warnings.length : 0}\``);
2435
+ } else {
2436
+ summaryLines.push("- Strict validation: (unknown)");
2437
+ }
2438
+ summaryLines.push("");
2439
+ summaryLines.push("## Next");
2440
+ summaryLines.push(`- ${planVerifyHint(changeId)}`);
2441
+ if (validateFailed) summaryLines.push("- Fix strict validation errors, then re-run `aiws change evidence`");
2442
+ else summaryLines.push(`- Verify evidence gate: \`aiws change validate ${changeId} --strict --check-evidence\``);
2443
+ await writeText(summaryAbs, summaryLines.join("\n") + "\n");
2444
+ created.push(relFromRoot(gitRoot, summaryAbs));
2445
+
2446
+ const declaredEvidence = extractId("Evidence_Path", proposal.text) || extractId("Evidence_Path(s)", proposal.text);
2447
+ const existingProposalEvidence = splitDeclaredValues(declaredEvidence).map((p) => String(p || "").replace(/^\.\//, ""));
2448
+ const mergedEvidence = mergeDeclaredValues(existingProposalEvidence, created);
2449
+ const mergedEvidenceText = formatDeclaredValues(mergedEvidence);
2450
+
2451
+ const updatedProposal = upsertProposalEvidencePath(proposal.text, mergedEvidenceText);
2452
+ if (updatedProposal.changed) {
2453
+ await writeText(path.join(changeDir, "proposal.md"), updatedProposal.text);
2454
+ }
2455
+
2456
+ if (planAbs && planText) {
2457
+ const existingPlanEvidence = splitDeclaredValues(extractId("Evidence_Path", planText) || extractId("Evidence_Path(s)", planText)).map((p) =>
2458
+ String(p || "").replace(/^\.\//, ""),
2459
+ );
2460
+ const mergedPlanEvidence = mergeDeclaredValues(existingPlanEvidence, mergedEvidence);
2461
+ const mergedPlanEvidenceText = formatDeclaredValues(mergedPlanEvidence);
2462
+ const updatedPlan = upsertIdLine(planText, ["Evidence_Path", "Evidence_Path(s)"], mergedPlanEvidenceText, { insertAfterLabels: ["Plan_File", "Contract_Row"] });
2463
+ if (updatedPlan.changed) await writeText(planAbs, updatedPlan.text);
2464
+ }
2465
+
2466
+ await appendMetricsEvent(gitRoot, changeId, "evidence", {
2467
+ generated_at: nowIsoUtc(),
2468
+ created: created.length,
2469
+ strict_validate: options.noValidate ? "skipped" : validateRes && validateRes.ok === true ? "ok" : "failed",
2470
+ allow_fail: options.allowFail === true,
2471
+ });
2472
+
2473
+ console.log(`✓ aiws change evidence: ${changeId}`);
2474
+ console.log(`dir: ${path.relative(gitRoot, changeDir)}`);
2475
+ if (planRel) console.log(`Plan_File: ${planRel}`);
2476
+ if (created.length > 0) {
2477
+ console.log("created:");
2478
+ for (const p of created) console.log(`- ${p}`);
2479
+ } else {
2480
+ console.log("created:");
2481
+ console.log("- (none)");
2482
+ }
2483
+ console.log("updated:");
2484
+ console.log(`- ${path.relative(gitRoot, path.join(changeDir, "proposal.md"))} (Evidence_Path)`);
2485
+ if (planRel && planText) console.log(`- ${planRel} (Evidence_Path)`);
2486
+ console.log("");
2487
+ console.log("next:");
2488
+ console.log(`- ${planVerifyHint(changeId)}`);
2489
+ if (validateFailed) console.log("- fix validation errors, then re-run evidence (or run with --allow-fail to proceed)");
2490
+ else console.log(`- verify evidence gate: \`aiws change validate ${changeId} --strict --check-evidence\``);
2491
+
2492
+ if (validateFailed && !options.allowFail) {
2493
+ const details = (validateRes && validateRes.raw ? String(validateRes.raw) : "").trim() || "Validation failed (see evidence JSON for details).";
2494
+ const hint = validatePathForError ? `\n\nevidence:\n- ${path.relative(gitRoot, validatePathForError)}` : "";
2495
+ throw new UserError("Failed to generate evidence due to strict validation errors.", { details: `${details}${hint}` });
2496
+ }
2497
+ }
2498
+
1408
2499
  /**
1409
2500
  * aiws change validate
1410
2501
  *
1411
- * @param {{ changeId?: string, strict: boolean, allowTruthDrift: boolean }} options
2502
+ * @param {{ changeId?: string, strict: boolean, allowTruthDrift: boolean, checkEvidence: boolean, checkScope: boolean }} options
1412
2503
  */
1413
2504
  export async function changeValidateCommand(options) {
1414
2505
  const gitRoot = await resolveGitRoot(process.cwd());
@@ -1420,6 +2511,18 @@ export async function changeValidateCommand(options) {
1420
2511
  const res = await validateChangeArtifacts(gitRoot, changeId, {
1421
2512
  strict: options.strict === true,
1422
2513
  allowTruthDrift: options.allowTruthDrift === true,
2514
+ checkEvidence: options.checkEvidence === true,
2515
+ checkScope: options.checkScope === true,
2516
+ });
2517
+ await appendMetricsEvent(gitRoot, changeId, "validate", {
2518
+ ok: res.ok === true,
2519
+ strict: options.strict === true,
2520
+ allow_truth_drift: options.allowTruthDrift === true,
2521
+ check_evidence: options.checkEvidence === true,
2522
+ check_scope: options.checkScope === true,
2523
+ errors: Array.isArray(res.errors) ? res.errors.length : 0,
2524
+ warnings: Array.isArray(res.warnings) ? res.warnings.length : 0,
2525
+ exit_code: res.exitCode,
1423
2526
  });
1424
2527
  if (res.raw) process.stderr.write(res.raw + "\n");
1425
2528
  if (!res.ok) throw new UserError("");
@@ -1513,6 +2616,12 @@ export async function changeSyncCommand(options) {
1513
2616
  note: "aiws change sync stamp; does not contain secrets.",
1514
2617
  };
1515
2618
  await writeText(stampPath, JSON.stringify(stamp, null, 2) + "\n");
2619
+ await appendMetricsEvent(gitRoot, changeId, "truth_sync", {
2620
+ synced_at: nowIso,
2621
+ baseline_from: baselineLabel,
2622
+ baseline_at: baselineAt,
2623
+ changed_files: changed.map((c) => c.file),
2624
+ });
1516
2625
 
1517
2626
  console.log(`✓ aiws change sync: ${changeId}`);
1518
2627
  console.log(`meta: ${path.relative(gitRoot, metaPath)}`);
@@ -1565,10 +2674,17 @@ export async function changeArchiveCommand(options) {
1565
2674
  dest = path.join(archiveRoot, `${prefix}-${changeId}-${nowStampUtc()}`);
1566
2675
  }
1567
2676
 
2677
+ await appendMetricsEvent(gitRoot, changeId, "archive", { archived_to: path.relative(gitRoot, dest) });
1568
2678
  await fs.rename(changeDir, dest);
1569
2679
  console.log(`✓ aiws change archive: ${changeId}`);
1570
2680
  console.log(`archived_to: ${path.relative(gitRoot, dest)}`);
1571
2681
 
2682
+ // Generate handoff.md
2683
+ const handoffPath = path.join(dest, "handoff.md");
2684
+ const handoffContent = await generateHandoffContent(gitRoot, dest, changeId);
2685
+ await writeText(handoffPath, handoffContent);
2686
+ console.log(`handoff: ${path.relative(gitRoot, handoffPath)}`);
2687
+
1572
2688
  const metaPath = path.join(dest, ".ws-change.json");
1573
2689
  if (await pathExists(metaPath)) {
1574
2690
  try {