archscribe 0.2.1 → 0.2.2

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 (254) hide show
  1. package/README.md +97 -38
  2. package/dashboard-server/client-dist/assets/index-BK3iMzXX.css +1 -0
  3. package/dashboard-server/client-dist/assets/index-Bs2O2H8s.js +23 -0
  4. package/dashboard-server/client-dist/index.html +2 -2
  5. package/dashboard-server/dist/core-bridge.js +8 -1
  6. package/dashboard-server/dist/files-route.js +6 -0
  7. package/dashboard-server/dist/index.js +27 -29
  8. package/dashboard-server/dist/outputs-route.js +208 -0
  9. package/dashboard-server/dist/run-route.js +22 -7
  10. package/dist/cli/archscribe.js +47 -11
  11. package/dist/cli/archscribe.js.map +1 -1
  12. package/dist/cli/commands.js +6 -0
  13. package/dist/cli/commands.js.map +1 -1
  14. package/dist/cli/context.d.ts +1 -0
  15. package/dist/cli/context.js +34 -0
  16. package/dist/cli/context.js.map +1 -0
  17. package/dist/cli/doctor.js +2 -1
  18. package/dist/cli/doctor.js.map +1 -1
  19. package/dist/cli/history.js +58 -0
  20. package/dist/cli/history.js.map +1 -1
  21. package/dist/cli/login.js +4 -3
  22. package/dist/cli/login.js.map +1 -1
  23. package/dist/cli/logout.js +1 -1
  24. package/dist/cli/logout.js.map +1 -1
  25. package/dist/cli/review.d.ts +1 -0
  26. package/dist/cli/review.js +144 -0
  27. package/dist/cli/review.js.map +1 -0
  28. package/dist/cli/run.d.ts +4 -1
  29. package/dist/cli/run.js +17 -21
  30. package/dist/cli/run.js.map +1 -1
  31. package/dist/cli/shell.d.ts +1 -1
  32. package/dist/cli/shell.js +19 -4
  33. package/dist/cli/shell.js.map +1 -1
  34. package/dist/cli/ui/animations.js +1 -1
  35. package/dist/cli/ui/document-frame.d.ts +17 -0
  36. package/dist/cli/ui/document-frame.js +65 -0
  37. package/dist/cli/ui/document-frame.js.map +1 -0
  38. package/dist/cli/ui/document-tui.d.ts +5 -0
  39. package/dist/cli/ui/document-tui.js +224 -0
  40. package/dist/cli/ui/document-tui.js.map +1 -0
  41. package/dist/cli/ui/keys.d.ts +1 -0
  42. package/dist/cli/ui/keys.js +30 -6
  43. package/dist/cli/ui/keys.js.map +1 -1
  44. package/dist/cli/ui/little-scribe.d.ts +3 -0
  45. package/dist/cli/ui/little-scribe.js +67 -0
  46. package/dist/cli/ui/little-scribe.js.map +1 -0
  47. package/dist/cli/ui/mascot.d.ts +4 -2
  48. package/dist/cli/ui/mascot.js +19 -46
  49. package/dist/cli/ui/mascot.js.map +1 -1
  50. package/dist/cli/ui/menu.d.ts +1 -1
  51. package/dist/cli/ui/menu.js +1 -1
  52. package/dist/cli/ui/menu.js.map +1 -1
  53. package/dist/cli/ui/stage.js +12 -7
  54. package/dist/cli/ui/stage.js.map +1 -1
  55. package/dist/cli/ui/term.js +3 -1
  56. package/dist/cli/ui/term.js.map +1 -1
  57. package/dist/core/actor-inference.d.ts +1 -0
  58. package/dist/core/actor-inference.js +2 -1
  59. package/dist/core/actor-inference.js.map +1 -1
  60. package/dist/core/approval-ledger.d.ts +57 -0
  61. package/dist/core/approval-ledger.js +95 -0
  62. package/dist/core/approval-ledger.js.map +1 -0
  63. package/dist/core/component-groups.d.ts +2 -0
  64. package/dist/core/component-groups.js +4 -0
  65. package/dist/core/component-groups.js.map +1 -1
  66. package/dist/core/docx-package.d.ts +9 -0
  67. package/dist/core/docx-package.js +99 -0
  68. package/dist/core/docx-package.js.map +1 -0
  69. package/dist/core/docx-styles.d.ts +12 -11
  70. package/dist/core/docx-styles.js +12 -11
  71. package/dist/core/docx-styles.js.map +1 -1
  72. package/dist/core/docx-update.d.ts +6 -0
  73. package/dist/core/docx-update.js +469 -0
  74. package/dist/core/docx-update.js.map +1 -0
  75. package/dist/core/docx.d.ts +8 -2
  76. package/dist/core/docx.js +263 -74
  77. package/dist/core/docx.js.map +1 -1
  78. package/dist/core/flow-steps.d.ts +1 -4
  79. package/dist/core/flow-steps.js +46 -108
  80. package/dist/core/flow-steps.js.map +1 -1
  81. package/dist/core/flow-trace.d.ts +9 -2
  82. package/dist/core/flow-trace.js +57 -58
  83. package/dist/core/flow-trace.js.map +1 -1
  84. package/dist/core/flow.js +9 -7
  85. package/dist/core/flow.js.map +1 -1
  86. package/dist/core/grouping-messages.generated.d.ts +21 -0
  87. package/dist/core/grouping-messages.generated.js +22 -0
  88. package/dist/core/grouping-messages.generated.js.map +1 -0
  89. package/dist/core/iuh-logo.d.ts +1 -0
  90. package/dist/core/iuh-logo.js +3 -0
  91. package/dist/core/iuh-logo.js.map +1 -0
  92. package/dist/core/ledger-reconcile.d.ts +40 -0
  93. package/dist/core/ledger-reconcile.js +296 -0
  94. package/dist/core/ledger-reconcile.js.map +1 -0
  95. package/dist/core/manifest.js +1 -1
  96. package/dist/core/manifest.js.map +1 -1
  97. package/dist/core/markdown.d.ts +14 -1
  98. package/dist/core/markdown.js +83 -14
  99. package/dist/core/markdown.js.map +1 -1
  100. package/dist/core/materialize-report.d.ts +10 -0
  101. package/dist/core/materialize-report.js +72 -0
  102. package/dist/core/materialize-report.js.map +1 -0
  103. package/dist/core/output-history.d.ts +29 -0
  104. package/dist/core/output-history.js +204 -0
  105. package/dist/core/output-history.js.map +1 -0
  106. package/dist/core/output-mutation.d.ts +1 -0
  107. package/dist/core/output-mutation.js +15 -0
  108. package/dist/core/output-mutation.js.map +1 -0
  109. package/dist/core/parser.js +1 -0
  110. package/dist/core/parser.js.map +1 -1
  111. package/dist/core/project-config.d.ts +4 -0
  112. package/dist/core/project-config.js +39 -0
  113. package/dist/core/project-config.js.map +1 -1
  114. package/dist/core/review-feedback.d.ts +7 -0
  115. package/dist/core/review-feedback.js +46 -0
  116. package/dist/core/review-feedback.js.map +1 -0
  117. package/dist/core/uc-context-builder.d.ts +1 -0
  118. package/dist/core/uc-context-builder.js +11 -0
  119. package/dist/core/uc-context-builder.js.map +1 -1
  120. package/dist/core/uc-grouping-candidates.d.ts +9 -0
  121. package/dist/core/uc-grouping-candidates.js +35 -0
  122. package/dist/core/uc-grouping-candidates.js.map +1 -0
  123. package/dist/core/uc-grouping-evidence.d.ts +5 -0
  124. package/dist/core/uc-grouping-evidence.js +95 -0
  125. package/dist/core/uc-grouping-evidence.js.map +1 -0
  126. package/dist/core/uc-proposal.d.ts +19 -2
  127. package/dist/core/uc-proposal.js +127 -0
  128. package/dist/core/uc-proposal.js.map +1 -1
  129. package/dist/diagrams/activity.js +16 -5
  130. package/dist/diagrams/activity.js.map +1 -1
  131. package/dist/diagrams/arch/classify.d.ts +35 -0
  132. package/dist/diagrams/arch/classify.js +132 -0
  133. package/dist/diagrams/arch/classify.js.map +1 -0
  134. package/dist/diagrams/arch/layout-clean.d.ts +10 -0
  135. package/dist/diagrams/arch/layout-clean.js +74 -0
  136. package/dist/diagrams/arch/layout-clean.js.map +1 -0
  137. package/dist/diagrams/arch/layout-component.d.ts +13 -0
  138. package/dist/diagrams/arch/layout-component.js +136 -0
  139. package/dist/diagrams/arch/layout-component.js.map +1 -0
  140. package/dist/diagrams/arch/layout-hexagonal.d.ts +11 -0
  141. package/dist/diagrams/arch/layout-hexagonal.js +142 -0
  142. package/dist/diagrams/arch/layout-hexagonal.js.map +1 -0
  143. package/dist/diagrams/arch/layout-layered.d.ts +17 -0
  144. package/dist/diagrams/arch/layout-layered.js +89 -0
  145. package/dist/diagrams/arch/layout-layered.js.map +1 -0
  146. package/dist/diagrams/arch/model.d.ts +66 -0
  147. package/dist/diagrams/arch/model.js +216 -0
  148. package/dist/diagrams/arch/model.js.map +1 -0
  149. package/dist/diagrams/arch/xml.d.ts +20 -0
  150. package/dist/diagrams/arch/xml.js +39 -0
  151. package/dist/diagrams/arch/xml.js.map +1 -0
  152. package/dist/diagrams/architecture.d.ts +26 -36
  153. package/dist/diagrams/architecture.js +48 -155
  154. package/dist/diagrams/architecture.js.map +1 -1
  155. package/dist/diagrams/layout/radial.d.ts +1 -1
  156. package/dist/diagrams/layout/radial.js +385 -0
  157. package/dist/diagrams/layout/radial.js.map +1 -1
  158. package/dist/diagrams/sequence-model.js +6 -8
  159. package/dist/diagrams/sequence-model.js.map +1 -1
  160. package/dist/diagrams/usecase.d.ts +2 -1
  161. package/dist/diagrams/usecase.js +44 -20
  162. package/dist/diagrams/usecase.js.map +1 -1
  163. package/dist/diagrams/usecase_layout.d.ts +7 -12
  164. package/dist/diagrams/usecase_layout.js +25 -84
  165. package/dist/diagrams/usecase_layout.js.map +1 -1
  166. package/dist/knowledge/evidence.d.ts +48 -0
  167. package/dist/knowledge/evidence.js +253 -0
  168. package/dist/knowledge/evidence.js.map +1 -0
  169. package/dist/knowledge/hub-grouping.d.ts +4 -0
  170. package/dist/knowledge/hub-grouping.js +43 -26
  171. package/dist/knowledge/hub-grouping.js.map +1 -1
  172. package/dist/knowledge/local-kb.js +22 -20
  173. package/dist/knowledge/local-kb.js.map +1 -1
  174. package/dist/knowledge/rag-augment.d.ts +31 -6
  175. package/dist/knowledge/rag-augment.js +78 -37
  176. package/dist/knowledge/rag-augment.js.map +1 -1
  177. package/dist/knowledge/rag-client.js +1 -1
  178. package/dist/knowledge/rag-client.js.map +1 -1
  179. package/dist/knowledge/retriever.d.ts +1 -0
  180. package/dist/knowledge/retriever.js +4 -2
  181. package/dist/knowledge/retriever.js.map +1 -1
  182. package/dist/knowledge/store-lock.d.ts +2 -0
  183. package/dist/knowledge/store-lock.js +35 -0
  184. package/dist/knowledge/store-lock.js.map +1 -0
  185. package/dist/knowledge/types.d.ts +2 -0
  186. package/dist/license/client.d.ts +2 -1
  187. package/dist/license/client.js +5 -2
  188. package/dist/license/client.js.map +1 -1
  189. package/dist/license/gate.js +2 -2
  190. package/dist/license/gate.js.map +1 -1
  191. package/dist/license/verify.js +19 -14
  192. package/dist/license/verify.js.map +1 -1
  193. package/dist/parser.jar +0 -0
  194. package/dist/server.js +120 -29
  195. package/dist/server.js.map +1 -1
  196. package/dist/theory/context.d.ts +52 -0
  197. package/dist/theory/context.js +144 -0
  198. package/dist/theory/context.js.map +1 -0
  199. package/dist/theory/fill.d.ts +16 -2
  200. package/dist/theory/fill.js +129 -97
  201. package/dist/theory/fill.js.map +1 -1
  202. package/dist/theory/references.d.ts +5 -3
  203. package/dist/theory/references.js +8 -10
  204. package/dist/theory/references.js.map +1 -1
  205. package/dist/theory/scaffold.js +40 -24
  206. package/dist/theory/scaffold.js.map +1 -1
  207. package/dist/tools/analyze_project.js +3 -0
  208. package/dist/tools/analyze_project.js.map +1 -1
  209. package/dist/tools/environment.js +1 -0
  210. package/dist/tools/environment.js.map +1 -1
  211. package/dist/tools/generate_report.d.ts +10 -6
  212. package/dist/tools/generate_report.js +193 -277
  213. package/dist/tools/generate_report.js.map +1 -1
  214. package/dist/tools/propose_uc_groupings.d.ts +1 -10
  215. package/dist/tools/propose_uc_groupings.js +23 -79
  216. package/dist/tools/propose_uc_groupings.js.map +1 -1
  217. package/dist/tools/review_tools.d.ts +26 -0
  218. package/dist/tools/review_tools.js +55 -0
  219. package/dist/tools/review_tools.js.map +1 -0
  220. package/dist/tools/scaffold.d.ts +3 -1
  221. package/dist/tools/scaffold.js +103 -61
  222. package/dist/tools/scaffold.js.map +1 -1
  223. package/dist/tools/scan_repo.js +1 -1
  224. package/dist/tools/scan_repo.js.map +1 -1
  225. package/dist/types/ir.d.ts +4 -0
  226. package/dist/types/license.d.ts +3 -0
  227. package/dist/types/report.d.ts +11 -2
  228. package/dist/types/theory.d.ts +4 -0
  229. package/dist/types/uc-grouping.d.ts +58 -0
  230. package/dist/utils/dashboard-launcher.js +1 -0
  231. package/dist/utils/dashboard-launcher.js.map +1 -1
  232. package/dist/utils/mcp-launch.d.ts +2 -0
  233. package/dist/utils/mcp-launch.js +12 -1
  234. package/dist/utils/mcp-launch.js.map +1 -1
  235. package/dist/utils/run-history.d.ts +1 -2
  236. package/dist/utils/run-history.js +2 -11
  237. package/dist/utils/run-history.js.map +1 -1
  238. package/package.json +34 -14
  239. package/LICENSE +0 -33
  240. package/dashboard-server/client-dist/assets/index-CswIFyKN.js +0 -9
  241. package/dashboard-server/client-dist/assets/index-DWB_-3yk.css +0 -1
  242. package/dashboard-server/dist/review-route.js +0 -150
  243. package/dist/core/review-ledger.d.ts +0 -36
  244. package/dist/core/review-ledger.js +0 -104
  245. package/dist/core/review-ledger.js.map +0 -1
  246. package/dist/core/review-rerun.d.ts +0 -16
  247. package/dist/core/review-rerun.js +0 -31
  248. package/dist/core/review-rerun.js.map +0 -1
  249. package/dist/tools/review-tasks.d.ts +0 -28
  250. package/dist/tools/review-tasks.js +0 -168
  251. package/dist/tools/review-tasks.js.map +0 -1
  252. package/dist/utils/approval.d.ts +0 -37
  253. package/dist/utils/approval.js +0 -173
  254. package/dist/utils/approval.js.map +0 -1
@@ -1,7 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
- import { buildReportMarkdown } from "../core/markdown.js";
4
+ import { buildReportMarkdown, repairDuplicateManagedRegions } from "../core/markdown.js";
5
5
  import { renderMarkdownToDocx } from "../core/docx.js";
6
6
  import { buildUseCaseCatalog, buildUseCaseFlows } from "../core/flow.js";
7
7
  import { mergeUseCaseSelection, parseReviewNotesFile } from "./review.js";
@@ -10,15 +10,19 @@ import { loadSession } from "../license/session.js";
10
10
  import { runLicenseInfo } from "../license/run-license.js";
11
11
  import { applyLicenseLimits, isProTier } from "../license/gate.js";
12
12
  import { TRIAL_BANNER } from "../license/banner.js";
13
- import { extractUseCaseSection } from "../utils/approval.js";
14
- import { loadReviewLedger } from "../core/review-ledger.js";
15
- import { sourceKey, selectRerunWork } from "../core/review-rerun.js";
13
+ import { readLedger, ucKey, writeLedger } from "../core/approval-ledger.js";
14
+ import { mergeTheorySections, migrateLegacyApprovals, reconcileUseCases, captureProtectedDiagrams, applyProtectedDiagrams } from "../core/ledger-reconcile.js";
15
+ import { readFeedback } from "../core/review-feedback.js";
16
+ import { withOutputMutation } from "../core/output-mutation.js";
17
+ import { setDocxState } from "../core/materialize-report.js";
18
+ import { recordVersion } from "../core/output-history.js";
16
19
  import { writeActivityDiagrams } from "../diagrams/activity.js";
17
20
  import { writeSequenceDiagrams } from "../diagrams/sequence.js";
18
21
  import { writeUsecaseDiagrams } from "../diagrams/usecase.js";
19
22
  import { writeClassDiagram } from "../diagrams/class.js";
20
23
  import { writeArchitectureDiagram } from "../diagrams/architecture.js";
21
- import { resolveWorkspacePath, ensureDir } from "../utils/file.js";
24
+ import { validateArchOverride } from "../diagrams/arch/model.js";
25
+ import { resolveWorkspacePath, ensureDir, writeTextFile } from "../utils/file.js";
22
26
  import { notifyNewReport } from "../utils/dashboard-launcher.js";
23
27
  import { minifyIr } from "../utils/ir-minify.js";
24
28
  import { PipelineTimer } from "../evaluation/timing.js";
@@ -26,13 +30,13 @@ import { augmentFlowsWithRAG } from "../knowledge/rag-augment.js";
26
30
  import { recordPipelineComplete } from "../license/telemetry.js";
27
31
  import { collectEvaluationReport } from "../evaluation/collector.js";
28
32
  import { generateDashboard } from "../evaluation/dashboard.js";
29
- import { validateApprovedHubs, buildProposal, saveProposal } from "../core/uc-proposal.js";
33
+ import { resolveGrouping, buildGroupingAudit } from "../core/uc-proposal.js";
34
+ import { buildGroupingSnapshot } from "../core/uc-grouping-evidence.js";
30
35
  import { learnHubGrouping } from "../knowledge/hub-grouping.js";
31
- import { isLoginUc, isRegisterUc } from "../diagrams/usecase_layout.js";
32
36
  import { snapshotRun } from "../utils/run-history.js";
33
37
  import { clearDrawioDir } from "../utils/diagram-dir.js";
34
38
  import { getPackageVersion } from "../utils/version.js";
35
- import { buildManifest, writeManifest, sha256File } from "../core/manifest.js";
39
+ import { buildManifest, writeManifest } from "../core/manifest.js";
36
40
  /** Only DI edges (field_injection + constructor_injection) match the dependency ground-truth methodology. */
37
41
  const INJECTION_TYPES = new Set(["field_injection", "constructor_injection"]);
38
42
  /** Only core Spring domain stereotypes match the class-count ground-truth methodology. */
@@ -64,180 +68,59 @@ function normalizeClasses(raw) {
64
68
  * Returns paths to all generated artifacts.
65
69
  */
66
70
  export async function generateReport(input) {
67
- const outputDirInput = input.output_dir ?? path.join(input.ir.project.projectPath, "archscribe-output");
68
- const publishedDir = resolveWorkspacePath(outputDirInput);
69
- const outputDir = `${publishedDir}.stage-${randomUUID()}`;
70
- try {
71
- if (fs.existsSync(publishedDir))
72
- fs.cpSync(publishedDir, outputDir, { recursive: true });
73
- else
74
- ensureDir(outputDir);
75
- const result = await generateStagedReport(input, outputDir);
76
- if (!result.docx_path)
77
- fs.rmSync(path.join(outputDir, 'report.docx'), { force: true });
78
- const backup = `${publishedDir}.previous-${randomUUID()}`;
79
- const hadPrevious = fs.existsSync(publishedDir);
80
- if (hadPrevious)
81
- fs.renameSync(publishedDir, backup);
82
- try {
83
- fs.renameSync(outputDir, publishedDir);
84
- }
85
- catch (error) {
86
- if (hadPrevious)
87
- fs.renameSync(backup, publishedDir);
88
- throw error;
89
- }
90
- if (hadPrevious) {
91
- try {
92
- fs.rmSync(backup, { recursive: true, force: true });
93
- }
94
- catch { /* a completed publication must not be reported as failed due to backup cleanup */ }
95
- }
96
- const published = (file) => file?.replace(outputDir + path.sep, publishedDir + path.sep);
97
- if (process.env.ARCHSCRIBE_RESEARCH_MODE !== '1') {
98
- try {
99
- const evalReport = JSON.parse(fs.readFileSync(path.join(publishedDir, 'evaluation-report.json'), 'utf8'));
100
- notifyNewReport(input.ir.project.projectPath, evalReport).catch(() => { });
101
- recordPipelineComplete({
102
- ucCount: result.usecase_selected_count,
103
- diagramTypes: ['usecase', ...(result.class_diagram_path ? ['class'] : []),
104
- ...(result.architecture_diagram_path ? ['architecture'] : []),
105
- ...(result.activity_diagram_paths?.length ? ['activity'] : []),
106
- ...(result.sequence_diagram_paths?.length ? ['sequence'] : [])],
107
- processingMs: evalReport.timing.totalTimeMs,
108
- });
109
- }
110
- catch { /* a published report remains successful if optional notifications fail */ }
111
- }
112
- return {
113
- ...result, markdown_path: published(result.markdown_path), docx_path: published(result.docx_path),
114
- review_notes_path: published(result.review_notes_path),
115
- architecture_diagram_path: published(result.architecture_diagram_path),
116
- usecase_diagram_path: published(result.usecase_diagram_path),
117
- class_diagram_path: published(result.class_diagram_path),
118
- activity_diagram_paths: result.activity_diagram_paths?.map((p) => published(p)),
119
- sequence_diagram_paths: result.sequence_diagram_paths?.map((p) => published(p)),
120
- evaluation_report_path: published(result.evaluation_report_path), dashboard_path: published(result.dashboard_path),
121
- };
122
- }
123
- finally {
124
- if (fs.existsSync(outputDir))
125
- fs.rmSync(outputDir, { recursive: true, force: true });
126
- }
71
+ validateArchOverride(input.architecture_groups);
72
+ return withOutputMutation(input.ir.project.projectPath, () => generateReportUnlocked(input));
127
73
  }
128
- export function assertReviewLicenseCeiling(check, retained, work) {
129
- if (!isProTier(check) && retained + work > (check.features?.maxUC ?? 3)) {
130
- throw new Error('License UC ceiling: retained approvals and requested work exceed this tier; reduce work or upgrade.');
74
+ async function generateReportUnlocked(input) {
75
+ // Reject stale or malformed memberships before any managed output is changed.
76
+ const catalog = buildUseCaseCatalog(input.ir);
77
+ const groupingSnapshot = buildGroupingSnapshot(input.ir, catalog);
78
+ const grouping = resolveGrouping(groupingSnapshot, { reviewed: input.reviewed_grouping, legacy: input.approved_hubs });
79
+ const { resolveReportSource } = await import("../core/project-config.js");
80
+ const reportSource = resolveReportSource(input.ir.project.projectPath, input.report_source);
81
+ if (reportSource) {
82
+ const { validateManagedSource } = await import("../core/docx-update.js");
83
+ await validateManagedSource(fs.readFileSync(reportSource));
131
84
  }
132
- }
133
- async function generateStagedReport(input, outputDir) {
134
- const previousManifestPath = path.join(outputDir, 'manifest.json');
135
- const previousManifest = fs.existsSync(previousManifestPath) ? JSON.parse(fs.readFileSync(previousManifestPath, 'utf8')) : null;
85
+ const outputDirInput = input.output_dir ?? path.join(input.ir.project.projectPath, "archscribe-output");
86
+ const outputDir = resolveWorkspacePath(outputDirInput);
87
+ ensureDir(outputDir);
88
+ // Validate and checkpoint existing human work before the first managed write.
89
+ const projectRoot = input.ir.project.projectPath;
90
+ const ledger = readLedger(projectRoot);
91
+ const feedback = readFeedback(projectRoot);
92
+ const evaluationPath = path.join(outputDir, "evaluation-report.json");
93
+ const previous = fs.existsSync(evaluationPath) ? JSON.parse(fs.readFileSync(evaluationPath, "utf8")) : {};
94
+ const protectedDiagrams = captureProtectedDiagrams(outputDir, ledger, feedback, previous.usecases ?? [], previous.diagramPaths ?? {}, projectRoot);
95
+ await recordVersion(projectRoot, outputDir, "pre-run: preserve current edits");
96
+ setDocxState(outputDir, "stale");
136
97
  const timer = new PipelineTimer();
137
98
  timer.recordSplit("parse", input.parse_time_ms ?? 0);
99
+ // Export IR to disk so get_client_theory_scaffold and token-savings can read it
100
+ const irJsonPath = path.join(outputDir, "ir.json");
101
+ fs.writeFileSync(irJsonPath, JSON.stringify(minifyIr(input.ir), null, 2), "utf8");
102
+ // B3: what these docs were generated from — read back by `archscribe status`.
103
+ const manifest = buildManifest(input.ir, getPackageVersion());
104
+ writeManifest(outputDir, manifest);
105
+ // Read before anything is generated: a corrupt ledger must stop the run, not be overwritten.
106
+ const previousReportMd = fs.existsSync(path.join(outputDir, "report.md"))
107
+ ? fs.readFileSync(path.join(outputDir, "report.md"), "utf8")
108
+ : "";
138
109
  const classResult = normalizeClasses(input.classes);
139
110
  const dependencies = input.dependencies ?? [];
140
111
  // ── Review + selection ───────────────────────────────────────────────────
141
112
  const reviewPath = input.review_notes_path ? resolveWorkspacePath(input.review_notes_path) : undefined;
142
113
  const reviewSelection = parseReviewNotesFile(reviewPath);
143
114
  const usecaseSelection = mergeUseCaseSelection(input.usecase_selection, reviewSelection) ?? { limit: 8 };
144
- const requestedSelection = { ...usecaseSelection };
145
115
  // ── License gate ─────────────────────────────────────────────────────────
146
116
  const licenseCheck = await loadLicense([input.ir.project.projectPath]);
147
117
  const gateResult = applyLicenseLimits(licenseCheck, usecaseSelection);
148
118
  // ── UC flows ─────────────────────────────────────────────────────────────
149
119
  timer.start("flow");
150
- const catalog = buildUseCaseCatalog(input.ir);
151
- const projectRoot = input.ir.project.projectPath;
152
- const ledger = loadReviewLedger(input.ir.project.projectPath);
153
- const candidates = catalog.map((c) => ({ id: c.id, key: sourceKey({ endpoint: c.endpoint, sourceFile: c.sourceFile, controllerName: c.controller, methodName: c.methodName }) }));
154
- if (new Set(candidates.map((c) => c.key)).size !== candidates.length)
155
- throw new Error('Ambiguous duplicate use case source; reconcile before rerunning.');
156
- // A new comment/draft does not revoke the last human-approved version.
157
- const frozen = (key) => !!ledger.entries[key]?.snapshots?.spec && ledger.entries[key]?.status !== 'pending';
158
- const approvedKeys = new Set(Object.values(ledger.entries).filter((e) => frozen(e.key)).map((e) => e.key));
159
- const explicit = new Set();
160
- const hasExplicit = !!(requestedSelection.selected_ids?.length || requestedSelection.selected_titles?.length || requestedSelection.selected_endpoints?.length);
161
- for (const c of catalog) {
162
- if (requestedSelection.selected_ids?.some((id) => id.toUpperCase() === c.id.toUpperCase()) ||
163
- requestedSelection.selected_titles?.some((title) => c.title.toLowerCase().includes(title.trim().toLowerCase())) ||
164
- requestedSelection.selected_endpoints?.some((endpoint) => c.endpoint.toLowerCase() === endpoint.trim().toLowerCase())) {
165
- explicit.add(sourceKey({ endpoint: c.endpoint, sourceFile: c.sourceFile, controllerName: c.controller, methodName: c.methodName }));
166
- }
167
- }
168
- const unmatched = requestedSelection.selected_ids?.filter((id) => !catalog.some((c) => c.id.toUpperCase() === id.toUpperCase())) ?? [];
169
- if (unmatched.length)
170
- throw new Error(`Unmatched legacy use case ID(s): ${unmatched.join(', ')}; reconcile by endpoint before rerunning.`);
171
- if (hasExplicit && !explicit.size)
172
- throw new Error('Requested use cases did not match any current source; reconcile the selection before rerunning.');
173
- const chosen = selectRerunWork(candidates, approvedKeys, usecaseSelection.limit ?? 8, hasExplicit ? explicit : undefined);
174
- assertReviewLicenseCeiling(licenseCheck, chosen.retainedKeys.length, chosen.workKeys.length);
175
- // Only write staged files once identity/ledger/license checks have succeeded.
176
- const irJsonPath = path.join(outputDir, 'ir.json');
177
- fs.writeFileSync(irJsonPath, JSON.stringify(minifyIr(input.ir), null, 2), 'utf8');
178
- writeManifest(outputDir, buildManifest(input.ir, getPackageVersion()));
179
- const selected = [...chosen.retainedKeys, ...chosen.workKeys];
180
- const currentIds = candidates.filter((c) => selected.includes(c.key)).map((c) => c.id);
181
- const usecaseFlows = currentIds.length ? buildUseCaseFlows(input.ir, { selected_ids: currentIds }, isProTier(licenseCheck) ? "pro" : "baseline") : [];
182
- const byKey = new Map(usecaseFlows.map((f) => [sourceKey(f), f]));
183
- const effectiveFlows = selected.filter((key) => byKey.has(key)).map((key) => {
184
- const flow = byKey.get(key);
185
- if (!flow)
186
- throw new Error(`Missing selected use case: ${key}`);
187
- return flow;
188
- });
189
- for (const key of chosen.unresolvedKeys) {
190
- const entry = ledger.entries[key];
191
- const [endpoint, sourceFile, controllerName, methodName] = JSON.parse(key);
192
- effectiveFlows.splice(chosen.retainedKeys.indexOf(key), 0, { id: '', title: entry.title ?? methodName, endpoint, controllerName, methodName,
193
- actor: '', purpose: '', description: 'Nguồn không còn trong lần quét hiện tại; giữ bản đã duyệt để đối chiếu.',
194
- preconditions: [], successPostconditions: [], failurePostconditions: [], mainSteps: [], alternateFlows: [],
195
- tier: 'baseline', sequenceSteps: [], sourceTrace: [`${sourceFile} -> ${controllerName}.${methodName}`] });
196
- }
197
- // Preserve the display ID in a frozen section; new work receives a unique ID if ranks shifted.
198
- const usedIds = new Set();
199
- for (const flow of effectiveFlows) {
200
- const entry = ledger.entries[sourceKey(flow)];
201
- if (frozen(sourceKey(flow))) {
202
- const spec = fs.readFileSync(path.join(projectRoot, '.archscribe', entry.snapshots.spec), 'utf8');
203
- flow.id = /^\*\*(UC\d+)\s+-\s+/m.exec(spec)?.[1] ?? flow.id;
204
- if (!flow.id)
205
- throw new Error('Approved spec has no use case ID');
206
- if (usedIds.has(flow.id))
207
- throw new Error(`Approved use cases share display ID ${flow.id}; reconcile before rerunning.`);
208
- usedIds.add(flow.id);
209
- }
210
- }
211
- let nextId = catalog.length + 1;
212
- for (const flow of effectiveFlows)
213
- if (!frozen(sourceKey(flow))) {
214
- if (usedIds.has(flow.id)) {
215
- do {
216
- flow.id = `UC${String(nextId++).padStart(3, '0')}`;
217
- } while (usedIds.has(flow.id));
218
- }
219
- usedIds.add(flow.id);
220
- }
221
- usecaseFlows.length = 0;
222
- usecaseFlows.push(...effectiveFlows);
223
- const changedApproved = [];
224
- for (const flow of usecaseFlows) {
225
- const entry = ledger.entries[sourceKey(flow)];
226
- if (!frozen(sourceKey(flow)) || !entry || !byKey.has(entry.key))
227
- continue;
228
- const current = catalog.find((c) => candidates.find((x) => x.id === c.id)?.key === entry.key);
229
- if (current && entry.title && entry.title !== current.title)
230
- changedApproved.push(flow.endpoint);
231
- const relative = flow.sourceTrace[0]?.split(' -> ')[0]?.replace(/\\/g, '/');
232
- const projectRelative = relative && path.posix.join(previousManifest?.sourceRoot ?? input.ir.project.sourceRoot, relative);
233
- const before = entry.sourceFingerprint ?? (projectRelative && previousManifest?.files[projectRelative]);
234
- const absolute = projectRelative && path.join(projectRoot, projectRelative);
235
- if (before && absolute && fs.existsSync(absolute) && before !== sha256File(absolute)) {
236
- changedApproved.push(flow.endpoint);
237
- }
238
- }
120
+ const usecaseFlows = buildUseCaseFlows(input.ir, usecaseSelection, isProTier(licenseCheck) ? "pro" : "baseline");
239
121
  // RAG augmentation (no-op when ARCHSCRIBE_ENABLE_RAG unset or ARCHSCRIBE_RESEARCH_MODE=1)
240
- await augmentFlowsWithRAG(usecaseFlows.filter((f) => !frozen(sourceKey(f))));
122
+ const semanticDecisions = await augmentFlowsWithRAG(usecaseFlows, input.ir);
123
+ writeTextFile(path.join(outputDir, "semantic-decisions.json"), JSON.stringify(semanticDecisions, null, 2));
241
124
  // Apply actor overrides (Pro only — gateResult.blockActorOverrides=true for free)
242
125
  const effectiveOverrides = gateResult.blockActorOverrides ? undefined : input.actor_overrides;
243
126
  if (effectiveOverrides) {
@@ -263,140 +146,79 @@ async function generateStagedReport(input, outputDir) {
263
146
  }
264
147
  }
265
148
  timer.stop("flow");
266
- // ── LLM-approved UC grouping ──────────────────────────────────────────────
267
- // When approved_hubs provided: set env var so groupIntoHubs() uses LLM grouping.
268
- // Cleared in finally so it never leaks to other generate_report calls.
269
- if (input.approved_hubs?.length) {
270
- // Login/Register UCs are handled separately by the diagram — exclude from validation.
271
- const allUcIds = catalog
272
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
273
- .filter(it => !isLoginUc(it) && !isRegisterUc(it))
274
- .map(it => it.id);
275
- const errors = validateApprovedHubs(input.approved_hubs, allUcIds);
276
- if (errors.length > 0) {
277
- throw new Error(`Invalid approved_hubs (${errors.length} error(s)):\n${errors.map(e => ` - ${e}`).join("\n")}`);
278
- }
279
- process.env.ARCHSCRIBE_APPROVED_GROUPING = JSON.stringify(input.approved_hubs.map(h => ({ label: h.label, ucs: h.ucs })));
280
- // Save audit trail
281
- const proposalItems = catalog.map(it => ({
282
- id: it.id, title: it.title, controller: it.controller,
283
- endpoint: it.endpoint, actors: it.actors,
284
- }));
285
- const proposal = buildProposal(input.approved_hubs, proposalItems, input.ir.project.projectPath);
286
- saveProposal(outputDir, proposal);
287
- // RAG learn (best-effort, silent fail)
288
- learnHubGrouping(input.approved_hubs.map(h => ({ label: h.label, ucTitles: h.ucs.map(u => u.title) })), path.basename(input.ir.project.projectPath)).catch(() => { });
289
- }
290
149
  // ── Diagrams ─────────────────────────────────────────────────────────────
291
150
  timer.start("diagram");
292
151
  const diagramsDir = path.join(outputDir, "diagrams");
293
152
  ensureDir(diagramsDir);
294
153
  const activityDir = path.join(diagramsDir, "activity");
295
154
  const sequenceDir = path.join(diagramsDir, "sequence");
296
- // Drop the previous run's activity/sequence diagrams before restoring approved
297
- // ones and writing this run's. Without this, a smaller selection leaves the
298
- // older files behind: stale UCs show up in the report folder and
299
- // computeCompleteness() counts them (coverage/score above 100%).
155
+ // Drop the previous run's activity/sequence diagrams before writing this run's.
156
+ // Without this, a smaller selection leaves the older files behind: stale UCs
157
+ // show up in the report folder and computeCompleteness() counts them.
158
+ // Approved diagrams are restored by key from approved/diagrams/ in reconcileUseCases.
300
159
  clearDrawioDir(activityDir);
301
160
  clearDrawioDir(sequenceDir);
302
161
  let activityPaths;
303
162
  let sequencePaths;
304
163
  let usecaseDiagramPath;
164
+ let usecaseDiagramPaths = [];
305
165
  let classDiagramPath;
306
166
  let architectureDiagramPath;
307
- try {
308
- const newFlows = usecaseFlows.filter((f) => !frozen(sourceKey(f)));
309
- writeActivityDiagrams(newFlows, activityDir);
310
- writeSequenceDiagrams(newFlows, sequenceDir);
311
- for (const flow of usecaseFlows) {
312
- const entry = ledger.entries[sourceKey(flow)];
313
- if (!frozen(sourceKey(flow)))
314
- continue;
315
- for (const kind of ['activity', 'sequence']) {
316
- const snapshot = entry.snapshots?.[kind];
317
- if (!snapshot)
318
- continue;
319
- const spec = fs.readFileSync(path.join(projectRoot, '.archscribe', entry.snapshots.spec), 'utf8');
320
- const figure = new RegExp(`<!-- FIGURE: diagrams/${kind}/([^\\s"/\\\\]+\\.drawio)`).exec(spec)?.[1];
321
- const dest = path.join(kind === 'activity' ? activityDir : sequenceDir, figure ?? `${flow.id}_${kind}.drawio`);
322
- fs.copyFileSync(path.join(projectRoot, '.archscribe', snapshot), dest);
323
- }
324
- }
325
- const activityByFlow = usecaseFlows.map((f) => {
326
- const file = fs.readdirSync(activityDir).find((name) => name.startsWith(`${f.id}_`) && name.endsWith('.drawio'));
327
- return file ? path.join(activityDir, file) : undefined;
328
- });
329
- activityByFlow.forEach((p, i) => { if (p)
167
+ {
168
+ activityPaths = writeActivityDiagrams(usecaseFlows, activityDir);
169
+ activityPaths.forEach((p, i) => { if (usecaseFlows[i])
330
170
  usecaseFlows[i].activityDiagramPath = path.relative(outputDir, p); });
331
- const sequenceByFlow = usecaseFlows.map((f) => {
332
- const file = fs.readdirSync(sequenceDir).find((name) => name.startsWith(`${f.id}_`) && name.endsWith('.drawio'));
333
- return file ? path.join(sequenceDir, file) : undefined;
334
- });
335
- sequenceByFlow.forEach((p, i) => { if (p)
171
+ sequencePaths = gateResult.sequenceDiagram ? writeSequenceDiagrams(usecaseFlows, sequenceDir) : [];
172
+ sequencePaths.forEach((p, i) => { if (usecaseFlows[i])
336
173
  usecaseFlows[i].sequenceDiagramPath = path.relative(outputDir, p); });
337
- activityPaths = activityByFlow.filter((p) => !!p);
338
- sequencePaths = sequenceByFlow.filter((p) => !!p);
339
- const usecasePaths = await writeUsecaseDiagrams(usecaseFlows, catalog, diagramsDir);
340
- usecaseDiagramPath = usecasePaths[0] ?? path.join(diagramsDir, "usecase-guest-customer.drawio");
174
+ usecaseDiagramPaths = await writeUsecaseDiagrams(usecaseFlows, catalog, diagramsDir, grouping);
175
+ usecaseDiagramPath = usecaseDiagramPaths[0] ?? path.join(diagramsDir, "usecase-guest-customer.drawio");
341
176
  if (!usecaseSelection.disablePremiumDiagrams) {
342
177
  classDiagramPath = path.join(diagramsDir, "class.drawio");
343
178
  await writeClassDiagram(input.ir, classDiagramPath);
344
179
  architectureDiagramPath = path.join(diagramsDir, "architecture.drawio");
345
- writeArchitectureDiagram(input.ir, architectureDiagramPath);
180
+ await writeArchitectureDiagram(input.ir, architectureDiagramPath, input.architecture_groups);
346
181
  }
347
182
  timer.stop("diagram");
348
183
  }
349
- finally {
350
- // Always clear env var — prevents leaking approved grouping to other calls
351
- if (input.approved_hubs?.length)
352
- delete process.env.ARCHSCRIBE_APPROVED_GROUPING;
353
- }
184
+ applyProtectedDiagrams(outputDir, protectedDiagrams, usecaseFlows, {
185
+ usecase: path.relative(outputDir, usecaseDiagramPath),
186
+ ...(classDiagramPath ? { class: path.relative(outputDir, classDiagramPath) } : {}),
187
+ ...(architectureDiagramPath ? { architecture: path.relative(outputDir, architectureDiagramPath) } : {}),
188
+ });
354
189
  // ── Report markdown ───────────────────────────────────────────────────────
355
190
  timer.start("report");
356
191
  const report = buildReportMarkdown(input.ir, classResult, dependencies, input.project_info, usecaseFlows, usecaseSelection, catalog, {
357
192
  usecase: path.relative(outputDir, usecaseDiagramPath),
193
+ usecases: usecaseDiagramPaths.map((diagram) => path.relative(outputDir, diagram)),
358
194
  ...(classDiagramPath ? { class: path.relative(outputDir, classDiagramPath) } : {}),
359
195
  ...(architectureDiagramPath ? { architecture: path.relative(outputDir, architectureDiagramPath) } : {}),
360
- });
361
- for (const flow of usecaseFlows) {
362
- const entry = ledger.entries[sourceKey(flow)];
363
- if (!frozen(sourceKey(flow)))
364
- continue;
365
- const section = fs.readFileSync(path.join(projectRoot, '.archscribe', entry.snapshots.spec), 'utf8');
366
- const generated = extractUseCaseSection(report.markdown, flow.id);
367
- if (!generated)
368
- throw new Error(`Missing generated section: ${flow.id}`);
369
- report.markdown = report.markdown.replace(generated.trimEnd(), section.trimEnd());
370
- }
371
- if (chosen.unresolvedKeys.length) {
372
- const warning = `\n**Cần đối chiếu:** ${chosen.unresolvedKeys.length} use case đã duyệt nhưng nguồn không còn trong lần quét hiện tại; bản lưu được giữ nguyên.\n`;
373
- report.markdown = report.markdown.replace('#### 3.1.4 Đặc tả một số use case', `${warning}\n#### 3.1.4 Đặc tả một số use case`);
374
- }
375
- if (changedApproved.length) {
376
- const warning = `\n**Cần đối chiếu:** Nguồn đã thay đổi cho use case đã duyệt: ${[...new Set(changedApproved)].join(', ')}. Đặc tả và sơ đồ vẫn là bản lưu, cần duyệt lại.\n`;
377
- report.markdown = report.markdown.replace('#### 3.1.4 Đặc tả một số use case', `${warning}\n#### 3.1.4 Đặc tả một số use case`);
378
- }
379
- const previousMd = path.join(outputDir, 'report.md');
380
- if (fs.existsSync(previousMd)) {
381
- const old = fs.readFileSync(previousMd, 'utf8');
382
- for (const chapter of [1, 2, 4, 5]) {
383
- const re = new RegExp(`(^## CHƯƠNG ${chapter}:.*?)(?=^## CHƯƠNG \\d+:|^## TÀI LIỆU THAM KHẢO|$(?![\\s\\S]))`, 'ms');
384
- const match = old.match(re);
385
- if (match && match[1].trim().split(/\r?\n/).length > 4)
386
- report.markdown = report.markdown.replace(re, match[1]);
387
- }
388
- }
196
+ }, grouping);
197
+ const approvalWarnings = usecaseSelection.approved_ids?.length
198
+ ? migrateLegacyApprovals(ledger, usecaseSelection.approved_ids, previousReportMd, usecaseFlows, path.join(outputDir, "approved"), manifest)
199
+ : [];
200
+ const catalogKeys = new Set(catalog.map((c) => ucKey(c.endpoint, c.controller, c.methodName)));
201
+ report.markdown = reconcileUseCases(ledger, usecaseFlows, report.markdown, manifest, outputDir, catalogKeys).markdown;
202
+ report.markdown = mergeTheorySections(ledger, report.markdown);
203
+ const repairedRegions = repairDuplicateManagedRegions(report.markdown);
204
+ report.markdown = repairedRegions.markdown;
205
+ if (repairedRegions.removed.length)
206
+ approvalWarnings.push(`Đã sửa vùng quản lý trùng trong report.md: ${repairedRegions.removed.join(", ")}`);
207
+ writeLedger(projectRoot, ledger);
389
208
  const markdownPath = path.join(outputDir, "report.md");
390
- const docxPath = path.join(outputDir, "report.docx");
209
+ const docxPath = path.join(outputDir, reportSource ? `report-updated-${randomUUID()}.docx` : "report.docx");
391
210
  const reviewNotesPath = path.join(outputDir, "review-notes.md");
392
211
  fs.writeFileSync(markdownPath, report.markdown, "utf8");
393
- if (!fs.existsSync(reviewNotesPath))
394
- fs.writeFileSync(reviewNotesPath, report.reviewNotes, "utf8");
212
+ fs.writeFileSync(reviewNotesPath, report.reviewNotes, "utf8");
395
213
  let docxWritten = false;
214
+ let docxResult;
396
215
  if (!usecaseSelection.disableDocx) {
397
- await renderMarkdownToDocx(report.markdown, docxPath, input.project_info);
216
+ docxResult = await renderMarkdownToDocx(report.markdown, docxPath, input.project_info, outputDir, { reportSource });
217
+ setDocxState(outputDir, "current", path.basename(docxPath));
398
218
  docxWritten = true;
399
219
  }
220
+ else
221
+ setDocxState(outputDir, "unavailable");
400
222
  timer.stop("report");
401
223
  // ── Evaluation report + dashboard ─────────────────────────────────────────
402
224
  const stereotypeCount = Object.entries(classResult.summary.by_type)
@@ -424,7 +246,6 @@ async function generateStagedReport(input, outputDir) {
424
246
  ...(architectureDiagramPath ? { architecture: toUrlPath(path.relative(outputDir, architectureDiagramPath)) } : {}),
425
247
  },
426
248
  });
427
- // Paths are relative; the run's staged absolute directory must not escape into published JSON.
428
249
  const evaluationReportPath = path.join(outputDir, "evaluation-report.json");
429
250
  const dashboardPath = path.join(outputDir, "dashboard.html");
430
251
  fs.writeFileSync(evaluationReportPath, JSON.stringify(evalReport, null, 2), "utf8");
@@ -442,12 +263,64 @@ async function generateStagedReport(input, outputDir) {
442
263
  f1Dependency: evalReport.accuracy.dependencyExtraction.f1,
443
264
  });
444
265
  generateDashboard(evalReport, dashboardPath);
266
+ const groupingAuditPath = path.join(outputDir, "uc-grouping-audit.json");
267
+ writeTextFile(groupingAuditPath, JSON.stringify(buildGroupingAudit(grouping, groupingSnapshot), null, 2));
268
+ // Publish all required outputs before contributing advisory examples.
269
+ if (grouping.mode === "reviewed-evidence") {
270
+ try {
271
+ const titles = new Map(catalog.map(item => [item.id, item.title]));
272
+ await learnHubGrouping(grouping.groups.map(group => ({ label: group.label,
273
+ ucTitles: group.members.map(member => member.title ?? titles.get(member.ucId) ?? member.ucId),
274
+ })), "");
275
+ }
276
+ catch (error) {
277
+ grouping.warnings.push(`Approved grouping examples could not be saved: ${error.message}`);
278
+ }
279
+ }
280
+ // Persist nonfatal learning diagnostics without turning learning into a failed run.
281
+ try {
282
+ writeTextFile(groupingAuditPath, JSON.stringify(buildGroupingAudit(grouping, groupingSnapshot), null, 2));
283
+ }
284
+ catch (error) {
285
+ grouping.warnings.push(`Grouping diagnostics could not be refreshed: ${error.message}`);
286
+ }
287
+ // Versioned history of tool-managed files; best-effort — a history failure must not fail the run.
288
+ try {
289
+ await recordVersion(projectRoot, outputDir, `run: ${usecaseFlows.length} UC`);
290
+ }
291
+ catch (err) {
292
+ console.error(`[archscribe] Cảnh báo: không ghi được lịch sử output: ${err.message}`);
293
+ }
445
294
  // Notify centralized dashboard server (non-blocking, silent fail).
446
295
  // Guarded by ARCHSCRIBE_RESEARCH_MODE so benchmark/thesis runs are unaffected.
447
- // Notifications and telemetry must follow publication, not the staged render.
296
+ if (process.env.ARCHSCRIBE_RESEARCH_MODE !== "1") {
297
+ notifyNewReport(input.ir.project.projectPath, evalReport).catch(() => {
298
+ // intentionally silent — dashboard is best-effort
299
+ });
300
+ // Fire-and-forget telemetry — this is the MCP tool path (Claude Code's
301
+ // scaffold_integration wires generate_report as the real entry point for
302
+ // most users), distinct from the CLI path's own call in cli/run.ts.
303
+ // Silently skipped when there's no license session or ARCHSCRIBE_TELEMETRY=0.
304
+ recordPipelineComplete({
305
+ ucCount: usecaseFlows.length,
306
+ diagramTypes: [
307
+ "usecase",
308
+ ...(classDiagramPath ? ["class"] : []),
309
+ ...(architectureDiagramPath ? ["architecture"] : []),
310
+ ...(activityPaths.length ? ["activity"] : []),
311
+ ...(sequencePaths.length ? ["sequence"] : []),
312
+ ],
313
+ processingMs: timer.toMetrics().totalTimeMs,
314
+ });
315
+ }
448
316
  return {
317
+ grouping_mode: grouping.mode,
318
+ grouping_warnings: grouping.warnings,
319
+ grouping_audit_path: groupingAuditPath,
449
320
  markdown_path: markdownPath,
450
321
  docx_path: docxWritten ? docxPath : undefined, // undefined for free tier — no file was written
322
+ source_path: docxResult?.source_path,
323
+ updated_regions: docxResult?.updated_regions,
451
324
  review_notes_path: reviewNotesPath,
452
325
  architecture_diagram_path: architectureDiagramPath, // undefined for free tier
453
326
  usecase_diagram_path: usecaseDiagramPath,
@@ -466,6 +339,7 @@ async function generateStagedReport(input, outputDir) {
466
339
  evaluation_report_path: evaluationReportPath,
467
340
  dashboard_path: dashboardPath,
468
341
  license: licenseCheck,
342
+ approval_warnings: approvalWarnings,
469
343
  };
470
344
  }
471
345
  /**
@@ -475,16 +349,58 @@ async function generateStagedReport(input, outputDir) {
475
349
  export async function renderReportDocx(input) {
476
350
  const mdPath = resolveWorkspacePath(input.markdown_path);
477
351
  const outPath = resolveWorkspacePath(input.output_path);
478
- // Watermark is injected at render time — immune to manual banner removal in .md
479
- const licCheck = await loadLicense([
480
- path.dirname(mdPath),
481
- path.dirname(path.dirname(mdPath)), // project root (one level above archscribe-output/)
482
- ]);
483
- let markdown = fs.readFileSync(mdPath, "utf8");
484
- if (licCheck.tier === "free") {
485
- markdown = TRIAL_BANNER + "\n\n" + markdown;
352
+ if (!input.project_path && input.report_source === undefined) {
353
+ throw new Error("project_path is required to establish report source policy; alternatively select report_source explicitly");
486
354
  }
487
- await renderMarkdownToDocx(markdown, outPath, input.project_info);
488
- return { docx_path: outPath };
355
+ const outputDir = path.dirname(mdPath);
356
+ const projectPath = input.project_path ? resolveWorkspacePath(input.project_path) : path.dirname(outputDir);
357
+ return withOutputMutation(projectPath, async () => {
358
+ const { resolveReportSource } = await import("../core/project-config.js");
359
+ const reportSource = input.project_path
360
+ ? resolveReportSource(resolveWorkspacePath(input.project_path), input.report_source)
361
+ : input.report_source === undefined ? undefined : resolveReportSource(path.dirname(mdPath), input.report_source);
362
+ // Watermark is injected at render time — immune to manual banner removal in .md
363
+ const licCheck = await loadLicense([
364
+ path.dirname(mdPath),
365
+ path.dirname(path.dirname(mdPath)), // project root (one level above archscribe-output/)
366
+ ]);
367
+ const selection = {};
368
+ applyLicenseLimits(licCheck, selection);
369
+ if (selection.disableDocx) {
370
+ if (path.basename(mdPath) === 'report.md')
371
+ setDocxState(outputDir, "unavailable");
372
+ throw new Error("DOCX export requires a license with exportDocx enabled");
373
+ }
374
+ let markdown = fs.readFileSync(mdPath, "utf8");
375
+ const repaired = repairDuplicateManagedRegions(markdown);
376
+ if (repaired.removed.length) {
377
+ markdown = repaired.markdown;
378
+ if (path.basename(mdPath) === "report.md")
379
+ fs.writeFileSync(mdPath, markdown, "utf8");
380
+ }
381
+ if (licCheck.tier === "free") {
382
+ markdown = TRIAL_BANNER + "\n\n" + markdown;
383
+ }
384
+ const managed = path.basename(mdPath) === 'report.md' && outPath === path.join(outputDir, 'report.docx');
385
+ if (reportSource && fs.existsSync(outPath))
386
+ throw new Error(`Destination already exists; source updates never overwrite files: ${outPath}`);
387
+ if (managed)
388
+ setDocxState(outputDir, "stale");
389
+ const temporary = `${outPath}.${randomUUID()}.tmp`;
390
+ try {
391
+ const result = await renderMarkdownToDocx(markdown, temporary, input.project_info, outputDir, { reportSource });
392
+ if (reportSource)
393
+ fs.linkSync(temporary, outPath);
394
+ else
395
+ fs.renameSync(temporary, outPath);
396
+ if (managed)
397
+ setDocxState(outputDir, "current");
398
+ return { ...result, docx_path: outPath };
399
+ }
400
+ finally {
401
+ if (fs.existsSync(temporary))
402
+ fs.unlinkSync(temporary);
403
+ }
404
+ });
489
405
  }
490
406
  //# sourceMappingURL=generate_report.js.map