@topogram/cli 0.3.63 → 0.3.64

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 (121) hide show
  1. package/package.json +1 -1
  2. package/src/adoption/plan.d.ts +6 -0
  3. package/src/adoption/reporting.d.ts +10 -0
  4. package/src/adoption/review-groups.d.ts +6 -0
  5. package/src/agent-brief.d.ts +3 -0
  6. package/src/agent-brief.js +495 -0
  7. package/src/agent-ops/query-builders.d.ts +26 -0
  8. package/src/archive/archive.d.ts +2 -0
  9. package/src/archive/compact.d.ts +1 -0
  10. package/src/archive/unarchive.d.ts +1 -0
  11. package/src/catalog.d.ts +10 -0
  12. package/src/catalog.js +62 -66
  13. package/src/cli/catalog-alias.d.ts +1 -0
  14. package/src/cli/command-parser.js +38 -0
  15. package/src/cli/command-parsers/core.js +102 -0
  16. package/src/cli/command-parsers/generator.js +39 -0
  17. package/src/cli/command-parsers/import.js +44 -0
  18. package/src/cli/command-parsers/legacy-workflow.js +21 -0
  19. package/src/cli/command-parsers/project.js +47 -0
  20. package/src/cli/command-parsers/sdlc.js +47 -0
  21. package/src/cli/command-parsers/shared.js +51 -0
  22. package/src/cli/command-parsers/template.js +48 -0
  23. package/src/cli/commands/agent.js +47 -0
  24. package/src/cli/commands/catalog.js +617 -0
  25. package/src/cli/commands/check.js +268 -0
  26. package/src/cli/commands/doctor.js +268 -0
  27. package/src/cli/commands/emit.js +149 -0
  28. package/src/cli/commands/generate.js +96 -0
  29. package/src/cli/commands/generator-policy.js +785 -0
  30. package/src/cli/commands/generator.js +443 -0
  31. package/src/cli/commands/import-runner.js +157 -0
  32. package/src/cli/commands/import.js +1734 -0
  33. package/src/cli/commands/inspect.js +55 -0
  34. package/src/cli/commands/new.js +94 -0
  35. package/src/cli/commands/package.js +815 -0
  36. package/src/cli/commands/query.js +1302 -0
  37. package/src/cli/commands/release-rollout.js +257 -0
  38. package/src/cli/commands/release-shared.js +528 -0
  39. package/src/cli/commands/release-status.js +429 -0
  40. package/src/cli/commands/release.js +107 -0
  41. package/src/cli/commands/sdlc.js +168 -0
  42. package/src/cli/commands/setup.js +76 -0
  43. package/src/cli/commands/source.js +291 -0
  44. package/src/cli/commands/template-runner.js +198 -0
  45. package/src/cli/commands/template.js +2145 -0
  46. package/src/cli/commands/trust.js +219 -0
  47. package/src/cli/commands/version.js +40 -0
  48. package/src/cli/commands/widget.js +168 -0
  49. package/src/cli/commands/workflow.js +63 -0
  50. package/src/cli/dispatcher.js +392 -0
  51. package/src/cli/help-dispatch.js +188 -0
  52. package/src/cli/help.js +296 -0
  53. package/src/cli/migration-guidance.js +59 -0
  54. package/src/cli/options.js +96 -0
  55. package/src/cli/output-safety.js +107 -0
  56. package/src/cli/path-normalization.js +29 -0
  57. package/src/cli.js +47 -11711
  58. package/src/example-implementation.d.ts +2 -0
  59. package/src/format.d.ts +1 -0
  60. package/src/generator/check.d.ts +1 -0
  61. package/src/generator/context/bundle.d.ts +1 -0
  62. package/src/generator/context/shared.d.ts +2 -0
  63. package/src/generator/native/parity-bundle.js +2 -1
  64. package/src/generator/surfaces/web/html-escape.js +22 -0
  65. package/src/generator/surfaces/web/react.js +10 -8
  66. package/src/generator/surfaces/web/sveltekit.js +7 -5
  67. package/src/generator/surfaces/web/vanilla.js +8 -4
  68. package/src/generator.d.ts +2 -0
  69. package/src/github-client.js +520 -0
  70. package/src/import/core/shared.js +20 -62
  71. package/src/import/extractors/api/flutter-dio.js +4 -8
  72. package/src/import/extractors/api/react-native-repository.js +4 -8
  73. package/src/import/index.d.ts +4 -0
  74. package/src/import/provenance.d.ts +4 -0
  75. package/src/new-project.js +100 -11
  76. package/src/npm-safety.js +79 -0
  77. package/src/parser.d.ts +1 -0
  78. package/src/path-helpers.d.ts +1 -0
  79. package/src/path-helpers.js +20 -0
  80. package/src/project-config.js +1 -0
  81. package/src/reconcile/docs.d.ts +8 -0
  82. package/src/reconcile/journeys.d.ts +1 -0
  83. package/src/resolver.d.ts +1 -0
  84. package/src/runtime-support.js +29 -0
  85. package/src/sdlc/adopt.d.ts +1 -0
  86. package/src/sdlc/check.d.ts +1 -0
  87. package/src/sdlc/explain.d.ts +1 -0
  88. package/src/sdlc/release.d.ts +1 -0
  89. package/src/sdlc/scaffold.d.ts +1 -0
  90. package/src/sdlc/transition.d.ts +1 -0
  91. package/src/text-helpers.d.ts +6 -0
  92. package/src/text-helpers.js +245 -0
  93. package/src/topogram-config.js +306 -0
  94. package/src/validator.d.ts +2 -0
  95. package/src/workflows/adoption/index.js +26 -0
  96. package/src/workflows/docs-generate.js +262 -0
  97. package/src/workflows/docs-scan.js +703 -0
  98. package/src/workflows/docs.js +15 -0
  99. package/src/workflows/import-app/api.js +799 -0
  100. package/src/workflows/import-app/db.js +538 -0
  101. package/src/workflows/import-app/index.js +30 -0
  102. package/src/workflows/import-app/shared.js +218 -0
  103. package/src/workflows/import-app/ui.js +443 -0
  104. package/src/workflows/import-app/workflow.js +159 -0
  105. package/src/workflows/reconcile/adoption-plan.js +742 -0
  106. package/src/workflows/reconcile/auth.js +692 -0
  107. package/src/workflows/reconcile/bundle-core.js +600 -0
  108. package/src/workflows/reconcile/bundle-shared.js +75 -0
  109. package/src/workflows/reconcile/candidate-model.js +477 -0
  110. package/src/workflows/reconcile/canonical-surface.js +264 -0
  111. package/src/workflows/reconcile/gap-report.js +333 -0
  112. package/src/workflows/reconcile/ids.js +6 -0
  113. package/src/workflows/reconcile/impacts.js +625 -0
  114. package/src/workflows/reconcile/index.js +7 -0
  115. package/src/workflows/reconcile/renderers.js +461 -0
  116. package/src/workflows/reconcile/summary.js +90 -0
  117. package/src/workflows/reconcile/workflow.js +309 -0
  118. package/src/workflows/shared.js +189 -0
  119. package/src/workflows/types.d.ts +93 -0
  120. package/src/workflows.d.ts +1 -0
  121. package/src/workflows.js +10 -7652
@@ -0,0 +1,692 @@
1
+ // @ts-check
2
+ import { confidenceRank } from "../docs.js";
3
+ import { inferCapabilityEntityId, normalizeOpenApiPath } from "../import-app/index.js";
4
+ import { idHintify } from "../../text-helpers.js";
5
+
6
+ /** @param {string} text @param {any[]} patterns @returns {any} */
7
+ export function authClaimPatternMatches(text, patterns = []) {
8
+ return patterns.some((/** @type {any} */ pattern) => pattern.test(text));
9
+ }
10
+
11
+ /** @param {any[]} entries @param {any[]} patterns @param {any} toText @returns {any} */
12
+ export function collectAuthClaimSignalMatches(entries, patterns, toText) {
13
+ return (entries || []).filter((/** @type {any} */ entry) => authClaimPatternMatches(toText(entry), patterns));
14
+ }
15
+
16
+ /** @param {string} value @returns {any} */
17
+ export function formatAuthClaimValueInline(value) {
18
+ return value == null ? "_dynamic_" : `\`${value}\``;
19
+ }
20
+
21
+ /** @param {WorkflowRecord} hint @returns {any} */
22
+ export function formatAuthClaimHintInline(hint) {
23
+ return `claim \`${hint.claim}\` = ${formatAuthClaimValueInline(hint.claim_value)} (${hint.confidence})`;
24
+ }
25
+
26
+ /** @param {WorkflowRecord} hint @returns {any} */
27
+ export function formatAuthPermissionHintInline(hint) {
28
+ return `permission \`${hint.permission}\` (${hint.confidence})`;
29
+ }
30
+
31
+ /** @param {WorkflowRecord} hint @returns {any} */
32
+ export function formatAuthOwnershipHintInline(hint) {
33
+ return `ownership \`${hint.ownership}\` field \`${hint.ownership_field}\` (${hint.confidence})`;
34
+ }
35
+
36
+ /** @param {WorkflowRecord} hint @returns {any} */
37
+ export function describeAuthPermissionWhyInferred(hint) {
38
+ /** @type {any[]} */
39
+ const signals = [];
40
+ if (hint?.evidence?.capability_hits) {
41
+ signals.push(`${hint.evidence.capability_hits} secured capability match${hint.evidence.capability_hits === 1 ? "" : "es"}`);
42
+ }
43
+ if (hint?.evidence?.route_hits) {
44
+ signals.push(`${hint.evidence.route_hits} route/resource match${hint.evidence.route_hits === 1 ? "" : "es"}`);
45
+ }
46
+ if (hint?.evidence?.doc_hits) {
47
+ signals.push(`${hint.evidence.doc_hits} imported doc or policy match${hint.evidence.doc_hits === 1 ? "" : "es"}`);
48
+ }
49
+ if (hint?.evidence?.provenance_hits) {
50
+ signals.push(`${hint.evidence.provenance_hits} auth middleware or policy hint${hint.evidence.provenance_hits === 1 ? "" : "s"}`);
51
+ }
52
+ if (signals.length === 0) {
53
+ return hint?.explanation || "Imported auth evidence suggests a permission rule may gate this surface.";
54
+ }
55
+ return `${hint?.explanation || "Imported auth evidence suggests a permission rule may gate this surface."} This inference is based on ${signals.join(", ")}.`;
56
+ }
57
+
58
+ /** @param {WorkflowRecord} hint @returns {any} */
59
+ export function buildAuthPermissionReviewGuidance(hint) {
60
+ return `Confirm whether permission \`${hint.permission}\` should gate the related auth-sensitive capabilities before promoting this bundle into canonical auth rules or UI visibility.`;
61
+ }
62
+
63
+ /** @param {WorkflowRecord} hint @returns {any} */
64
+ export function describeAuthClaimWhyInferred(hint) {
65
+ /** @type {any[]} */
66
+ const signals = [];
67
+ if (hint?.evidence?.capability_hits) {
68
+ signals.push(`${hint.evidence.capability_hits} secured capability match${hint.evidence.capability_hits === 1 ? "" : "es"}`);
69
+ }
70
+ if (hint?.evidence?.route_hits) {
71
+ signals.push(`${hint.evidence.route_hits} route match${hint.evidence.route_hits === 1 ? "" : "es"}`);
72
+ }
73
+ if (hint?.evidence?.participant_hits) {
74
+ signals.push(`${hint.evidence.participant_hits} participant match${hint.evidence.participant_hits === 1 ? "" : "es"}`);
75
+ }
76
+ if (hint?.evidence?.doc_hits) {
77
+ signals.push(`${hint.evidence.doc_hits} imported doc match${hint.evidence.doc_hits === 1 ? "" : "es"}`);
78
+ }
79
+ if (signals.length === 0) {
80
+ return hint?.explanation || "Imported auth-related evidence suggests this claim may matter here.";
81
+ }
82
+ return `${hint?.explanation || "Imported auth-related evidence suggests this claim may matter here."} This inference is based on ${signals.join(", ")}.`;
83
+ }
84
+
85
+ /** @param {WorkflowRecord} hint @returns {any} */
86
+ export function buildAuthClaimReviewGuidance(hint) {
87
+ const claimTarget = `claim \`${hint.claim}\` = ${formatAuthClaimValueInline(hint.claim_value)}`;
88
+ return `Confirm whether ${claimTarget} should gate the related auth-sensitive capabilities before promoting this bundle into canonical auth rules or UI visibility.`;
89
+ }
90
+
91
+ /** @param {WorkflowRecord} hint @returns {any} */
92
+ export function describeAuthOwnershipWhyInferred(hint) {
93
+ /** @type {any[]} */
94
+ const signals = [];
95
+ if (hint?.evidence?.field_hits) {
96
+ signals.push(`${hint.evidence.field_hits} ownership-style field match${hint.evidence.field_hits === 1 ? "" : "es"}`);
97
+ }
98
+ if (hint?.evidence?.capability_hits) {
99
+ signals.push(`${hint.evidence.capability_hits} secured lifecycle/detail capability match${hint.evidence.capability_hits === 1 ? "" : "es"}`);
100
+ }
101
+ if (hint?.evidence?.doc_hits) {
102
+ signals.push(`${hint.evidence.doc_hits} imported doc match${hint.evidence.doc_hits === 1 ? "" : "es"}`);
103
+ }
104
+ if (signals.length === 0) {
105
+ return hint?.explanation || "Imported field and auth evidence suggests ownership-based access control may matter here.";
106
+ }
107
+ return `${hint?.explanation || "Imported field and auth evidence suggests ownership-based access control may matter here."} This inference is based on ${signals.join(", ")}.`;
108
+ }
109
+
110
+ /** @param {WorkflowRecord} hint @returns {any} */
111
+ export function buildAuthOwnershipReviewGuidance(hint) {
112
+ return `Confirm whether field \`${hint.ownership_field}\` should drive \`${hint.ownership}\` access for the related auth-sensitive capabilities before promoting this bundle into canonical auth rules or UI visibility.`;
113
+ }
114
+
115
+ /** @param {WorkflowRecord} entry @returns {any} */
116
+ export function formatAuthRoleGuidanceInline(entry) {
117
+ return `role \`${entry.role_id}\` (${entry.confidence})`;
118
+ }
119
+
120
+ /** @param {WorkflowRecord} entry @returns {any} */
121
+ export function buildAuthRoleReviewGuidance(entry) {
122
+ if (entry.followup_action === "promote_role") {
123
+ return `Promote role \`${entry.role_id}\` first, then confirm it remains the primary participant for the related auth-sensitive capabilities before promoting linked auth changes from this bundle.`;
124
+ }
125
+ if (entry.followup_action === "link_role_to_docs") {
126
+ const docList = (entry.followup_doc_ids || []).length
127
+ ? ` docs ${(entry.followup_doc_ids || []).map((/** @type {any} */ item) => `\`${item}\``).join(", ")}`
128
+ : " the existing canonical docs";
129
+ return `Link role \`${entry.role_id}\` into${docList} before promoting more auth-sensitive changes from this bundle.`;
130
+ }
131
+ return `Confirm whether role \`${entry.role_id}\` should remain the primary participant for the related auth-sensitive capabilities before promoting role or auth changes from this bundle.`;
132
+ }
133
+
134
+ /** @param {WorkflowRecord} entry @returns {any} */
135
+ export function formatAuthRoleFollowupInline(entry) {
136
+ if (entry.followup_action === "promote_role") {
137
+ return "promote role";
138
+ }
139
+ if (entry.followup_action === "link_role_to_docs") {
140
+ return entry.followup_doc_ids?.length
141
+ ? `link role to docs ${(entry.followup_doc_ids || []).map((/** @type {any} */ item) => `\`${item}\``).join(", ")}`
142
+ : "link role to docs";
143
+ }
144
+ return "review only";
145
+ }
146
+
147
+ /** @param {any[]} items @returns {any} */
148
+ export function summarizeHintClosureState(items) {
149
+ const statuses = (items || []).map((/** @type {any} */ item) => item.status).filter(Boolean);
150
+ if (statuses.length === 0) {
151
+ return {
152
+ closure_state: "unresolved",
153
+ closure_reason: "No reviewed projection patch has been applied for this inferred auth hint yet."
154
+ };
155
+ }
156
+ if (statuses.every((/** @type {any} */ status) => status === "applied")) {
157
+ return {
158
+ closure_state: "adopted",
159
+ closure_reason: "All matching projection patch actions for this inferred auth hint have been applied."
160
+ };
161
+ }
162
+ if (statuses.every((/** @type {any} */ status) => ["applied", "approved", "skipped"].includes(status))) {
163
+ return {
164
+ closure_state: "deferred",
165
+ closure_reason: "This inferred auth hint has been reviewed or intentionally held back, but not every matching projection patch has been applied yet."
166
+ };
167
+ }
168
+ return {
169
+ closure_state: "unresolved",
170
+ closure_reason: "At least one matching projection patch for this inferred auth hint is still blocked on review or waiting to be applied."
171
+ };
172
+ }
173
+
174
+ /** @param {WorkflowRecord} bundle @param {any[]} planItems @returns {any} */
175
+ export function annotateBundleAuthHintClosures(bundle, planItems) {
176
+ const bundleItems = (planItems || []).filter((/** @type {any} */ item) => item.bundle === bundle.slug);
177
+ const annotatedPermissions = (bundle.authPermissionHints || []).map((/** @type {any} */ hint) => ({
178
+ ...hint,
179
+ ...summarizeHintClosureState(bundleItems.filter((/** @type {any} */ item) =>
180
+ item.suggested_action === "apply_projection_permission_patch" &&
181
+ item.permission === hint.permission
182
+ ))
183
+ }));
184
+ const annotatedClaims = (bundle.authClaimHints || []).map((/** @type {any} */ hint) => ({
185
+ ...hint,
186
+ ...summarizeHintClosureState(bundleItems.filter((/** @type {any} */ item) =>
187
+ item.suggested_action === "apply_projection_auth_patch" &&
188
+ item.claim === hint.claim &&
189
+ item.claim_value === (Object.prototype.hasOwnProperty.call(hint, "claim_value") ? hint.claim_value : null)
190
+ ))
191
+ }));
192
+ const annotatedOwnerships = (bundle.authOwnershipHints || []).map((/** @type {any} */ hint) => ({
193
+ ...hint,
194
+ ...summarizeHintClosureState(bundleItems.filter((/** @type {any} */ item) =>
195
+ item.suggested_action === "apply_projection_ownership_patch" &&
196
+ item.ownership === hint.ownership &&
197
+ item.ownership_field === hint.ownership_field
198
+ ))
199
+ }));
200
+ return {
201
+ ...bundle,
202
+ authPermissionHints: annotatedPermissions,
203
+ authClaimHints: annotatedClaims,
204
+ authOwnershipHints: annotatedOwnerships
205
+ };
206
+ }
207
+
208
+ /** @param {WorkflowRecord} bundle @returns {any} */
209
+ export function buildAuthHintClosureSummary(bundle) {
210
+ const hints = [
211
+ ...(bundle.authPermissionHints || []),
212
+ ...(bundle.authClaimHints || []),
213
+ ...(bundle.authOwnershipHints || [])
214
+ ];
215
+ const counts = hints.reduce(
216
+ (/** @type {any} */ acc, /** @type {any} */ hint) => {
217
+ const state = hint.closure_state || "unresolved";
218
+ if (state === "adopted") {
219
+ acc.adopted += 1;
220
+ } else if (state === "deferred") {
221
+ acc.deferred += 1;
222
+ } else {
223
+ acc.unresolved += 1;
224
+ }
225
+ return acc;
226
+ },
227
+ { total: hints.length, adopted: 0, deferred: 0, unresolved: 0 }
228
+ );
229
+ if (counts.total === 0) {
230
+ return {
231
+ status: "no_auth_hints",
232
+ label: "no auth hints",
233
+ reason: "This bundle does not currently carry inferred permission, claim, or ownership hints.",
234
+ ...counts
235
+ };
236
+ }
237
+ if (counts.unresolved === 0 && counts.deferred === 0) {
238
+ return {
239
+ status: "mostly_closed",
240
+ label: "mostly closed",
241
+ reason: "All inferred auth hints for this bundle have been adopted into canonical projection rules.",
242
+ ...counts
243
+ };
244
+ }
245
+ if (counts.unresolved === 0) {
246
+ return {
247
+ status: "partially_closed",
248
+ label: "partially closed",
249
+ reason: "Every inferred auth hint has been reviewed, but at least one is still intentionally deferred instead of adopted.",
250
+ ...counts
251
+ };
252
+ }
253
+ return {
254
+ status: "high_risk",
255
+ label: "high risk",
256
+ reason: "At least one inferred auth hint is still unresolved, so the recovered auth story for this bundle is not closed yet.",
257
+ ...counts
258
+ };
259
+ }
260
+
261
+ /** @param {CandidateBundle} bundle @returns {any} */
262
+ export function inferBundleAuthRoleGuidance(bundle) {
263
+ const roles = bundle.roles || [];
264
+ if (roles.length === 0) {
265
+ return [];
266
+ }
267
+ const authSensitiveCapabilities = new Set([
268
+ ...(bundle.authPermissionHints || []).flatMap((/** @type {any} */ hint) => hint.related_capabilities || []),
269
+ ...(bundle.authClaimHints || []).flatMap((/** @type {any} */ hint) => hint.related_capabilities || []),
270
+ ...(bundle.authOwnershipHints || []).flatMap((/** @type {any} */ hint) => hint.related_capabilities || [])
271
+ ]);
272
+ const claimPreferredRoles = new Set(
273
+ (bundle.authClaimHints || []).flatMap((/** @type {any} */ hint) => {
274
+ if (hint.claim === "reviewer") return ["role_reviewer"];
275
+ if (hint.claim === "tenant") return ["role_admin", "role_manager"];
276
+ return [];
277
+ })
278
+ );
279
+ const ownershipPreferredRoles = new Set(
280
+ (bundle.authOwnershipHints || []).flatMap((/** @type {any} */ hint) => {
281
+ if (hint.ownership_field === "owner_id") return ["role_owner"];
282
+ if (hint.ownership_field === "assignee_id") return ["role_assignee"];
283
+ return [];
284
+ })
285
+ );
286
+
287
+ return roles
288
+ .map((/** @type {any} */ role) => {
289
+ const relatedCapabilities = [...new Set((role.related_capabilities || []).filter((/** @type {any} */ capabilityId) => authSensitiveCapabilities.has(capabilityId)))];
290
+ const directRoleMatch = claimPreferredRoles.has(role.id_hint) || ownershipPreferredRoles.has(role.id_hint);
291
+ if (!directRoleMatch && relatedCapabilities.length === 0) {
292
+ return null;
293
+ }
294
+ /** @type {any[]} */
295
+ const reasonParts = [];
296
+ if (directRoleMatch) {
297
+ reasonParts.push("role naming lines up with inferred auth semantics");
298
+ }
299
+ if (relatedCapabilities.length > 0) {
300
+ reasonParts.push(`${relatedCapabilities.length} related auth-sensitive capability match${relatedCapabilities.length === 1 ? "" : "es"}`);
301
+ }
302
+ return {
303
+ role_id: role.id_hint,
304
+ confidence: role.confidence || "low",
305
+ related_capabilities: relatedCapabilities.sort(),
306
+ related_docs: [...new Set(role.related_docs || [])].sort(),
307
+ why_inferred: `Imported role evidence suggests \`${role.id_hint}\` is likely part of the recovered auth story because ${reasonParts.join(" and ")}.`,
308
+ review_guidance: buildAuthRoleReviewGuidance({ role_id: role.id_hint })
309
+ };
310
+ })
311
+ .filter(Boolean)
312
+ .sort((/** @type {any} */ a, /** @type {any} */ b) =>
313
+ confidenceRank(b.confidence) - confidenceRank(a.confidence) ||
314
+ (b.related_capabilities.length - a.related_capabilities.length) ||
315
+ a.role_id.localeCompare(b.role_id)
316
+ );
317
+ }
318
+
319
+ /** @param {CandidateBundle} bundle @returns {any} */
320
+ export function classifyBundleAuthRoleGuidance(bundle) {
321
+ return (bundle.authRoleGuidance || []).map((/** @type {any} */ entry) => {
322
+ const matchingDocLinks = (bundle.docLinkSuggestions || [])
323
+ .filter((/** @type {any} */ item) => (item.add_related_roles || []).includes(entry.role_id));
324
+ const hasRolePromotion = (bundle.adoptionPlan || [])
325
+ .some((/** @type {any} */ step) => step.action === "promote_role" && step.item === entry.role_id);
326
+ const followupDocIds = matchingDocLinks.map((/** @type {any} */ item) => item.doc_id).sort();
327
+ const followupPatchPaths = matchingDocLinks.map((/** @type {any} */ item) => item.patch_rel_path).filter(Boolean).sort();
328
+ let followupAction = "review_only";
329
+ let followupReason = "Role evidence is still thin enough that this should stay review-only until the participant story is clearer.";
330
+ if (matchingDocLinks.length > 0 && entry.related_capabilities.length === 0) {
331
+ followupAction = "link_role_to_docs";
332
+ followupReason = "Imported docs already exist for this participant signal, and the safer next step is to link the role into those docs before promoting more auth-sensitive changes.";
333
+ } else if (hasRolePromotion && (confidenceRank(entry.confidence) >= confidenceRank("medium") || entry.related_capabilities.length > 0)) {
334
+ followupAction = "promote_role";
335
+ followupReason = "Recovered role evidence is strong enough to promote this role candidate before adopting linked auth-sensitive changes.";
336
+ } else if (matchingDocLinks.length > 0) {
337
+ followupAction = "link_role_to_docs";
338
+ followupReason = "This role already has useful canonical doc anchors, so linking the participant context into docs is the safest next step.";
339
+ }
340
+ const classified = {
341
+ ...entry,
342
+ followup_action: followupAction,
343
+ followup_label: formatAuthRoleFollowupInline({
344
+ ...entry,
345
+ followup_action: followupAction,
346
+ followup_doc_ids: followupDocIds
347
+ }),
348
+ followup_reason: followupReason,
349
+ followup_doc_ids: followupDocIds,
350
+ followup_patch_paths: followupPatchPaths
351
+ };
352
+ return {
353
+ ...classified,
354
+ review_guidance: buildAuthRoleReviewGuidance(classified)
355
+ };
356
+ });
357
+ }
358
+
359
+ /** @param {any[]} docLinkSuggestions @param {any} authRoleGuidance @returns {any} */
360
+ export function annotateDocLinkSuggestionsWithAuthRoleGuidance(docLinkSuggestions, authRoleGuidance) {
361
+ const authRoleMap = new Map((authRoleGuidance || []).map((/** @type {any} */ entry) => [entry.role_id, entry]));
362
+ return (docLinkSuggestions || []).map((/** @type {any} */ item) => {
363
+ const authRoleFollowups = [...new Set(item.add_related_roles || [])]
364
+ .map((/** @type {any} */ roleId) => authRoleMap.get(roleId))
365
+ .filter(Boolean)
366
+ .map((/** @type {any} */ entry) => ({
367
+ role_id: entry.role_id,
368
+ followup_action: entry.followup_action,
369
+ followup_label: entry.followup_label
370
+ }));
371
+ return authRoleFollowups.length > 0
372
+ ? { ...item, auth_role_followups: authRoleFollowups }
373
+ : item;
374
+ });
375
+ }
376
+
377
+ /** @param {WorkflowRecord} capability @returns {any} */
378
+ export function permissionResourceStemForCapability(capability) {
379
+ const endpointPath = normalizeOpenApiPath(capability?.endpoint?.path || "");
380
+ const pathSegments = endpointPath
381
+ .split("/")
382
+ .filter(Boolean)
383
+ .filter((/** @type {any} */ segment) => segment !== "{}");
384
+ const firstPathSegment = idHintify(pathSegments[0] || "");
385
+ if (firstPathSegment) {
386
+ return firstPathSegment;
387
+ }
388
+ const entityId = String(capability?.entity_id || inferCapabilityEntityId(capability) || "").replace(/^entity_/, "");
389
+ if (!entityId) {
390
+ return "resource";
391
+ }
392
+ return entityId.endsWith("s") ? entityId : `${entityId}s`;
393
+ }
394
+
395
+ /** @param {string} resource @returns {any} */
396
+ export function singularizePermissionResource(resource) {
397
+ return String(resource || "").endsWith("s") ? String(resource).slice(0, -1) : String(resource || "");
398
+ }
399
+
400
+ /** @param {WorkflowRecord} capability @param {string} resourceStem @returns {any} */
401
+ export function inferPermissionActionForCapability(capability, resourceStem) {
402
+ const capabilityId = String(capability?.id_hint || "");
403
+ const capabilityMatch = capabilityId.match(/^cap_([^_]+)_(.+)$/);
404
+ const resourceSingular = singularizePermissionResource(resourceStem);
405
+ const resourcePrefixes = [resourceStem, resourceSingular].filter(Boolean);
406
+ if (!capabilityMatch) {
407
+ const method = String(capability?.endpoint?.method || "").toUpperCase();
408
+ if (method === "GET") return "read";
409
+ if (method === "POST") return "create";
410
+ if (method === "PATCH" || method === "PUT") return "update";
411
+ if (method === "DELETE") return "delete";
412
+ return null;
413
+ }
414
+ const [, verb, remainder] = capabilityMatch;
415
+ if (verb === "get" || verb === "list") {
416
+ return "read";
417
+ }
418
+ let suffix = remainder;
419
+ for (const prefix of resourcePrefixes) {
420
+ if (suffix === prefix) {
421
+ suffix = "";
422
+ break;
423
+ }
424
+ if (suffix.startsWith(`${prefix}_`)) {
425
+ suffix = suffix.slice(prefix.length + 1);
426
+ break;
427
+ }
428
+ }
429
+ if (!suffix) {
430
+ return verb;
431
+ }
432
+ if (verb === "request") {
433
+ return `request_${suffix}`;
434
+ }
435
+ return ["create", "update", "delete"].includes(verb) ? verb : `${verb}${suffix ? `_${suffix}` : ""}`;
436
+ }
437
+
438
+ /** @param {CandidateBundle} bundle @returns {any} */
439
+ export function inferBundleAuthPermissionHints(bundle) {
440
+ const securedCapabilities = (bundle.capabilities || []).filter((/** @type {any} */ entry) => entry.auth_hint === "secured");
441
+ if (securedCapabilities.length === 0) {
442
+ return [];
443
+ }
444
+
445
+ const docEntries = bundle.docs || [];
446
+ const grouped = new Map();
447
+ for (const capability of securedCapabilities) {
448
+ const resourceStem = permissionResourceStemForCapability(capability);
449
+ const action = inferPermissionActionForCapability(capability, resourceStem);
450
+ if (!resourceStem || !action) {
451
+ continue;
452
+ }
453
+ const permission = `${resourceStem}.${action}`;
454
+ const docPatterns = [
455
+ new RegExp(`\\b${permission.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "i"),
456
+ new RegExp(`\\b${resourceStem.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "i"),
457
+ new RegExp(`\\b${action.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "i")
458
+ ];
459
+ const docMatches = collectAuthClaimSignalMatches(
460
+ docEntries,
461
+ docPatterns,
462
+ (/** @type {any} */ entry) => [entry.id, entry.title, ...(entry.provenance || []), entry.body || ""].filter(Boolean).join(" ")
463
+ );
464
+ const provenanceText = [capability.id_hint, capability.label, capability.endpoint?.path, ...(capability.provenance || [])]
465
+ .filter(Boolean)
466
+ .join(" ");
467
+ const provenanceHits = /\b(permission|policy|scope|authorize|authoriz|allow|guard|access)\b/i.test(provenanceText) ? 1 : 0;
468
+ const existing = grouped.get(permission) || {
469
+ permission,
470
+ confidence: "low",
471
+ review_required: true,
472
+ related_capabilities: [],
473
+ evidence: {
474
+ capability_hits: 0,
475
+ route_hits: 0,
476
+ doc_hits: 0,
477
+ provenance_hits: 0
478
+ },
479
+ explanation: "Secured capability naming and imported route evidence suggest this permission may gate the recovered surface."
480
+ };
481
+ existing.related_capabilities.push(capability.id_hint);
482
+ existing.evidence.capability_hits += 1;
483
+ existing.evidence.route_hits += capability.endpoint?.path ? 1 : 0;
484
+ existing.evidence.doc_hits += docMatches.length;
485
+ existing.evidence.provenance_hits += provenanceHits;
486
+ const confidence = provenanceHits > 0 || docMatches.length > 0 || capability.endpoint?.path ? "medium" : "low";
487
+ if (confidenceRank(confidence) > confidenceRank(existing.confidence)) {
488
+ existing.confidence = confidence;
489
+ }
490
+ grouped.set(permission, existing);
491
+ }
492
+
493
+ return [...grouped.values()]
494
+ .map((/** @type {any} */ entry) => ({
495
+ ...entry,
496
+ related_capabilities: [...new Set(entry.related_capabilities)].sort(),
497
+ why_inferred: describeAuthPermissionWhyInferred(entry),
498
+ review_guidance: buildAuthPermissionReviewGuidance(entry)
499
+ }))
500
+ .sort((/** @type {any} */ a, /** @type {any} */ b) => confidenceRank(b.confidence) - confidenceRank(a.confidence) || a.permission.localeCompare(b.permission));
501
+ }
502
+
503
+ /** @param {CandidateBundle} bundle @returns {any} */
504
+ export function inferBundleAuthClaimHints(bundle) {
505
+ const securedCapabilities = (bundle.capabilities || []).filter((/** @type {any} */ entry) => entry.auth_hint === "secured");
506
+ if (securedCapabilities.length === 0) {
507
+ return [];
508
+ }
509
+
510
+ const candidates = [
511
+ {
512
+ claim: "reviewer",
513
+ claim_value: "true",
514
+ confidenceFloor: "medium",
515
+ capabilityPatterns: [/\breviewer\b/i, /\breview\b/i, /\bapprove\b/i, /\breject\b/i, /\brevision\b/i],
516
+ routePatterns: [/\breviewer\b/i, /\breview\b/i, /\bapprove\b/i, /\breject\b/i, /\brevision\b/i],
517
+ participantPatterns: [/\breviewer\b/i],
518
+ docPatterns: [/\breviewer\b/i, /\breview\b/i, /\bapprove\b/i, /\breject\b/i, /\brevision\b/i],
519
+ explanation: "Review-oriented capability, route, or participant evidence suggests a reviewer claim may gate these actions."
520
+ },
521
+ {
522
+ claim: "tenant",
523
+ claim_value: null,
524
+ confidenceFloor: "low",
525
+ capabilityPatterns: [/\btenant\b/i, /\bworkspace\b/i, /\borganization\b/i, /\borg\b/i],
526
+ routePatterns: [/\btenant\b/i, /\bworkspace\b/i, /\borganization\b/i, /\borg\b/i],
527
+ participantPatterns: [],
528
+ docPatterns: [/\btenant\b/i, /\bworkspace\b/i, /\borganization\b/i, /\borg\b/i],
529
+ explanation: "Tenant or workspace naming suggests a request-scoped claim may be part of access control here."
530
+ }
531
+ ];
532
+
533
+ const routeEntries = [...(bundle.uiRoutes || []), ...securedCapabilities];
534
+ const participantEntries = [...(bundle.actors || []), ...(bundle.roles || [])];
535
+ const docEntries = bundle.docs || [];
536
+
537
+ return candidates
538
+ .map((/** @type {any} */ candidate) => {
539
+ const capabilityMatches = collectAuthClaimSignalMatches(
540
+ securedCapabilities,
541
+ candidate.capabilityPatterns,
542
+ (/** @type {any} */ entry) => [entry.id_hint, entry.label, entry.endpoint?.path, ...(entry.provenance || [])].filter(Boolean).join(" ")
543
+ );
544
+ const routeMatches = collectAuthClaimSignalMatches(
545
+ routeEntries,
546
+ candidate.routePatterns,
547
+ (/** @type {any} */ entry) => [entry.path, entry.route_path, entry.id_hint, entry.label, ...(entry.provenance || [])].filter(Boolean).join(" ")
548
+ );
549
+ const participantMatches = collectAuthClaimSignalMatches(
550
+ participantEntries,
551
+ candidate.participantPatterns,
552
+ (/** @type {any} */ entry) => [entry.id_hint, entry.label, ...(entry.provenance || [])].filter(Boolean).join(" ")
553
+ );
554
+ const docMatches = collectAuthClaimSignalMatches(
555
+ docEntries,
556
+ candidate.docPatterns,
557
+ (/** @type {any} */ entry) => [entry.id, entry.title, ...(entry.provenance || []), entry.body || ""].filter(Boolean).join(" ")
558
+ );
559
+ const signalCount = [
560
+ capabilityMatches.length > 0,
561
+ routeMatches.length > 0,
562
+ participantMatches.length > 0,
563
+ docMatches.length > 0
564
+ ].filter(Boolean).length;
565
+
566
+ if (signalCount === 0) {
567
+ return null;
568
+ }
569
+ if (candidate.claim === "reviewer" && signalCount < 2) {
570
+ return null;
571
+ }
572
+
573
+ const confidence =
574
+ participantMatches.length > 0 || (capabilityMatches.length > 0 && routeMatches.length > 0)
575
+ ? candidate.confidenceFloor
576
+ : "low";
577
+
578
+ return {
579
+ claim: candidate.claim,
580
+ claim_value: candidate.claim_value,
581
+ confidence,
582
+ review_required: true,
583
+ related_capabilities: [...new Set(capabilityMatches.map((/** @type {any} */ entry) => entry.id_hint))].sort(),
584
+ evidence: {
585
+ capability_hits: capabilityMatches.length,
586
+ route_hits: routeMatches.length,
587
+ participant_hits: participantMatches.length,
588
+ doc_hits: docMatches.length
589
+ },
590
+ explanation: candidate.explanation,
591
+ why_inferred: describeAuthClaimWhyInferred({
592
+ claim: candidate.claim,
593
+ claim_value: candidate.claim_value,
594
+ explanation: candidate.explanation,
595
+ evidence: {
596
+ capability_hits: capabilityMatches.length,
597
+ route_hits: routeMatches.length,
598
+ participant_hits: participantMatches.length,
599
+ doc_hits: docMatches.length
600
+ }
601
+ }),
602
+ review_guidance: buildAuthClaimReviewGuidance({
603
+ claim: candidate.claim,
604
+ claim_value: candidate.claim_value
605
+ })
606
+ };
607
+ })
608
+ .filter(Boolean)
609
+ .sort((/** @type {any} */ a, /** @type {any} */ b) => confidenceRank(b.confidence) - confidenceRank(a.confidence) || a.claim.localeCompare(b.claim));
610
+ }
611
+
612
+ /** @param {CandidateBundle} bundle @returns {any} */
613
+ export function inferBundleAuthOwnershipHints(bundle) {
614
+ const securedCapabilities = (bundle.capabilities || []).filter((/** @type {any} */ entry) => entry.auth_hint === "secured");
615
+ if (securedCapabilities.length === 0) {
616
+ return [];
617
+ }
618
+
619
+ const entityFieldEntries = ((bundle.importedFieldEvidence || []).length > 0 ? bundle.importedFieldEvidence : (bundle.entities || []).flatMap((/** @type {any} */ entity) => (entity.fields || []).map((/** @type {any} */ field) => ({
620
+ entity_id: entity.id_hint,
621
+ name: field.name,
622
+ field_type: field.field_type,
623
+ required: field.required
624
+ }))));
625
+ const docEntries = bundle.docs || [];
626
+ const ownershipScopedCapabilities = securedCapabilities.filter((/** @type {any} */ entry) =>
627
+ /^cap_(get|update|close|complete|archive|delete|submit|request|approve|reject)_/.test(entry.id_hint || "")
628
+ );
629
+ if (entityFieldEntries.length === 0 || ownershipScopedCapabilities.length === 0) {
630
+ return [];
631
+ }
632
+
633
+ const candidates = [
634
+ {
635
+ ownership: "owner_or_admin",
636
+ ownership_field: "owner_id",
637
+ confidenceFloor: "medium",
638
+ fieldPatterns: [/^owner_id$/i, /^author_id$/i],
639
+ docPatterns: [/\bowner\b/i, /\bauthor\b/i],
640
+ explanation: "Ownership-style field naming suggests this bundle may authorize detail or lifecycle actions based on resource ownership."
641
+ },
642
+ {
643
+ ownership: "owner_or_admin",
644
+ ownership_field: "assignee_id",
645
+ confidenceFloor: "medium",
646
+ fieldPatterns: [/^assignee_id$/i],
647
+ docPatterns: [/\bassignee\b/i, /\bassigned\b/i],
648
+ explanation: "Assignment-style field naming suggests this bundle may authorize detail or lifecycle actions based on the assigned user."
649
+ }
650
+ ];
651
+
652
+ return candidates
653
+ .map((/** @type {any} */ candidate) => {
654
+ const fieldMatches = entityFieldEntries.filter((/** @type {any} */ entry) => candidate.fieldPatterns.some((/** @type {any} */ pattern) => pattern.test(entry.name || "")));
655
+ const docMatches = collectAuthClaimSignalMatches(
656
+ docEntries,
657
+ candidate.docPatterns,
658
+ (/** @type {any} */ entry) => [entry.id, entry.title, ...(entry.provenance || []), entry.body || ""].filter(Boolean).join(" ")
659
+ );
660
+ if (fieldMatches.length === 0) {
661
+ return null;
662
+ }
663
+ const relatedCapabilities = ownershipScopedCapabilities.map((/** @type {any} */ entry) => entry.id_hint).sort();
664
+ const evidence = {
665
+ field_hits: fieldMatches.length,
666
+ capability_hits: relatedCapabilities.length,
667
+ doc_hits: docMatches.length
668
+ };
669
+ return {
670
+ ownership: candidate.ownership,
671
+ ownership_field: candidate.ownership_field,
672
+ confidence: candidate.confidenceFloor,
673
+ review_required: true,
674
+ related_capabilities: relatedCapabilities,
675
+ related_entities: [...new Set(fieldMatches.map((/** @type {any} */ entry) => entry.entity_id))].sort(),
676
+ evidence,
677
+ explanation: candidate.explanation,
678
+ why_inferred: describeAuthOwnershipWhyInferred({
679
+ ownership: candidate.ownership,
680
+ ownership_field: candidate.ownership_field,
681
+ explanation: candidate.explanation,
682
+ evidence
683
+ }),
684
+ review_guidance: buildAuthOwnershipReviewGuidance({
685
+ ownership: candidate.ownership,
686
+ ownership_field: candidate.ownership_field
687
+ })
688
+ };
689
+ })
690
+ .filter(Boolean)
691
+ .sort((/** @type {any} */ a, /** @type {any} */ b) => confidenceRank(b.confidence) - confidenceRank(a.confidence) || a.ownership_field.localeCompare(b.ownership_field));
692
+ }