@shiftleftpt/sbd-toe-mcp 0.20.0 → 0.21.0

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 (53) hide show
  1. package/README.md +2 -2
  2. package/dist/index.js +107 -266
  3. package/dist/index.js.map +1 -1
  4. package/dist/resources/sbd-toe-resources.js +1 -1
  5. package/dist/resources/sbd-toe-resources.js.map +1 -1
  6. package/dist/serving/adjacency.d.ts +68 -0
  7. package/dist/serving/adjacency.js +127 -0
  8. package/dist/serving/adjacency.js.map +1 -0
  9. package/dist/serving/affordances.js +4 -5
  10. package/dist/serving/affordances.js.map +1 -1
  11. package/dist/serving/agent-guide.js +5 -3
  12. package/dist/serving/agent-guide.js.map +1 -1
  13. package/dist/serving/behaviour-notes.d.ts +2 -2
  14. package/dist/serving/behaviour-notes.js +2 -8
  15. package/dist/serving/behaviour-notes.js.map +1 -1
  16. package/dist/serving/notes.d.ts +41 -0
  17. package/dist/serving/notes.js +43 -0
  18. package/dist/serving/notes.js.map +1 -0
  19. package/dist/serving/payload-ceilings.d.ts +73 -11
  20. package/dist/serving/payload-ceilings.js +85 -24
  21. package/dist/serving/payload-ceilings.js.map +1 -1
  22. package/dist/serving/response-shaping.d.ts +10 -0
  23. package/dist/serving/response-shaping.js +26 -0
  24. package/dist/serving/response-shaping.js.map +1 -1
  25. package/dist/serving/server-surface.d.ts +10 -0
  26. package/dist/serving/server-surface.js +14 -2
  27. package/dist/serving/server-surface.js.map +1 -1
  28. package/dist/serving/surface-history.d.ts +118 -0
  29. package/dist/serving/surface-history.js +119 -0
  30. package/dist/serving/surface-history.js.map +1 -0
  31. package/dist/tools/assess-implementation.d.ts +9 -0
  32. package/dist/tools/assess-implementation.js +7 -1
  33. package/dist/tools/assess-implementation.js.map +1 -1
  34. package/dist/tools/get-guide-by-role.d.ts +40 -0
  35. package/dist/tools/get-guide-by-role.js +158 -4
  36. package/dist/tools/get-guide-by-role.js.map +1 -1
  37. package/dist/tools/get-macro-processes.js +18 -8
  38. package/dist/tools/get-macro-processes.js.map +1 -1
  39. package/dist/tools/get-threat-landscape.js +11 -5
  40. package/dist/tools/get-threat-landscape.js.map +1 -1
  41. package/dist/tools/ontology-loader.d.ts +7 -0
  42. package/dist/tools/ontology-loader.js +2 -0
  43. package/dist/tools/ontology-loader.js.map +1 -1
  44. package/dist/tools/prepare-codegen-context.d.ts +339 -276
  45. package/dist/tools/prepare-codegen-context.js +454 -530
  46. package/dist/tools/prepare-codegen-context.js.map +1 -1
  47. package/dist/tools/resolve-entities.js +8 -4
  48. package/dist/tools/resolve-entities.js.map +1 -1
  49. package/dist/tools/select-requirements.d.ts +2 -1
  50. package/dist/tools/select-requirements.js +23 -8
  51. package/dist/tools/select-requirements.js.map +1 -1
  52. package/package.json +1 -1
  53. package/prompts/sbd-toe-grounded-codegen.md +11 -11
@@ -13,7 +13,7 @@
13
13
  * 3. Resolution: pull deterministic data from the three published sources
14
14
  * (runtime v0, runtime v1, overlay).
15
15
  * 4. Output: produce `activated_scope`, `g2_context`, `manual_grounding`,
16
- * `regulatory_overlay`, `citation_map`, `completeness_report`,
16
+ * `regulatory_overlay`, `citations` (0.21 §3: invertido em todos os níveis), `completeness_report`,
17
17
  * `llm_codegen_instructions` and `security_rationale_template`.
18
18
  *
19
19
  * Strict rules:
@@ -33,39 +33,13 @@ import { servedKgReleaseTag, servingServerVersion } from "../version-info.js";
33
33
  import { expandQueryWithAliases } from "../backend/semantic-index-gateway.js";
34
34
  import { requirementCategoryOf } from "../serving/requirement-id.js";
35
35
  import { prepareCodegenAffordances } from "../serving/affordances.js";
36
+ import { estimateSize } from "../serving/response-shaping.js";
37
+ import { PAYLOAD_PROMISE_TK as LEVEL_ENVELOPE_TK } from "../serving/payload-ceilings.js";
38
+ import { buildDeclaredAdjacency, declaredAdjacencyDetail } from "../serving/adjacency.js";
39
+ import { NOTES, NOTES_HEADER } from "../serving/notes.js";
40
+ import { buildActivationVocabulary } from "../serving/activation-vocabulary.js";
36
41
  import { runSelectionWithActivation, normalizeDeclaredTechnologies, stackTokensFromVocabulary } from "../serving/selection.js";
37
42
  import { REQUIREMENT_CEILING_BY_DETAIL, COST_PER_REQ_TK, BASE_TK, PAYLOAD_PROMISE_TK, projectedCostTk } from "../serving/payload-ceilings.js";
38
- const EVIDENCE_PATTERN_CAP = 25;
39
- /**
40
- * v2 token diet, s3 — evidence-pattern cap applied at `detail: "standard" |
41
- * "minimal"` ON TOP of the classic cap: the dieted list is the deterministic
42
- * PREFIX (relevance_score desc, id asc — the exact order the core already
43
- * emits) of the classic top-{@link EVIDENCE_PATTERN_CAP} list. Never silent:
44
- * `completeness_report` reports total/returned/capped and, when anything was
45
- * cut, `evidence_patterns_rest` says how to retrieve the rest (same tool,
46
- * `detail: "full"`).
47
- */
48
- const STANDARD_EVIDENCE_PATTERN_CAP = 10;
49
- /**
50
- * v2 token diet, s3b (revised per the 2026-07-05 operator ADENDA in
51
- * agentic/planeado/v2-token-diet/EPIC.md — no top-N, no subsetting of the
52
- * activated set): at `detail: "minimal"` the evidence cap tightens 10→5 with
53
- * the SAME s3 mechanism (deterministic prefix, never-silent counts +
54
- * executable rest-reference). This cap — together with the minimal
55
- * `manual_grounding` form — is the ONLY divergence from `standard`; the
56
- * activated scope (requirements/controls/slices/entities, with the verbatim
57
- * published descriptions) stays COMPLETE and byte-identical to `standard`.
58
- */
59
- const MINIMAL_EVIDENCE_PATTERN_CAP = 5;
60
- /**
61
- * v2 token diet, s3c (operator ADENDA 2026-07-05, reactivated same day): at
62
- * `detail: "ultrathin"` NO evidence pattern goes inline (cap 0) — the SAME s3
63
- * never-silent mechanism still applies in full: `completeness_report` reports
64
- * total/returned(=0)/capped(=total) and `evidence_patterns_rest` is the
65
- * executable reference to the CHEAPEST level that returns them inline
66
- * (detail="minimal" ⇒ top-5; "standard" ⇒ 10; "full" ⇒ classic 25).
67
- */
68
- const ULTRATHIN_EVIDENCE_PATTERN_CAP = 0;
69
43
  /**
70
44
  * Section → source map for the dieted encoding: each list is
71
45
  * source-homogeneous BY CONSTRUCTION (the projection types hardcode a single
@@ -85,7 +59,6 @@ const PROVENANCE_SOURCES = {
85
59
  "g2_context.practices": "runtime_v1",
86
60
  "g2_context.artifacts": "runtime_v1",
87
61
  "g2_context.relations": "runtime_v1",
88
- "g2_context.evidence_patterns": "runtime_v0",
89
62
  "manual_grounding.groups": "runtime_v1",
90
63
  "regulatory_overlay.frameworks": "overlay",
91
64
  "regulatory_overlay.obligations": "overlay",
@@ -93,51 +66,21 @@ const PROVENANCE_SOURCES = {
93
66
  "regulatory_overlay.playbooks": "overlay"
94
67
  };
95
68
  /**
96
- * Inline legend for `standard`/`minimal` (s3: slim pointer — the full legend,
97
- * including the section→source table and every derivation rule of the dieted
98
- * encoding, lives in the `sbd://toe/codegen-instructions/{mode}` resource,
99
- * section `detail_encoding`).
69
+ * Inline legend for `lista`/`standard` (0.21): slim pointer — the full legend
70
+ * (section→source table + every derivation rule of the dieted encoding) lives
71
+ * in the `sbd://toe/codegen-instructions/{mode}` resource, `detail_encoding`.
100
72
  */
101
- const PROVENANCE_LEGEND = {
102
- note: "Deduplicated encoding (detail=standard/minimal): per-item `source` fields " +
103
- "are elided (every list is source-homogeneous), requirement `category` = " +
104
- "requirement_id category segment (the one before the number: AUT-003→AUT, " +
105
- "REQ-AGN-001→AGN), g2_context entity lists are grouped as " +
106
- "{slice_id: {entity_id: name|null}}, and citations ids are referenced via " +
107
- "ids_from payload paths. Full legend: read_sbd_toe_resource(" +
108
- "sbd://toe/codegen-instructions/{mode}), section detail_encoding."
109
- };
110
- /**
111
- * Inline legend for `ultrathin` (s3c) — the standard/minimal legend text is
112
- * frozen within a bundle pin (snapshots are byte-frozen; the only edit so far is
113
- * the v1.10 category-segment wording, beta.3, bundle re-pin); ultrathin carries
114
- * its own note with the extra cut rules. Full legend: same MCP resource, section
115
- * `detail_encoding` (incl. the `ultrathin` entry).
116
- */
117
- const PROVENANCE_LEGEND_ULTRATHIN = {
118
- note: "Deduplicated encoding (detail=ultrathin): same rules as detail=standard/" +
119
- "minimal — per-item `source` elided, requirement `category` = " +
120
- "requirement_id category segment (before the number), g2_context entity lists grouped as " +
121
- "{slice_id: {entity_id: name|null}}, citations ids via ids_from payload " +
122
- "paths — PLUS: published `description` fields elided (executable " +
123
- "activated_scope.descriptions_ref, detail='minimal'), evidence_patterns 0 " +
124
- "inline (counts + rest-ref in completeness_report), manual_grounding " +
125
- "aggregate-only (total + sha + groups_ref) and completeness diagnostics " +
126
- "as exact counts (+ ref). Nothing silently dropped. Full legend: MCP " +
127
- "read_sbd_toe_resource(sbd://toe/codegen-instructions/{mode}), detail_encoding."
128
- };
73
+ const PROVENANCE_LEGEND = { note_id: "prepare.provenance_legend" }; // 0.21 §6-c: texto em sbd://toe/notes
129
74
  /**
130
- * v2 token diet, s4 — cheap turns, not fewer turns: short note (≈50 tokens)
131
- * appended to every `standard`/`minimal` ready payload. The production
132
- * write-test-edit loop is legitimate; what must not repeat is the cost of
133
- * re-requesting THIS payload — an identical call returns a byte-identical
134
- * result (deterministic, tested), so the context already in the session is
135
- * the source for the loop. Follow-ups that genuinely need more go through
136
- * `detail: "minimal"` or a targeted `consult_security_requirements` call —
137
- * never a repeat of the full payload. `full` carries NO hint (byte-identical
138
- * to the classic payload, EPIC invariant 1).
75
+ * v2 token diet, s4 — cheap turns, not fewer turns: short note appended to
76
+ * every `lista`/`standard` ready payload. An identical call returns a
77
+ * byte-identical result (deterministic, tested), so the context already in the
78
+ * session is the source for the write-test-edit loop. Follow-ups that need the
79
+ * inline grounding/relations/trace go through `detail: "full"` (declared
80
+ * price in size_estimate) or a targeted `consult_security_requirements` call.
139
81
  */
140
- export const REPEAT_CALL_HINT = "Identical input returns this exact payload (deterministic) — reuse the context already received; deepen via detail:'minimal' or a targeted consult_security_requirements.";
82
+ export const REPEAT_CALL_HINT = NOTES["prepare.repeat_call_hint"]; // 0.21 §6-c: servido por referência (note_id)
83
+ const REPEAT_CALL_HINT_ID = "prepare.repeat_call_hint";
141
84
  // ---------------------------------------------------------------------------
142
85
  // Activation lexicon (small, auditable; WP6 layers semantic scoring on top)
143
86
  // ---------------------------------------------------------------------------
@@ -1263,11 +1206,11 @@ export function instructionSlotsForMode(mode) {
1263
1206
  const slots = [
1264
1207
  {
1265
1208
  when: "always",
1266
- text: "Generate code or review changes ONLY against the deterministic IDs provided in `citation_map`. Do NOT invent SbD-ToE requirement, control, slice, mechanism or obligation IDs."
1209
+ text: "Generate code or review changes ONLY against the deterministic IDs provided in `citations` (the closed world of legal ids for this task). Do NOT invent SbD-ToE requirement, control, slice, mechanism or obligation IDs."
1267
1210
  },
1268
1211
  {
1269
1212
  when: "always",
1270
- text: "For each non-trivial design decision, populate the `security_rationale_template.decisions[].cited_ids` with IDs from `citation_map`. If no ID applies, say so explicitly."
1213
+ text: "For each non-trivial design decision, populate the `security_rationale_template.decisions[].cited_ids` with IDs from `citations`. If no ID applies, say so explicitly."
1271
1214
  },
1272
1215
  {
1273
1216
  when: "always",
@@ -1289,13 +1232,13 @@ export function instructionSlotsForMode(mode) {
1289
1232
  if (mode === "review") {
1290
1233
  slots.push({
1291
1234
  when: "always",
1292
- text: "Review mode: enumerate findings per changed_file, mapped to the activated_scope. Each finding must reference at least one citation_map ID or say 'no normative ID covers this'."
1235
+ text: "Review mode: enumerate findings per changed_file, mapped to the activated_scope. Each finding must reference at least one id from `citations` or say 'no normative ID covers this'."
1293
1236
  });
1294
1237
  }
1295
1238
  if (mode === "test-plan") {
1296
1239
  slots.push({
1297
1240
  when: "always",
1298
- text: "Test-plan mode: produce a checklist of tests grouped by validated_id, with input/expectation, and reference evidence_patterns when available."
1241
+ text: "Test-plan mode: produce a checklist of tests grouped by validated_id, with input/expectation. Each activated requirement carries its own `verify` (validation method) and `evidence` (expected proof) inline — use them verbatim as the test's expectation; for evidence_pattern_id/control_id/expected_artifact_type_ids follow completeness_report.verification.by_ref."
1299
1242
  });
1300
1243
  }
1301
1244
  for (const level of ["L1", "L2", "L3"]) {
@@ -1305,8 +1248,8 @@ export function instructionSlotsForMode(mode) {
1305
1248
  });
1306
1249
  }
1307
1250
  slots.push({
1308
- when: "citation_map_empty",
1309
- text: "Citation_map is empty. This is a strong signal the activated scope did not yield deterministic anchors — request clarification before generating code."
1251
+ when: "citations_empty",
1252
+ text: "`citations` is empty. This is a strong signal the activated scope did not yield deterministic anchors — request clarification before generating code."
1310
1253
  });
1311
1254
  return slots;
1312
1255
  }
@@ -1318,7 +1261,7 @@ function activeInstructionConditions(args) {
1318
1261
  if (args.riskLevel)
1319
1262
  active.push(`risk_level:${args.riskLevel}`);
1320
1263
  if (args.citationMapEmpty)
1321
- active.push("citation_map_empty");
1264
+ active.push("citations_empty");
1322
1265
  return active;
1323
1266
  }
1324
1267
  function buildLlmInstructions(args) {
@@ -1336,7 +1279,7 @@ const SECURITY_RATIONALE_TEMPLATE_SKELETON = {
1336
1279
  decisions: [
1337
1280
  {
1338
1281
  decision: "<fill: what design choice was made>",
1339
- rationale: "<fill: why, citing IDs from citation_map>",
1282
+ rationale: "<fill: why, citing IDs from citations>",
1340
1283
  cited_ids: ["<requirement_id|control_id|slice_id|obligation_id>"]
1341
1284
  }
1342
1285
  ],
@@ -1372,16 +1315,28 @@ export function codegenInstructionsResourceUri(mode) {
1372
1315
  return `${CODEGEN_INSTRUCTIONS_RESOURCE_URI_PREFIX}${mode}`;
1373
1316
  }
1374
1317
  /**
1375
- * Full legend of the dieted (`standard`/`minimal`) encoding, published in the
1318
+ * Full legend of the dieted (`lista`/`standard`) encoding, published in the
1376
1319
  * codegen-instructions resource. Every rule here is a lossless, deterministic
1377
1320
  * derivation over the SAME payload (or an executable reference) — nothing is
1378
1321
  * silently dropped (EPIC invariant 2) and no data changes, only serialization
1379
- * (EPIC invariant 4).
1322
+ * (EPIC invariant 4). 0.21 §1: the requirement is fused (description never
1323
+ * leaves) and the evidence_patterns block is gone at every level.
1380
1324
  */
1381
1325
  const DETAIL_ENCODING_LEGEND = {
1382
- note: "How to read a detail=standard/minimal payload of prepare_sbd_toe_codegen_context. " +
1326
+ note: "How to read a detail=lista/standard payload of prepare_sbd_toe_codegen_context (0.21). " +
1383
1327
  "Every rule below is a deterministic re-encoding of the same published data: " +
1384
- "nothing is silently dropped, and detail=full always returns the classic inline payload.",
1328
+ "nothing is silently dropped. detail=full inlines everything (grounding, relations, trace) " +
1329
+ "and declares its price in size_estimate; the fused requirement is identical at every level.",
1330
+ levels: "lista — every activated requirement complete and verbatim (id, name, type, description, verify, " +
1331
+ "evidence) + citable ids + the instructions that forbid inventing ids; manual grounding by " +
1332
+ "reference (manual_grounding.entries_ref → detail='full'); relations OUT (g2_context.relations_summary " +
1333
+ "keeps the exact accounting; include_relations=true restores them); adjacency SUMMARY inline (top-N + " +
1334
+ "denominators), detail by reference. standard — what lista promises plus the adjacency DETAIL inline " +
1335
+ "(every undeclared signal that would change the set). full — what standard promises plus manual_grounding verbatim inline, " +
1336
+ "g2_context.relations_ref (executable trace calls; include_relations=true inlines them) and " +
1337
+ "activation_trace inline; no requirement ceiling. " +
1338
+ "'ultrathin' was retired in 0.21 (its documented purpose was to cut the description, which " +
1339
+ "is no longer negotiable); 'minimal' became 'lista' (same 8,450 tk envelope).",
1385
1340
  sources: {
1386
1341
  note: "Per-item `source` fields are elided. Every list below is source-homogeneous " +
1387
1342
  "(no exceptions): apply the listed source to each of its items. " +
@@ -1390,69 +1345,63 @@ const DETAIL_ENCODING_LEGEND = {
1390
1345
  "reference to trace_sbd_toe_graph calls, not a source list.",
1391
1346
  map: PROVENANCE_SOURCES
1392
1347
  },
1393
- citations: "citations.<source>.source_data is an ordered run-length map file -> count. " +
1348
+ citations: "0.21 §3: `citations` is the closed world of legal ids at EVERY level (citation_map is gone). " +
1349
+ "citations.<source>.source_data is an ordered run-length map file -> count. " +
1394
1350
  "The citable ids are NOT repeated: citations.<source>.ids_from is aligned 1:1 " +
1395
1351
  "with the source_data files, and names the payload path whose ids (in payload " +
1396
- "order) form that file's run. Paths of the form " +
1397
- "keys(g2_context.<list>[slice]) iterate the slice groups in order, then the " +
1398
- "entity-id keys in order. If a file ever has no path mapping, the group " +
1399
- "carries explicit `ids` instead (lossless fallback).",
1400
- activated_scope_requirements: "requirement `category` is elided because it equals the requirement_id " +
1401
- "category segment — the one immediately before the number (AUT-003→AUT, " +
1402
- "REQ-AGN-001→AGN; consumer contract v1.10 §1.18). Verbatim bundle invariant; " +
1403
- "the field survives inline on any future mismatch. `description` is the verbatim published field from " +
1404
- "data/publish/runtime/requirements.json — never paraphrased.",
1352
+ "order) form that file's run. Paths of the form section.list[].field iterate a list; " +
1353
+ "keys(g2_context.<list>[slice]) (lista/standard) iterate the slice groups in order, then the " +
1354
+ "entity-id keys in order; at full the g2 sections are lists (g2_context.<list>[].entity_id). " +
1355
+ "If a file ever has no path mapping, the group carries explicit `ids` instead (lossless fallback).",
1356
+ activated_scope_requirements: "ONE object per requirement (0.21 §1): {id, name, type, description, verify, evidence}. " +
1357
+ "`description` is the verbatim published field (data/publish/runtime/requirements.json) and " +
1358
+ "NEVER leaves, at any level. `verify` = verification_logic and `evidence` = " +
1359
+ "evidence_expectation of the requirement's published evidence pattern " +
1360
+ "(data/publish/runtime/evidence_patterns.json, 1:1 per requirement), verbatim. The pattern's " +
1361
+ "other fields (evidence_pattern_id, control_id, expected_artifact_type_ids) are served by " +
1362
+ "reference: completeness_report.verification.by_ref (get_sbd_toe_verification_matrix, ≤50 " +
1363
+ "ids per call). `category` is elided because it equals the id category segment (AUT-003→AUT, " +
1364
+ "REQ-AGN-001→AGN; consumer contract v1.10 §1.18) — the field survives inline on any mismatch.",
1405
1365
  activated_scope_controls: "controls with confidence='direct' carry the verbatim published `description` " +
1406
1366
  "from data/publish/runtime/controls.json.",
1367
+ adjacency: "0.21 §2 — `adjacency` at EVERY level: the closed-vocabulary signals you did NOT declare that would " +
1368
+ "change the requirement set, with what each would add (arithmetic over the declaration: the same " +
1369
+ "deterministic selection re-run with the signal added — never a reading of the task). " +
1370
+ "undeclared_that_would_change_the_set is the top-N by would_add; would_change_the_set is the " +
1371
+ "denominator (never truncated in silence); scanned is how many vocabulary values were probed. " +
1372
+ "`detail` (the full list; the summary is its prefix) is inline at standard/full and reachable via " +
1373
+ "detail_ref at lista. In selection_mode='discover' the adjacency is relative to the declaration made, " +
1374
+ "not to the inferred set.",
1407
1375
  g2_entities: "g2_context.control_objectives/mechanisms/practices/artifacts are grouped as " +
1408
1376
  "{slice_id: {entity_id: name|null}}. entity_type is the list the map lives in " +
1409
1377
  "(ControlObjective/Mechanism/Practice/Artifact), slice_id is the group key, " +
1410
1378
  "slice_family is activated_scope.slices[].objective_family for that slice_id, " +
1411
1379
  "and a null name means the entity is unnamed in the published rastreabilidade " +
1412
1380
  "(the full projection omits `name` for it).",
1413
- evidence_patterns: "g2_context.evidence_patterns is the deterministic prefix (relevance desc, " +
1414
- "then id asc; the tool-computed relevance_score is elided — the order carries " +
1415
- "the ranking) of the classic detail=full list, capped per " +
1416
- "completeness_report.evidence_pattern_cap. completeness_report reports " +
1417
- "total/returned/capped and, when anything was cut, evidence_patterns_rest " +
1418
- "says how to retrieve the rest (same input, detail='full'; with debug=true " +
1419
- "the ids beyond the classic cap are listed in debug.rejected_candidates).",
1420
- manual_grounding_minimal: "At detail=minimal, manual_grounding is the aggregated-provenance form " +
1421
- "(s3b): total_entries, the manual_commit_sha shared by every group " +
1422
- "(hoisted; a group keeps its own sha inline only if hoisting was not " +
1423
- "possible), and the (rastreabilidade_role, manual_chapter, manual_file) " +
1424
- "groups with the exact per-group `entries` COUNT instead of the " +
1425
- "v1_entity_ids list (counts sum to total_entries — never silent). The " +
1426
- "grounding id set is already in the same payload (g2_context entity-map " +
1427
- "keys); manual_grounding.groups_ref is the executable reference (same " +
1428
- "input, detail='standard') for the per-group id lists — groups align " +
1429
- "1:1, same order. detail=standard keeps the full grouping inline.",
1430
- activation_trace: "activation_trace is elided at detail=standard/minimal; " +
1381
+ verification: "There is no g2_context.evidence_patterns block any more (0.21 §1). " +
1382
+ "completeness_report.verification declares the denominators: requirements, " +
1383
+ "with_verify_and_evidence, partial, without_pattern, and " +
1384
+ "related_by_control_outside_scope (patterns linked to an activated control whose " +
1385
+ "requirement is not in the activated set — never inlined, reachable via the ref).",
1386
+ manual_grounding: "At detail=lista/standard, manual_grounding is the counts form: total_entries, the " +
1387
+ "manual_commit_sha shared by every group (hoisted; a group keeps its own sha inline " +
1388
+ "only if hoisting was not possible), and the (rastreabilidade_role, manual_chapter, " +
1389
+ "manual_file) groups with the exact per-group `entries` COUNT (counts sum to " +
1390
+ "total_entries — never silent). The grounding id set is already in the same payload " +
1391
+ "(g2_context entity-map keys); manual_grounding.entries_ref is the executable " +
1392
+ "reference (same input, detail='full') for the verbatim flat entries.",
1393
+ activation_trace: "activation_trace is elided at detail=lista/standard; " +
1431
1394
  "activation_trace_ref.entries keeps the exact count. Re-call with debug=true " +
1432
1395
  "to include the full trace (it is always inline at detail=full).",
1433
- relations_ref: "Inline g2_context.relations are elided at detail=standard/minimal (re-call " +
1434
- "with include_relations=true to restore them). Recover the elided graph edges " +
1396
+ relations_ref: "0.21 §3: inline g2_context.relations are elided at EVERY level (re-call with " +
1397
+ "include_relations=true to restore them). At full, g2_context.relations_ref lists the " +
1398
+ "executable trace calls; at lista/standard only g2_context.relations_summary (the same exact " +
1399
+ "accounting) stays — the edges link nodes this payload already carries. Recover the elided graph edges " +
1435
1400
  "by executing trace_sbd_toe_graph with each {lens, anchor} pair listed " +
1436
1401
  "(anchors are activated slice/entity ids from the same payload); the " +
1437
1402
  "belongsToSlice edges counted as coverage.implicit_in_entities are already " +
1438
1403
  "encoded by the slice grouping key of every g2_context entity; any relation " +
1439
- "covered by neither stays inline in residual_relations (never silent).",
1440
- ultrathin: "detail=ultrathin (s3c) applies every rule above PLUS: (1) requirements " +
1441
- "{requirement_id, name, type} and controls {control_id, name, domain, " +
1442
- "control_type, confidence} keep the COMPLETE activated set (same ids, " +
1443
- "same order, name always present) but elide the published `description` " +
1444
- "— activated_scope.descriptions_ref is the executable reference (same " +
1445
- "input, detail='minimal') for the verbatim descriptions; (2) " +
1446
- "g2_context.evidence_patterns is empty (cap 0) — completeness_report " +
1447
- "keeps total/returned=0/capped=total and evidence_patterns_rest points " +
1448
- "to detail='minimal' (cheapest level returning patterns inline; " +
1449
- "'standard' returns 10, 'full' the classic 25); (3) manual_grounding is " +
1450
- "{total_entries, manual_commit_sha, groups_ref} — the group list is " +
1451
- "elided (detail='standard' returns the full 1:1 grouping); (4) " +
1452
- "v1_consistency_mismatches/v1_manifest_warnings text arrays are replaced " +
1453
- "by exact *_count fields (+ v1_diagnostics_ref when any count > 0, " +
1454
- "detail='minimal' returns the texts). The citable id set and the " +
1455
- "citations/ids_from encoding are IDENTICAL to the other dieted levels."
1404
+ "covered by neither stays inline in residual_relations (never silent)."
1456
1405
  };
1457
1406
  /**
1458
1407
  * Content of the `sbd://toe/codegen-instructions/{mode}` MCP resource — the
@@ -1468,17 +1417,18 @@ export function buildCodegenInstructionsResourceContent(mode) {
1468
1417
  return {
1469
1418
  resource: codegenInstructionsResourceUri(mode),
1470
1419
  mode,
1471
- note: "Static per-mode boilerplate for prepare_sbd_toe_codegen_context at " +
1472
- "detail=standard/minimal (kept inline at detail=full). Also carries the " +
1473
- "detail_encoding legend for the dieted payload.",
1420
+ note: "Static per-mode boilerplate of prepare_sbd_toe_codegen_context (0.21: the " +
1421
+ "instructions and the template are INLINE at every level; this resource is the " +
1422
+ "reference copy, slot by slot). Also carries the detail_encoding legend.",
1474
1423
  // 0.15.0 item 8, invertido para esta linha (0.20): aqui o trace EXISTE.
1475
1424
  line_note: "Nesta linha 0.20 o trace_sbd_toe_graph existe: execute os " +
1476
1425
  "relations_ref directamente ({lens, anchor}). include_relations=true no " +
1477
1426
  "prepare continua disponível como atalho para relações inline.",
1478
1427
  llm_codegen_instructions: {
1479
- assembly: "Include each slot whose `when` is 'always' or appears in this call's " +
1480
- "codegen_instructions_ref.active_conditions, in the listed order — the " +
1481
- "result is byte-identical to the detail=full inline llm_codegen_instructions.",
1428
+ assembly: "Include each slot whose `when` is 'always' or whose condition holds for the call " +
1429
+ "(regulatory_overlay: activated_scope.regulatory_obligations non-empty; " +
1430
+ "risk_level:<L>: input_echo.risk_level; citations_empty: no citable id), in the " +
1431
+ "listed order — the result is byte-identical to the inline llm_codegen_instructions.",
1482
1432
  slots: instructionSlotsForMode(mode)
1483
1433
  },
1484
1434
  security_rationale_template: {
@@ -1514,12 +1464,12 @@ function blocked(input, raw, status, reasons, suggestions, partial, debug) {
1514
1464
  }
1515
1465
  return result;
1516
1466
  }
1517
- const DETAIL_LEVELS = new Set([
1518
- "ultrathin",
1519
- "minimal",
1520
- "standard",
1521
- "full"
1522
- ]);
1467
+ const DETAIL_LEVELS = new Set(["lista", "standard", "full"]);
1468
+ /** 0.21: níveis retirados/renomeados — o erro diz para onde foram, nunca só «inválido». */
1469
+ const RETIRED_DETAIL_LEVELS = {
1470
+ ultrathin: "'ultrathin' retirou-se na 0.21: a sua razão de existir era cortar a descrição publicada, e a descrição deixou de ser negociável (nunca sai, em nenhum nível). Usa detail='lista'.",
1471
+ minimal: "'minimal' passou a chamar-se 'lista' na 0.21 (herda-lhe o envelope de 8.450 tk; traz a descrição, verify e evidence de cada requisito inline). Usa detail='lista'."
1472
+ };
1523
1473
  /**
1524
1474
  * Validate the `detail` input (v2 token diet, s1). Invalid values fail fast
1525
1475
  * with a JSON-RPC -32602 (same pattern as trace-graph's lens validation);
@@ -1534,12 +1484,11 @@ function parseDetail(raw) {
1534
1484
  if (typeof value === "string" && DETAIL_LEVELS.has(value)) {
1535
1485
  return value;
1536
1486
  }
1537
- throw Object.assign(new Error(`Invalid "detail": ${JSON.stringify(value)}. Use one of: ultrathin, minimal, standard, full.`), {
1538
- rpcError: {
1539
- code: -32602,
1540
- message: 'Invalid "detail". Use one of: ultrathin, minimal, standard, full.'
1541
- }
1542
- });
1487
+ const retired = typeof value === "string" ? RETIRED_DETAIL_LEVELS[value] : undefined;
1488
+ const message = retired
1489
+ ? `Invalid "detail": ${JSON.stringify(value)}. ${retired}`
1490
+ : `Invalid "detail": ${JSON.stringify(value)}. Use one of: lista, standard, full.`;
1491
+ throw Object.assign(new Error(message), { rpcError: { code: -32602, message } });
1543
1492
  }
1544
1493
  /**
1545
1494
  * Validate the `include_relations` input (v2 token diet, s2). Only booleans
@@ -1568,9 +1517,7 @@ const PRED_REALIZED_BY_PRACTICE = "objective_realized_by_practice";
1568
1517
  // s3: slimmed — the full explanation lives in the codegen-instructions MCP
1569
1518
  // resource (detail_encoding.relations_ref). Kept URI-free on purpose: the
1570
1519
  // no-leak gate scans relations_ref for any scheme://.
1571
- const RELATIONS_REF_NOTE = "Inline g2_context.relations elided; execute each listed trace_sbd_toe_graph " +
1572
- "{lens, anchor} call to recover them, or re-call with include_relations=true. " +
1573
- "Encoding details: MCP resource codegen-instructions, detail_encoding.relations_ref.";
1520
+ const RELATIONS_REF_NOTE_ID = "prepare.relations_ref"; // 0.21 §6-c: texto em src/serving/notes.ts → sbd://toe/notes/prepare.relations_ref
1574
1521
  /**
1575
1522
  * v2 token diet, s2 — build the `relations_ref` for `detail: "standard" |
1576
1523
  * "minimal"`. See the {@link RelationsRefLensCall} doc block for the full
@@ -1690,7 +1637,7 @@ function buildRelationsRef(result) {
1690
1637
  implicit_in_entities: implicitInEntities,
1691
1638
  residual_inline: residual.length
1692
1639
  },
1693
- note: RELATIONS_REF_NOTE
1640
+ note_id: RELATIONS_REF_NOTE_ID
1694
1641
  };
1695
1642
  if (residual.length > 0)
1696
1643
  relationsRef.residual_relations = residual;
@@ -1708,7 +1655,7 @@ function stripSource(items) {
1708
1655
  * if one ever appears, the group falls back to explicit `ids` (lossless).
1709
1656
  */
1710
1657
  const CITATION_FILE_TO_PAYLOAD_PATH = {
1711
- "data/publish/runtime/requirements.json": "activated_scope.requirements[].requirement_id",
1658
+ "data/publish/runtime/requirements.json": "activated_scope.requirements[].id",
1712
1659
  "data/publish/runtime/controls.json": "activated_scope.controls[].control_id",
1713
1660
  "data/publish/runtime/v1/slices.json": "activated_scope.slices[].slice_id",
1714
1661
  "data/publish/runtime/v1/control_objectives.json": "keys(g2_context.control_objectives[slice])",
@@ -1718,6 +1665,37 @@ const CITATION_FILE_TO_PAYLOAD_PATH = {
1718
1665
  "data/publish/overlay/external_frameworks.json": "regulatory_overlay.frameworks[].framework_id",
1719
1666
  "data/publish/overlay/external_obligations.json": "activated_scope.regulatory_obligations[].obligation_id"
1720
1667
  };
1668
+ /** 0.21 §3: at `full` the g2 entity sections are LISTS (classic), so the ids_from paths differ
1669
+ * only for those four files; every other path is shared with the dieted levels. */
1670
+ const CITATION_FILE_TO_PAYLOAD_PATH_FULL = {
1671
+ ...CITATION_FILE_TO_PAYLOAD_PATH,
1672
+ "data/publish/runtime/v1/control_objectives.json": "g2_context.control_objectives[].entity_id",
1673
+ "data/publish/runtime/v1/mechanisms.json": "g2_context.mechanisms[].entity_id",
1674
+ "data/publish/runtime/v1/practices.json": "g2_context.practices[].entity_id",
1675
+ "data/publish/runtime/v1/artifacts.json": "g2_context.artifacts[].entity_id"
1676
+ };
1677
+ /**
1678
+ * 0.21 §3 — resolve the ids of a `citations` block over the payload that carries it
1679
+ * (any level): `section.list[].field` iterates a list; `keys(g2_context.<list>[slice])`
1680
+ * iterates the slice groups then the entity-id keys. Explicit `ids` is the lossless
1681
+ * fallback. Exported so consumers and tests read ids by the SAME published rule.
1682
+ */
1683
+ export function citableIds(payload) {
1684
+ const root = payload;
1685
+ const at = (path) => {
1686
+ const keys = /^keys\(g2_context\.([a-z_]+)\[slice\]\)$/.exec(path);
1687
+ if (keys) {
1688
+ const grouped = (root["g2_context"]?.[keys[1]] ?? {});
1689
+ return Object.values(grouped).flatMap((entities) => Object.keys(entities));
1690
+ }
1691
+ const list = /^([a-z0-9_]+)\.([a-z0-9_]+)\[\]\.([a-z0-9_]+)$/.exec(path);
1692
+ if (!list)
1693
+ throw new Error(`ids_from path desconhecido: ${path}`);
1694
+ const items = (root[list[1]]?.[list[2]] ?? []);
1695
+ return items.map((item) => item[list[3]]);
1696
+ };
1697
+ return Object.values(root.citations ?? {}).flatMap((group) => group?.ids ?? (group?.ids_from ?? []).flatMap(at));
1698
+ }
1721
1699
  /**
1722
1700
  * Invert the classic `citation_map` (id → {source, source_data}) into
1723
1701
  * source-grouped `citations` (see {@link CitationsGroup}). Pure re-encoding:
@@ -1727,7 +1705,8 @@ const CITATION_FILE_TO_PAYLOAD_PATH = {
1727
1705
  * of repeated; a group keeps explicit `ids` only if one of its files has no
1728
1706
  * payload-path mapping (never expected for the published bundle).
1729
1707
  */
1730
- function invertCitationMap(citationMap) {
1708
+ function invertCitationMap(citationMap, layout = "grouped") {
1709
+ const pathTable = layout === "list" ? CITATION_FILE_TO_PAYLOAD_PATH_FULL : CITATION_FILE_TO_PAYLOAD_PATH;
1731
1710
  const bySource = new Map();
1732
1711
  for (const [id, entry] of Object.entries(citationMap)) {
1733
1712
  let files = bySource.get(entry.source);
@@ -1751,7 +1730,7 @@ function invertCitationMap(citationMap) {
1751
1730
  for (const [file, fileIds] of files) {
1752
1731
  source_data[file] = fileIds.length;
1753
1732
  ids.push(...fileIds);
1754
- const path = CITATION_FILE_TO_PAYLOAD_PATH[file];
1733
+ const path = pathTable[file];
1755
1734
  if (path === undefined)
1756
1735
  allFilesMapped = false;
1757
1736
  else
@@ -1830,11 +1809,7 @@ function groupManualGrounding(result) {
1830
1809
  return grouped;
1831
1810
  }
1832
1811
  // s3b: kept URI-free on purpose (no-leak discipline, same as RELATIONS_REF_NOTE).
1833
- const GROUNDING_GROUPS_REF_NOTE = "Per-group v1_entity_ids elided at detail=minimal (each group carries its " +
1834
- "exact `entries` count). The grounding id set is already in this payload — " +
1835
- "every grounding id is an entity-id key of the g2_context maps. Re-call " +
1836
- "with the same input at detail='standard' for the per-group id lists " +
1837
- "(groups align 1:1, same order).";
1812
+ const GROUNDING_ENTRIES_REF_NOTE_ID = "prepare.grounding.entries_ref"; // 0.21 §6-c: texto em src/serving/notes.ts → sbd://toe/notes/prepare.grounding.entries_ref
1838
1813
  /**
1839
1814
  * v2 token diet, s3b (revised ADENDA 2026-07-05) — minimal-form
1840
1815
  * `manual_grounding`, derived from the detail="standard" grouping (so the 1:1
@@ -1871,101 +1846,17 @@ function buildMinimalGrounding(grouped) {
1871
1846
  entries: group.v1_entity_ids.length,
1872
1847
  ...(group.v1_entity_names ? { v1_entity_names: group.v1_entity_names } : {})
1873
1848
  })),
1874
- groups_ref: {
1849
+ entries_ref: {
1875
1850
  tool: "prepare_sbd_toe_codegen_context",
1876
- with: { detail: "standard" },
1877
- note: GROUNDING_GROUPS_REF_NOTE
1851
+ with: { detail: "full" },
1852
+ note_id: GROUNDING_ENTRIES_REF_NOTE_ID
1878
1853
  }
1879
1854
  };
1880
1855
  if (grouped.ungrouped)
1881
1856
  minimal.ungrouped = grouped.ungrouped;
1882
1857
  return minimal;
1883
1858
  }
1884
- // s3c notes — all NEW constants (the s1–s4 note texts are byte-frozen by the
1885
- // standard/minimal golden snapshots and are never edited). Kept URI-free
1886
- // (no-leak discipline, same as RELATIONS_REF_NOTE).
1887
- const GROUNDING_GROUPS_REF_NOTE_ULTRATHIN = "Grounding group list elided at detail=ultrathin (total_entries is the " +
1888
- "exact flat entry count; manual_commit_sha is the shared published manual " +
1889
- "commit). The grounding id set is already in this payload — every " +
1890
- "grounding id is an entity-id key of the g2_context maps. Re-call with the " +
1891
- "same input at detail='standard' for the full (role, chapter, file) groups " +
1892
- "with per-group v1_entity_ids; detail='minimal' returns the groups with " +
1893
- "per-group counts.";
1894
- const DESCRIPTIONS_REF_NOTE = "Published `description` fields (the 'how') elided at detail=ultrathin — " +
1895
- "the requirement/control lists themselves are COMPLETE (same ids, same " +
1896
- "order, name always present). Re-call with the same input at " +
1897
- "detail='minimal' for the same complete scope WITH the verbatim published " +
1898
- "descriptions (requirements + direct controls).";
1899
- const EVIDENCE_PATTERNS_REST_NOTE_ULTRATHIN = "No evidence pattern goes inline at detail=ultrathin (returned=0; " +
1900
- "capped=total). Re-call with the same input at detail='minimal' for the " +
1901
- "deterministic top-5 (cheapest level that returns patterns inline); " +
1902
- "detail='standard' returns the top-10 and detail='full' the classic " +
1903
- "top-25 (each list is a deterministic prefix of the next).";
1904
- const ACTIVATION_TRACE_REF_NOTE_ULTRATHIN = "activation_trace elided at detail=ultrathin — re-call with debug=true to " +
1905
- "include it (always inline at detail=full).";
1906
- const V1_DIAGNOSTICS_REF_NOTE = "v1_consistency_mismatches/v1_manifest_warnings texts elided at " +
1907
- "detail=ultrathin (exact counts inline). Re-call with the same input at " +
1908
- "detail='minimal' for the full text arrays in completeness_report.";
1909
- /**
1910
- * v2 token diet, s3c — ultrathin-form `manual_grounding`, derived from the
1911
- * s3b minimal form (so `total_entries`, the hoisted sha and the ungrouped
1912
- * guard are byte-identical by construction). Serialization-only cut, never
1913
- * silent: the (role, chapter, file) group list with per-group counts is
1914
- * elided; `total_entries` keeps the exact flat count and `groups_ref` is the
1915
- * executable reference to the full grouping (same input, detail="standard").
1916
- * Lossless guards (expected never): if the sha was not hoistable or any group
1917
- * carries `v1_entity_names`, the minimal `groups` list survives inline.
1918
- */
1919
- function buildUltrathinGrounding(minimal) {
1920
- const mustKeepGroups = minimal.manual_commit_sha === undefined ||
1921
- minimal.groups.some((group) => group.v1_entity_names !== undefined || group.manual_commit_sha !== undefined);
1922
- const ultrathin = {
1923
- total_entries: minimal.total_entries,
1924
- ...(minimal.manual_commit_sha !== undefined
1925
- ? { manual_commit_sha: minimal.manual_commit_sha }
1926
- : {}),
1927
- ...(mustKeepGroups && minimal.groups.length > 0 ? { groups: minimal.groups } : {}),
1928
- groups_ref: {
1929
- tool: "prepare_sbd_toe_codegen_context",
1930
- with: { detail: "standard" },
1931
- note: GROUNDING_GROUPS_REF_NOTE_ULTRATHIN
1932
- }
1933
- };
1934
- if (minimal.ungrouped)
1935
- ultrathin.ungrouped = minimal.ungrouped;
1936
- return ultrathin;
1937
- }
1938
- /**
1939
- * v2 token diet, s3c — trim the completeness report for `detail: "ultrathin"`.
1940
- * Every COUNT survives verbatim (never-silent backbone: expected/returned per
1941
- * entity kind, m_recall, named/unnamed, evidence total/returned/capped/cap and
1942
- * the rest-ref); only the two diagnostic TEXT arrays are re-encoded as exact
1943
- * counts + the executable `v1_diagnostics_ref` (see
1944
- * {@link UltrathinCompletenessReport} for what is cut and why).
1945
- */
1946
- function trimCompletenessForUltrathin(report) {
1947
- const { v1_consistency_mismatches, v1_manifest_warnings, ...kept } = report;
1948
- // 0.15.0: ultrathin OMITE os counts excluded_by_level (dieta; tecto 4.840 vigia) —
1949
- // a banda fica declarada no select e nos perfis standard/minimal/full.
1950
- if (kept.selection) {
1951
- const { excluded_by_level_categories: _c, excluded_by_level_requirements: _r, lexical_share: _lx, ...selRest } = kept.selection;
1952
- kept.selection = selRest;
1953
- }
1954
- return {
1955
- ...kept,
1956
- v1_consistency_mismatches_count: v1_consistency_mismatches.length,
1957
- v1_manifest_warnings_count: v1_manifest_warnings.length,
1958
- ...(v1_consistency_mismatches.length + v1_manifest_warnings.length > 0
1959
- ? {
1960
- v1_diagnostics_ref: {
1961
- tool: "prepare_sbd_toe_codegen_context",
1962
- with: { detail: "minimal" },
1963
- note: V1_DIAGNOSTICS_REF_NOTE
1964
- }
1965
- }
1966
- : {})
1967
- };
1968
- }
1859
+ // (notas s3c removidas na 0.21 — o nível ultrathin reformou-se.)
1969
1860
  /** Slice-grouped, name-only entity encoding (see {@link SliceGroupedEntityNames}). */
1970
1861
  function groupEntitiesBySlice(entities) {
1971
1862
  const grouped = {};
@@ -1981,135 +1872,74 @@ function categoryIsDerivable(requirementId, category) {
1981
1872
  const derived = requirementCategoryOf(requirementId);
1982
1873
  return derived !== undefined && derived === category;
1983
1874
  }
1984
- /** Dieted requirements: `source`/derivable `category` elided, verbatim
1985
- * published `description` appended (s3 — the "how"). s3c: at
1986
- * `detail: "ultrathin"` (`includeDescriptions: false`) the description is
1987
- * elided too — each item is exactly {requirement_id, name, type} (plus the
1988
- * unchanged `category` lossless guard) with the executable
1989
- * `activated_scope.descriptions_ref` pointing at detail="minimal". */
1990
- function dietRequirements(requirements, includeDescriptions) {
1991
- const descriptionById = new Map();
1992
- if (includeDescriptions) {
1993
- for (const requirement of getOntologyData().requirements) {
1994
- if (requirement.description) {
1995
- descriptionById.set(requirement.requirement_id, requirement.description);
1996
- }
1997
- }
1998
- }
1875
+ /** Dieted requirements (0.21 §1): the fused object minus per-item `source`;
1876
+ * `category` elided iff derivable from the id (lossless guard otherwise). The
1877
+ * description/verify/evidence come from the core — they are the SAME at every
1878
+ * level; nothing is added or removed here. */
1879
+ function dietRequirements(requirements) {
1999
1880
  return requirements.map((item) => {
2000
1881
  const { source: _source, category, ...rest } = item;
2001
- const description = descriptionById.get(item.requirement_id);
2002
1882
  return {
2003
1883
  ...rest,
2004
- ...(categoryIsDerivable(item.requirement_id, category) ? {} : { category }),
2005
- ...(description ? { description } : {})
1884
+ ...(category !== undefined && !categoryIsDerivable(item.id, category) ? { category } : {})
2006
1885
  };
2007
1886
  });
2008
1887
  }
2009
- /** Dieted controls: `source` elided; `direct` controls carry the verbatim
2010
- * published `description` (s3 — the "how"). s3c: at `detail: "ultrathin"`
2011
- * (`includeDescriptions: false`) the description is elided — each item is
2012
- * exactly {control_id, name, domain, control_type, confidence} (every
2013
- * non-description published field: small, useful, and required to keep the
2014
- * item more than id-only). */
2015
- function dietControls(controls, includeDescriptions) {
2016
- const descriptionById = new Map();
2017
- if (includeDescriptions) {
2018
- for (const control of getOntologyData().controls) {
2019
- if (control.description)
2020
- descriptionById.set(control.control_id, control.description);
2021
- }
2022
- }
2023
- return controls.map((item) => {
2024
- const { source: _source, ...rest } = item;
2025
- const description = item.confidence === "direct" ? descriptionById.get(item.control_id) : undefined;
2026
- return { ...rest, ...(description ? { description } : {}) };
2027
- });
1888
+ /** Dieted controls: `source` elided; the `direct` controls' verbatim published
1889
+ * `description` comes from the core (0.21: at every level, full included). */
1890
+ function dietControls(controls) {
1891
+ return stripSource(controls);
2028
1892
  }
2029
1893
  /**
2030
- * v2 token diet, s1+s2+s3 — dieted encoding for `detail: "standard" |
2031
- * "minimal"`. Pure post-processing over the byte-identical full result. The
2032
- * citable ID set is EXACTLY the full one (invariant 3; the omitted evidence
2033
- * patterns carry no citation_map ids — verified by tests). Every cut is
2034
- * either a lossless derivable-field re-encoding documented in the
2035
- * codegen-instructions resource legend, or an explicit bound with
2036
- * total/returned/omitted counts plus an executable reference to the rest
2037
- * (invariant 2 — never silent):
2038
- * - s1: inverted citations, grouped grounding, per-item `source` legend;
1894
+ * 0.21 — a forma por nível é uma TABELA, não ramos: o que cada nível põe
1895
+ * inline e o que põe por referência. Parametrizável de propósito — a §4 do
1896
+ * despacho (o Mensor mede se o `manual_grounding` vai inline ou por
1897
+ * referência) e o «2 ou 3 níveis» ficam em aberto e decidem-se aqui, numa
1898
+ * linha, sem reescrever o servidor.
1899
+ */
1900
+ export const LEVEL_FORM = {
1901
+ lista: { manual_grounding: "ref", relations: "ref", adjacency_detail: "ref" }, // relations "ref" = 0.21 §3 summary (accounting + way back)
1902
+ standard: { manual_grounding: "ref", relations: "ref", adjacency_detail: "inline" } // 0.21 §2: o separador lista↔standard
1903
+ };
1904
+ const ADJACENCY_DETAIL_REF_NOTE_ID = "prepare.adjacency.detail_ref"; // 0.21 §6-c: texto em src/serving/notes.ts → sbd://toe/notes/prepare.adjacency.detail_ref
1905
+ /**
1906
+ * Dieted encoding for `detail: "lista" | "standard"` (0.21). Pure
1907
+ * post-processing over the full result. The citable ID set is EXACTLY the
1908
+ * full one (invariant 3). Every cut is either a lossless derivable-field
1909
+ * re-encoding documented in the codegen-instructions resource legend, or an
1910
+ * explicit bound with counts plus an executable reference (never silent):
1911
+ * - s1: inverted citations, per-item `source` legend;
2039
1912
  * - s2: relations on-demand via `relations_ref` (include_relations restores);
2040
- * - s3: evidence cap 25→10 (deterministic prefix; counts + rest-ref in
2041
- * completeness_report), instructions/template → MCP resource, trace only
2042
- * with debug, verbatim published `description` on requirements + direct
2043
- * controls, and derivable-field dedup (category, entity_type/slice_family
2044
- * via slice-grouped entity maps, relevance_score, citation id repeats);
2045
- * - s3b (revised ADENDA 2026-07-05 — no top-N): `minimal` keeps the
2046
- * activated scope byte-identical to `standard` and diverges ONLY on
2047
- * traceability serialization — evidence cap 10→5 (same mechanism) and
2048
- * `manual_grounding` in the minimal form (counts + hoisted sha +
2049
- * executable groups_ref);
2050
- * - s3c (`ultrathin`, operator reactivation 2026-07-05): same complete
2051
- * activated set, but descriptions elided (descriptions_ref →
2052
- * detail="minimal"), evidence cap 5→0 (rest-ref → detail="minimal"),
2053
- * grounding aggregate-only and completeness diagnostics as counts + ref.
1913
+ * - 0.21 §1: the fused requirement is byte-identical to full's minus
1914
+ * `source`; instructions + template INLINE; manual_grounding in the
1915
+ * counts form with `entries_ref` → detail="full"; trace only with debug.
2054
1916
  */
2055
- function applyStructuralDiet(result, detail, includeRelations) {
2056
- // s3/s3b/s3c evidence cap (standard 10, minimal 5, ultrathin 0):
2057
- // deterministic prefix of the classic (already sorted: relevance_score desc,
2058
- // id asc) list; each dieted list is by construction a prefix of the next
2059
- // level's. Never-silent counts below; the rest-ref points to detail="full"
2060
- // (classic top-25) at standard/minimal and to detail="minimal" (the
2061
- // CHEAPEST level that returns patterns inline) at ultrathin.
2062
- const ultrathin = detail === "ultrathin";
2063
- const evidenceCap = ultrathin
2064
- ? ULTRATHIN_EVIDENCE_PATTERN_CAP
2065
- : detail === "minimal"
2066
- ? MINIMAL_EVIDENCE_PATTERN_CAP
2067
- : STANDARD_EVIDENCE_PATTERN_CAP;
2068
- const evidenceKept = result.g2_context.evidence_patterns.slice(0, evidenceCap);
2069
- const evidenceTotal = result.completeness_report.evidence_patterns_total;
2070
- const evidenceCapped = evidenceTotal - evidenceKept.length;
2071
- const completeness = {
2072
- ...result.completeness_report,
2073
- evidence_patterns_returned: evidenceKept.length,
2074
- evidence_patterns_capped: evidenceCapped,
2075
- evidence_pattern_cap: evidenceCap,
2076
- ...(evidenceCapped > 0
2077
- ? {
2078
- evidence_patterns_rest: (ultrathin
2079
- ? {
2080
- tool: "prepare_sbd_toe_codegen_context",
2081
- with: { detail: "minimal" },
2082
- note: EVIDENCE_PATTERNS_REST_NOTE_ULTRATHIN
2083
- }
2084
- : {
2085
- tool: "prepare_sbd_toe_codegen_context",
2086
- with: { detail: "full" },
2087
- note: "Re-call with the same input at detail='full' for the classic inline " +
2088
- `top-${EVIDENCE_PATTERN_CAP} evidence_patterns (this list is its ` +
2089
- "deterministic prefix); with debug=true, ids beyond the classic cap " +
2090
- "are listed in debug.rejected_candidates."
2091
- })
2092
- }
2093
- : {})
2094
- };
2095
- // s3 instructions → resource: conditions computed from the SAME resolved
2096
- // inputs the core used, so resource + active_conditions reconstruct the
2097
- // inline full content byte-identically.
2098
- const echoedRisk = result.input_echo.risk_level;
2099
- const riskLevel = echoedRisk === "L1" || echoedRisk === "L2" || echoedRisk === "L3"
2100
- ? echoedRisk
2101
- : undefined;
2102
- const instructionsRef = {
2103
- resource: codegenInstructionsResourceUri(result.mode),
2104
- active_conditions: activeInstructionConditions({
2105
- hasOverlay: result.activated_scope.regulatory_obligations.length > 0,
2106
- riskLevel,
2107
- citationMapEmpty: Object.keys(result.citation_map).length === 0
2108
- }),
2109
- note: "Slots por índice: read_sbd_toe_resource(uri, slot=\"<n>\"); active_conditions filtram; byte-identical ao detail=full."
1917
+ const RELATIONS_SUMMARY_NOTE_ID = "prepare.relations_summary"; // 0.21 §6-c: texto em src/serving/notes.ts → sbd://toe/notes/prepare.relations_summary
1918
+ /**
1919
+ * 0.21 §3 — the SERVED full: classic content, two form changes, same citable set.
1920
+ * `citations` (inverted; ids via list paths) replaces `citation_map`; `relations_ref`
1921
+ * replaces the inline relations unless `include_relations: true`.
1922
+ */
1923
+ function shapeFull(result, includeRelations) {
1924
+ const { citation_map, g2_context, ...rest } = result;
1925
+ const { relations, ...g2 } = g2_context;
1926
+ return {
1927
+ ...rest,
1928
+ ...(includeRelations ? { input_echo: { ...result.input_echo, include_relations: true } } : {}),
1929
+ g2_context: {
1930
+ ...g2,
1931
+ ...(includeRelations ? { relations } : { relations_ref: buildRelationsRef(result) })
1932
+ },
1933
+ citations: invertCitationMap(citation_map, "list")
2110
1934
  };
1935
+ }
1936
+ function applyStructuralDiet(result, detail, includeRelations) {
1937
+ const form = LEVEL_FORM[detail];
1938
+ // 0.21 §3: the exact accounting comes from the same builder the full uses for relations_ref.
1939
+ const relationsRef = includeRelations || form.relations !== "ref" ? undefined : buildRelationsRef(result);
2111
1940
  const dieted = {
2112
1941
  status: result.status,
1942
+ notes: NOTES_HEADER,
2113
1943
  mode: result.mode,
2114
1944
  // Echo the requested detail (and the include_relations escape hatch, when
2115
1945
  // active) for audit; the FULL result never echoes either (explicit "full"
@@ -2119,56 +1949,50 @@ function applyStructuralDiet(result, detail, includeRelations) {
2119
1949
  detail,
2120
1950
  ...(includeRelations ? { include_relations: true } : {})
2121
1951
  },
2122
- // s3: activation_trace only with debug=true; never-silent counter otherwise
2123
- // (s3c: ultrathin carries its own note — the standard/minimal text is
2124
- // byte-frozen by the golden snapshots).
2125
1952
  ...(result.debug
2126
1953
  ? { activation_trace: result.activation_trace }
2127
1954
  : {
2128
1955
  activation_trace_ref: {
2129
1956
  entries: result.activation_trace.length,
2130
- note: ultrathin
2131
- ? ACTIVATION_TRACE_REF_NOTE_ULTRATHIN
2132
- : "activation_trace elided at detail=standard/minimal — re-call with " +
2133
- "debug=true to include it (always inline at detail=full)."
1957
+ note_id: "prepare.activation_trace_ref"
2134
1958
  }
2135
1959
  }),
2136
- provenance_legend: ultrathin ? PROVENANCE_LEGEND_ULTRATHIN : PROVENANCE_LEGEND,
2137
- // s3c: ultrathin elides the published descriptions (executable
2138
- // descriptions_ref → detail="minimal"); the lists stay COMPLETE.
1960
+ provenance_legend: PROVENANCE_LEGEND,
2139
1961
  activated_scope: {
2140
- requirements: dietRequirements(result.activated_scope.requirements, !ultrathin),
2141
- controls: dietControls(result.activated_scope.controls, !ultrathin),
1962
+ requirements: dietRequirements(result.activated_scope.requirements),
1963
+ controls: dietControls(result.activated_scope.controls),
2142
1964
  slices: stripSource(result.activated_scope.slices),
2143
- regulatory_obligations: stripSource(result.activated_scope.regulatory_obligations),
2144
- ...(ultrathin
2145
- ? {
2146
- descriptions_ref: {
2147
- tool: "prepare_sbd_toe_codegen_context",
2148
- with: { detail: "minimal" },
2149
- note: DESCRIPTIONS_REF_NOTE
2150
- }
2151
- }
2152
- : {})
1965
+ regulatory_obligations: stripSource(result.activated_scope.regulatory_obligations)
2153
1966
  },
1967
+ // 0.21 §2: resumo sempre; detalhe inline (standard) ou por referência executável (lista).
1968
+ adjacency: form.adjacency_detail === "inline"
1969
+ ? result.adjacency
1970
+ : {
1971
+ undeclared_that_would_change_the_set: result.adjacency.undeclared_that_would_change_the_set,
1972
+ scanned: result.adjacency.scanned,
1973
+ would_change_the_set: result.adjacency.would_change_the_set,
1974
+ shown: result.adjacency.shown,
1975
+ detail_ref: { tool: "prepare_sbd_toe_codegen_context", with: { detail: "standard" }, note_id: ADJACENCY_DETAIL_REF_NOTE_ID }
1976
+ },
2154
1977
  g2_context: {
2155
1978
  control_objectives: groupEntitiesBySlice(result.g2_context.control_objectives),
2156
1979
  mechanisms: groupEntitiesBySlice(result.g2_context.mechanisms),
2157
1980
  practices: groupEntitiesBySlice(result.g2_context.practices),
2158
1981
  artifacts: groupEntitiesBySlice(result.g2_context.artifacts),
2159
- ...(includeRelations
1982
+ ...(relationsRef === undefined
2160
1983
  ? { relations: stripSource(result.g2_context.relations) }
2161
- : { relations_ref: buildRelationsRef(result) }),
2162
- evidence_patterns: evidenceKept.map(({ source: _source, relevance_score: _score, ...rest }) => rest)
1984
+ : {
1985
+ relations_summary: {
1986
+ total_relations: relationsRef.total_relations,
1987
+ via_lenses: relationsRef.coverage.via_lenses,
1988
+ implicit_in_entities: relationsRef.coverage.implicit_in_entities,
1989
+ residual_inline: relationsRef.coverage.residual_inline,
1990
+ note_id: RELATIONS_SUMMARY_NOTE_ID
1991
+ },
1992
+ ...(relationsRef.residual_relations ? { residual_relations: relationsRef.residual_relations } : {})
1993
+ })
2163
1994
  },
2164
- // s3b: minimal serves the count+provenance form (executable groups_ref);
2165
- // standard keeps the full grouping; s3c: ultrathin serves the aggregate
2166
- // form only (total + hoisted sha + groups_ref, group list elided).
2167
- manual_grounding: ultrathin
2168
- ? buildUltrathinGrounding(buildMinimalGrounding(groupManualGrounding(result)))
2169
- : detail === "minimal"
2170
- ? buildMinimalGrounding(groupManualGrounding(result))
2171
- : groupManualGrounding(result),
1995
+ manual_grounding: buildMinimalGrounding(groupManualGrounding(result)),
2172
1996
  regulatory_overlay: {
2173
1997
  frameworks: stripSource(result.regulatory_overlay.frameworks),
2174
1998
  obligations: stripSource(result.regulatory_overlay.obligations),
@@ -2176,45 +2000,73 @@ function applyStructuralDiet(result, detail, includeRelations) {
2176
2000
  playbooks: stripSource(result.regulatory_overlay.playbooks)
2177
2001
  },
2178
2002
  citations: invertCitationMap(result.citation_map),
2179
- // s3c: ultrathin trims the diagnostic text arrays to exact counts + ref.
2180
- completeness_report: ultrathin
2181
- ? trimCompletenessForUltrathin(completeness)
2182
- : completeness,
2183
- codegen_instructions_ref: instructionsRef,
2003
+ completeness_report: result.completeness_report,
2004
+ llm_codegen_instructions: result.llm_codegen_instructions,
2005
+ security_rationale_template: result.security_rationale_template,
2184
2006
  // s4: identical re-call is deterministic — point the client back at the
2185
- // context it already holds (full stays byte-identical: no hint there).
2186
- repeat_call_hint: REPEAT_CALL_HINT,
2007
+ // context it already holds.
2008
+ repeat_call_hint: { note_id: REPEAT_CALL_HINT_ID },
2187
2009
  provenance: result.provenance
2188
2010
  };
2189
- if (result.debug) {
2190
- // 0.20.0-beta.26 (§17-A, menor): a nota contava o cap CLÁSSICO (returned=25) mesmo
2191
- // quando o nível dietado devolvia 5 — o número que o consumidor lia não era o que
2192
- // recebeu. Passa a contar o efectivo, dizendo qual é o cap deste `detail`.
2193
- dieted.debug = {
2194
- ...result.debug,
2195
- notes: result.debug.notes.map((note) => note.startsWith("evidence_patterns: total=")
2196
- ? `evidence_patterns: total=${evidenceTotal} returned=${evidenceKept.length} capped=${evidenceCapped} (cap efectivo do detail="${detail}": ${evidenceCap}; cap clássico: ${EVIDENCE_PATTERN_CAP})`
2197
- : note)
2198
- };
2199
- }
2011
+ if (result.debug)
2012
+ dieted.debug = result.debug;
2200
2013
  return dieted;
2201
2014
  }
2015
+ /**
2016
+ * 0.21 §5 — o preço declarado. Duas passagens: a primeira mede com o campo a
2017
+ * zero, a segunda re-mede com os dígitos reais lá dentro, para que o número
2018
+ * anunciado seja o do payload QUE O CONSUMIDOR RECEBE (±1 token de
2019
+ * arredondamento, nunca mais). Régua = chars/4, a mesma da medição do §5.
2020
+ */
2021
+ const ENVELOPE_EXCEEDED_NOTE_ID = "prepare.size_estimate.envelope_exceeded"; // 0.21 §6-c: texto em src/serving/notes.ts → sbd://toe/notes/prepare.size_estimate.envelope_exceeded
2022
+ function withSizeEstimate(payload, detail) {
2023
+ const envelope = LEVEL_ENVELOPE_TK[detail];
2024
+ const declare = (est) => envelope === undefined
2025
+ ? est
2026
+ : {
2027
+ ...est,
2028
+ envelope_tk: envelope,
2029
+ within_envelope: est.approx_tokens <= envelope,
2030
+ ...(est.approx_tokens <= envelope ? {} : { note_id: ENVELOPE_EXCEEDED_NOTE_ID })
2031
+ };
2032
+ const first = estimateSize({ ...payload, size_estimate: declare({ chars: 0, approx_tokens: 0 }) });
2033
+ const second = estimateSize({ ...payload, size_estimate: declare(first) });
2034
+ return { ...payload, size_estimate: declare(second) };
2035
+ }
2202
2036
  export function handlePrepareCodegenContext(raw) {
2203
- // v2 token diet (s1/s2): `detail` and `include_relations` select the
2204
- // response ENCODING only — they are validated up-front and never influence
2205
- // activation/resolution.
2037
+ // `detail` and `include_relations` select the response ENCODING only —
2038
+ // they are validated up-front and never influence activation/resolution.
2206
2039
  const detail = parseDetail(raw);
2207
2040
  const includeRelations = parseIncludeRelations(raw);
2208
2041
  const result = prepareCodegenContextCore(raw);
2209
- const shaped = detail !== "full" && result.status === "ready_for_codegen"
2210
- ? applyStructuralDiet(result, detail, includeRelations)
2211
- : result;
2042
+ const shaped = result.status !== "ready_for_codegen"
2043
+ ? result
2044
+ : detail === "full"
2045
+ ? shapeFull(result, includeRelations)
2046
+ : applyStructuralDiet(result, detail, includeRelations);
2212
2047
  // RF-H: append the advisory band (status-aware, pure) around the deterministic result.
2213
- return { ...shaped, next: prepareCodegenAffordances(result.status, "citation_map" in result ? Object.keys(result.citation_map).filter((id) => /^[A-Z]{3}-\d{3}$/.test(id)) : []) };
2048
+ const withNext = { ...shaped, next: prepareCodegenAffordances(result.status, "citation_map" in result ? Object.keys(result.citation_map).filter((id) => /^[A-Z]{3}-\d{3}$/.test(id)) : []) };
2049
+ // 0.21 §5: every ready payload declares its price (full has no ceiling — it declares instead).
2050
+ return withNext.status === "ready_for_codegen" ? withSizeEstimate(withNext, detail) : withNext;
2214
2051
  }
2215
2052
  function prepareCodegenContextCore(raw) {
2216
2053
  const input = normalizeInput(raw);
2217
- const preGate = gateBeforeActivation(input);
2054
+ // 0.21 §6 — o `task` vs o contrato: em modo DECLARATIVO com declaração, o task é contexto
2055
+ // REGISTADO (task_role: recorded_context) e NÃO influencia o resultado — logo não pode
2056
+ // barrar a resposta (contagem de palavras, padrões de vagueza, tecnologia fora do âmbito).
2057
+ // O gate mantém-se onde o task é MOTOR: em `discover`, e em declarativo sem declaração
2058
+ // (onde a selecção responde needs_input de qualquer forma).
2059
+ const selectionModeEarly = raw.selection_mode === "discover" ? "discover" : "declarative";
2060
+ const structuralEarly = {
2061
+ chapters: Array.isArray(raw.chapters) ? raw.chapters.filter((x) => typeof x === "string" && x.length > 0) : [],
2062
+ categories: Array.isArray(raw.categories) ? raw.categories.filter((x) => typeof x === "string" && x.length > 0) : []
2063
+ };
2064
+ // Em declarativo o gate NUNCA corre: sem declaração a selecção responde needs_input a nomear
2065
+ // o vocabulário (o contrato), e uma declaração inerte (stack fora do vocabulário) é declarada
2066
+ // com os valores válidos — nunca um needs_clarification sobre o task, que não é motor aqui.
2067
+ void structuralEarly;
2068
+ const taskIsRecordedContext = selectionModeEarly === "declarative";
2069
+ const preGate = taskIsRecordedContext ? null : gateBeforeActivation(input);
2218
2070
  if (preGate && preGate.status !== "ready_for_codegen") {
2219
2071
  return blocked(input, raw, preGate.status, preGate.reasons, preGate.suggestions, [], { rejected: [], notes: [] });
2220
2072
  }
@@ -2225,11 +2077,19 @@ function prepareCodegenContextCore(raw) {
2225
2077
  const selectionMode = raw.selection_mode === "discover" ? "discover" : "declarative";
2226
2078
  const declaredTechnologies = normalizeDeclaredTechnologies(Array.isArray(raw.technologies) ? raw.technologies.filter((t) => typeof t === "string") : [], input.stack);
2227
2079
  const declarativeSelection = selectionMode !== "discover";
2080
+ // 0.21 §6 — forma B no prepare: chapters/categories declarados passam ao motor tal e qual,
2081
+ // e CONTAM como declaração (o lote de decomposição é uma chamada só com `categories`).
2082
+ const structural = {
2083
+ chapters: Array.isArray(raw.chapters) ? raw.chapters.filter((x) => typeof x === "string" && x.length > 0) : [],
2084
+ categories: Array.isArray(raw.categories) ? raw.categories.filter((x) => typeof x === "string" && x.length > 0) : []
2085
+ };
2228
2086
  const hasDeclaredActivator = input.concerns.length > 0 ||
2229
2087
  input.exposure !== undefined ||
2230
2088
  input.data_sensitivity !== undefined ||
2231
2089
  input.changed_files.length > 0 ||
2232
- declaredTechnologies.length > 0;
2090
+ declaredTechnologies.length > 0 ||
2091
+ structural.chapters.length > 0 ||
2092
+ structural.categories.length > 0;
2233
2093
  // P1-A (0.20.0-beta.22): a decisão de needs_input é UMA e vive no motor — indexada
2234
2094
  // à activação produzida, não à presença de campos. O prepare reage ao veredicto
2235
2095
  // (abaixo, depois de correr a selecção), em vez de ter a sua própria regra.
@@ -2253,10 +2113,17 @@ function prepareCodegenContextCore(raw) {
2253
2113
  void focusConcerns; // kept for the debug notes below; the gate no longer counts requirements
2254
2114
  // MP1 selection (G-mp1a O2): the engine composes baseline ∪ context and narrows
2255
2115
  // by the task's declared signals — this is the requirement set served.
2256
- const selection = runSelectionWithActivation(input, activation, selectionMode === "discover" ? (raw.technologies ?? []) : declaredTechnologies, selectionMode);
2116
+ const selection = runSelectionWithActivation(input, activation, selectionMode === "discover" ? (raw.technologies ?? []) : declaredTechnologies, selectionMode, structural);
2257
2117
  if (selection.needs_input) {
2258
2118
  const ni = selection.needs_input;
2259
- return blocked(input, raw, "needs_input", [
2119
+ const inert = (ni.inert_declarations ?? []).join(" ");
2120
+ const vocab = buildActivationVocabulary();
2121
+ const validValues = {
2122
+ ...(/\bstack=|\btechnologies=/.test(inert) ? { technologies: vocab.technologies.values.map((t) => String(t.value)) } : {}),
2123
+ ...(/\bexposure=/.test(inert) ? { exposure: vocab.exposure.values.map((e) => String(e.value)) } : {}),
2124
+ ...(/\bdata_sensitivity=/.test(inert) ? { data_sensitivity: vocab.data_sensitivity.values.map((d) => String(d.value)) } : {})
2125
+ };
2126
+ const blockedNeedsInput = blocked(input, raw, "needs_input", [
2260
2127
  ni.reason,
2261
2128
  "Contrato v1.18-beta: o servidor responde ao declarado e NÃO interpreta o `task` — que fica registado para auditoria."
2262
2129
  ], [
@@ -2268,6 +2135,8 @@ function prepareCodegenContextCore(raw) {
2268
2135
  ...(ni.inert_declarations?.length ? [`Declarações inertes nesta chamada: ${ni.inert_declarations.join("; ")}.`] : []),
2269
2136
  `Queres o comportamento inferencial antigo? selection_mode="discover" (exploratório).`
2270
2137
  ], activation.trace);
2138
+ blockedNeedsInput.needs_input = { ...ni, ...(Object.keys(validValues).length > 0 ? { valid_values: validValues } : {}) };
2139
+ return blockedNeedsInput;
2271
2140
  }
2272
2141
  const estimatedRequirements = selection.selected.length;
2273
2142
  // 0.19.4 («a promessa do minimal», lead opção 2): tecto de requisitos por-id
@@ -2278,40 +2147,81 @@ function prepareCodegenContextCore(raw) {
2278
2147
  const ceilingDetail = parseDetail(raw);
2279
2148
  const requirementCeiling = REQUIREMENT_CEILING_BY_DETAIL[ceilingDetail];
2280
2149
  if (requirementCeiling !== undefined && selection.selected.length > requirementCeiling) {
2150
+ // 0.21 §6 (condição da decisão (a)): lotes que SOMAM O TODO. Partição das categorias
2151
+ // activadas em lotes ≤ tecto (guloso por tamanho decrescente), cada lote uma declaração
2152
+ // ESTRUTURAL executável; technologies/changed_files preservados literalmente; a contagem
2153
+ // de cada lote é REAL (a selecção corre-se para o lote).
2281
2154
  const byCategory = new Map();
2282
2155
  for (const r of selection.selected)
2283
2156
  byCategory.set(r.category, (byCategory.get(r.category) ?? 0) + 1);
2284
- const remaining = new Set(byCategory.keys());
2285
- const batches = [];
2286
- while (remaining.size > 0 && batches.length < 3) {
2287
- let best = null;
2288
- let bestCats = [];
2289
- let bestWeight = 0;
2290
- for (const concern of VALID_CONCERNS) {
2291
- const cats = [...categoriesForConcerns([concern])].filter((c) => remaining.has(c));
2292
- const weight = cats.reduce((n, c) => n + (byCategory.get(c) ?? 0), 0);
2293
- if (weight > bestWeight) {
2294
- best = concern;
2295
- bestCats = cats;
2296
- bestWeight = weight;
2157
+ const categoriesDesc = [...byCategory.entries()].sort((a, b2) => b2[1] - a[1] || a[0].localeCompare(b2[0]));
2158
+ // As tecnologias preservadas em cada lote podem acrescentar requisitos por regra NOMEADA
2159
+ // (ex.: SES-008 por `jwt`) fora das categorias do lote — reserva-se essa margem na
2160
+ // capacidade de cada lote, para que a contagem REAL (abaixo) nunca exceda o tecto.
2161
+ const technologyExtras = declaredTechnologies.length > 0
2162
+ ? runSelectionWithActivation({ ...input, concerns: [], exposure: undefined, data_sensitivity: undefined, changed_files: [] }, { ...activation, concerns: [], sliceFamilies: [], trace: [], rejected: [], notes: [] }, declaredTechnologies, "declarative", { chapters: [], categories: [] }).selected.length
2163
+ : 0;
2164
+ const capacity = Math.max(1, requirementCeiling - technologyExtras);
2165
+ const bins = [];
2166
+ const binLoad = [];
2167
+ for (const [category, count] of categoriesDesc) {
2168
+ let placed = false;
2169
+ for (let i = 0; i < bins.length; i += 1) {
2170
+ if (binLoad[i] + count <= capacity) {
2171
+ bins[i].push(category);
2172
+ binLoad[i] += count;
2173
+ placed = true;
2174
+ break;
2297
2175
  }
2298
2176
  }
2299
- if (!best)
2300
- break;
2301
- batches.push({ concerns: [best], estimated_requirements: bestWeight });
2302
- for (const c of bestCats)
2303
- remaining.delete(c);
2177
+ if (!placed) {
2178
+ bins.push([category]);
2179
+ binLoad.push(count);
2180
+ }
2304
2181
  }
2182
+ const activatorConcerns = new Set([
2183
+ ...(input.exposure ? EXPOSURE_CONCERNS[input.exposure] ?? [] : []),
2184
+ ...(input.data_sensitivity ? SENSITIVITY_CONCERNS[input.data_sensitivity] ?? [] : [])
2185
+ ]);
2186
+ const concernsForCategory = (category) => [...new Set([...input.concerns, ...activation.concerns])].filter((c) => categoriesForConcerns([c]).has(category)).sort();
2187
+ const batchWith = (categories) => ({
2188
+ categories,
2189
+ ...(declaredTechnologies.length > 0 ? { technologies: [...declaredTechnologies] } : {}),
2190
+ ...(input.changed_files.length > 0 ? { changed_files: [...input.changed_files] } : {})
2191
+ });
2192
+ const union = new Set();
2193
+ const batches = bins.map((categories) => {
2194
+ const w = batchWith(categories);
2195
+ const run = runSelectionWithActivation({ ...input, concerns: [] }, { ...activation, concerns: [], sliceFamilies: [], trace: [], rejected: [], notes: [] }, w.technologies ?? [], "declarative", { chapters: [], categories });
2196
+ for (const r of run.selected)
2197
+ union.add(r.requirement_id);
2198
+ const concerns = [...new Set(categories.flatMap(concernsForCategory))].filter((c) => !activatorConcerns.has(c) || input.concerns.includes(c)).sort();
2199
+ return {
2200
+ with: w,
2201
+ requirements: run.selected.length,
2202
+ derived_from: {
2203
+ concerns,
2204
+ ...(input.exposure && categories.some((cat) => [...activatorConcerns].some((c) => (EXPOSURE_CONCERNS[input.exposure] ?? []).includes(c) && categoriesForConcerns([c]).has(cat))) ? { exposure: input.exposure } : {}),
2205
+ ...(input.data_sensitivity && categories.some((cat) => [...activatorConcerns].some((c) => (SENSITIVITY_CONCERNS[input.data_sensitivity] ?? []).includes(c) && categoriesForConcerns([c]).has(cat))) ? { data_sensitivity: input.data_sensitivity } : {})
2206
+ }
2207
+ };
2208
+ });
2209
+ const selectedIds = selection.selected.map((r) => r.requirement_id);
2210
+ const covered = selectedIds.filter((id) => union.has(id)).length;
2211
+ const recall = selectedIds.length === 0 ? 1 : covered / selectedIds.length;
2305
2212
  const projected = projectedCostTk(ceilingDetail, selection.selected.length) ?? 0;
2306
2213
  const b = blocked(input, raw, "needs_decomposition", [
2307
2214
  `Selecção de ${selection.selected.length} requisitos excede o tecto de ${requirementCeiling} para detail="${ceilingDetail}" ` +
2308
2215
  `(medição: ~${COST_PER_REQ_TK[ceilingDetail] ?? 0} tk/req sobre base ~${BASE_TK[ceilingDetail] ?? 0} tk ⇒ ~${projected} tk, ` +
2309
- `acima da promessa de ${PAYLOAD_PROMISE_TK[ceilingDetail] ?? 0} tk deste nível).`
2216
+ `acima do envelope de ${PAYLOAD_PROMISE_TK[ceilingDetail] ?? 0} tk deste nível).`
2310
2217
  ], [
2311
- "Divide por área — repete SÓ com task + risk_level + concerns do lote; os activadores largos (exposure/data_sensitivity/stack) ficam FORA da chamada do lote, porque concerns SOMAM activação, não restringem. Lotes (estimativas por área do pedido original): " +
2312
- batches.map((bt, i) => `${i + 1}) concerns=[${bt.concerns.map((c) => `"${c}"`).join(", ")}] (~${bt.estimated_requirements} reqs)`).join("; ") +
2313
- ". Categorias sem lote entram na chamada mais próxima.",
2314
- `Em alternativa usa detail="full" (sem tecto — payload completo, custo alto) ou reduz o âmbito da task.`
2218
+ `Divide em ${batches.length} lotes que SOMAM O TODO (união = ${union.size} ids, m_recall ${recall.toFixed(2)} face à selecção inteira): ` +
2219
+ "repete com task + risk_level + detail + `categories` do lote" +
2220
+ (declaredTechnologies.length > 0 || input.changed_files.length > 0 ? " (technologies/changed_files preservados em cada lote)" : "") +
2221
+ ". Cada lote é a partição EXACTA das categorias que a tua declaração activou — exposure/data_sensitivity estão lá pelo seu efeito (re-declará-los somaria as suas categorias a todos os lotes). Lotes: " +
2222
+ batches.map((bt, i) => `${i + 1}) categories=[${bt.with.categories.map((c) => `"${c}"`).join(", ")}] (${bt.requirements} reqs; de ${bt.derived_from.concerns.map((c) => `"${c}"`).join(", ") || "activadores"}${bt.derived_from.exposure ? `, exposure=${bt.derived_from.exposure}` : ""}${bt.derived_from.data_sensitivity ? `, data_sensitivity=${bt.derived_from.data_sensitivity}` : ""})`).join("; ") +
2223
+ ".",
2224
+ `Em alternativa usa detail="full" (sem tecto — preço declarado em size_estimate) ou reduz o âmbito da task.`
2315
2225
  ], activation.trace, input.debug ? { rejected: activation.rejected, notes: activation.notes } : undefined);
2316
2226
  b.requirement_ceiling = {
2317
2227
  detail: ceilingDetail,
@@ -2320,7 +2230,8 @@ function prepareCodegenContextCore(raw) {
2320
2230
  cost_per_req_tk: COST_PER_REQ_TK[ceilingDetail] ?? 0,
2321
2231
  projected_tk: projected,
2322
2232
  promise_tk: PAYLOAD_PROMISE_TK[ceilingDetail] ?? 0,
2323
- batches
2233
+ batches,
2234
+ union: { requirements: union.size, recall: Number(recall.toFixed(4)) }
2324
2235
  };
2325
2236
  return b;
2326
2237
  }
@@ -2393,67 +2304,74 @@ function prepareCodegenContextCore(raw) {
2393
2304
  });
2394
2305
  const directControlIds = new Set(v0.controls.filter((control) => control.confidence === "direct").map((control) => control.control_id));
2395
2306
  const derivedControlIds = new Set(v0.controls.filter((control) => control.confidence === "derived").map((control) => control.control_id));
2396
- const activeRequirementIdsForEvidence = new Set(v0.requirements.map((requirement) => requirement.requirement_id));
2397
- function projectEvidencePattern(pattern, relevanceScore) {
2398
- const projection = {
2399
- id: pattern.id,
2400
- relevance_score: relevanceScore,
2307
+ // ----- 0.21 §1: the fused requirement ---------------------------------
2308
+ // One object per requirement: the published description NEVER leaves, and the
2309
+ // requirement's own evidence pattern (1:1 in the bundle) is inlined as
2310
+ // verify/evidence. No cap, no join left to the model. Patterns that touched
2311
+ // the scope only through an activated CONTROL (their requirement is outside
2312
+ // the activated set) are NOT inlined — they belong to other requirements —
2313
+ // and are counted + referenced below (never silent).
2314
+ const activeRequirementIds = new Set(v0.requirements.map((r) => r.requirement_id));
2315
+ const patternByRequirement = new Map();
2316
+ for (const pattern of ontologyForSelection.evidencePatterns ?? []) {
2317
+ if (pattern.maps_to_requirement_id && !patternByRequirement.has(pattern.maps_to_requirement_id)) {
2318
+ patternByRequirement.set(pattern.maps_to_requirement_id, pattern);
2319
+ }
2320
+ }
2321
+ let withVerifyAndEvidence = 0;
2322
+ let partialPatterns = 0;
2323
+ let withoutPattern = 0;
2324
+ const fusedRequirements = v0.requirements.map((requirement) => {
2325
+ const pattern = patternByRequirement.get(requirement.requirement_id);
2326
+ const verify = pattern?.verification_logic;
2327
+ const evidence = pattern?.evidence_expectation;
2328
+ if (!pattern)
2329
+ withoutPattern += 1;
2330
+ else if (verify && evidence)
2331
+ withVerifyAndEvidence += 1;
2332
+ else
2333
+ partialPatterns += 1;
2334
+ return {
2335
+ id: requirement.requirement_id,
2336
+ name: requirement.name,
2337
+ ...(requirement.type ? { type: requirement.type } : {}),
2338
+ ...(categoryIsDerivable(requirement.requirement_id, requirement.category) ? {} : { category: requirement.category }),
2339
+ ...(requirement.description ? { description: requirement.description } : {}),
2340
+ ...(verify ? { verify } : {}),
2341
+ ...(evidence ? { evidence } : {}),
2401
2342
  source: "runtime_v0"
2402
2343
  };
2403
- if (pattern.maps_to_requirement_id)
2404
- projection.maps_to_requirement_id = pattern.maps_to_requirement_id;
2405
- if (pattern.maps_to_control_id)
2406
- projection.maps_to_control_id = pattern.maps_to_control_id;
2407
- if (pattern.evidence_expectation)
2408
- projection.evidence_expectation = pattern.evidence_expectation;
2409
- if (pattern.verification_logic)
2410
- projection.verification_logic = pattern.verification_logic;
2411
- if (pattern.expected_artifact_type_ids && pattern.expected_artifact_type_ids.length > 0) {
2412
- projection.expected_artifact_type_ids = pattern.expected_artifact_type_ids;
2413
- }
2414
- return projection;
2415
- }
2416
- /**
2417
- * 0.20.0-beta.26 (§17-A) — ORDENAÇÃO POR PERTENÇA AO ÂMBITO.
2418
- *
2419
- * A ordenação anterior dava 1.0 a qualquer EP ligado a um CONTROLO directo e só 0.7 ao
2420
- * EP ligado a um REQUISITO do âmbito activado: a pertença ao controlo ganhava à pertença
2421
- * ao requisito, e o desempate por id fazia o resto. Efeito medido: numa tarefa de
2422
- * validação (âmbito ERR/VAL) vinham 5 em 5 EPs de fora — EP-API-002/003/007, EP-AUT-010,
2423
- * EP-CFG-005 — e nem um EP-VAL/EP-ERR; em `auth` funcionava por SORTE ALFABÉTICA
2424
- * (ACC < API < AUT < CFG < ERR < VAL). Pior: em «exigir reautenticação» o `minimal`
2425
- * omitia EP-AUT-009, o padrão do requisito que a tarefa NOMEIA.
2426
- *
2427
- * Isto não é um modelo de relevância — é uma comparação de PERTENÇA, e é por isso que
2428
- * pode ser uma invariante testável: o requisito do âmbito activado vem primeiro, depois
2429
- * o controlo directo, depois o derivado, e o id só desempata dentro do mesmo escalão.
2430
- */
2431
- const scoredEvidencePatterns = v0.evidencePatterns.map((pattern) => {
2432
- let score = 0;
2433
- if (pattern.maps_to_requirement_id &&
2434
- activeRequirementIdsForEvidence.has(pattern.maps_to_requirement_id)) {
2435
- score = Math.max(score, 1.0);
2436
- }
2437
- if (pattern.maps_to_control_id &&
2438
- directControlIds.has(pattern.maps_to_control_id)) {
2439
- score = Math.max(score, 0.7);
2440
- }
2441
- if (pattern.maps_to_control_id &&
2442
- derivedControlIds.has(pattern.maps_to_control_id)) {
2443
- score = Math.max(score, 0.5);
2444
- }
2445
- return { pattern, score };
2446
2344
  });
2447
- scoredEvidencePatterns.sort((a, b) => b.score - a.score || a.pattern.id.localeCompare(b.pattern.id));
2448
- const keptEvidencePatterns = scoredEvidencePatterns.slice(0, EVIDENCE_PATTERN_CAP);
2449
- const cappedEvidencePatterns = scoredEvidencePatterns.slice(EVIDENCE_PATTERN_CAP);
2345
+ const relatedByControlOutsideScope = v0.evidencePatterns.filter((pattern) => !(pattern.maps_to_requirement_id && activeRequirementIds.has(pattern.maps_to_requirement_id))).length;
2346
+ const verificationCalls = Math.ceil(v0.requirements.length / 50);
2347
+ const riskForRef = input.risk_level ? `"${input.risk_level}"` : "<declara o risk_level>";
2348
+ const verification = {
2349
+ requirements: v0.requirements.length,
2350
+ with_verify_and_evidence: withVerifyAndEvidence,
2351
+ partial: partialPatterns,
2352
+ without_pattern: withoutPattern,
2353
+ by_ref: {
2354
+ tool: "get_sbd_toe_verification_matrix",
2355
+ with: `risk_level=${riskForRef}, requirement_ids=[activated_scope.requirements[].id] (≤50 por chamada)`,
2356
+ calls: verificationCalls,
2357
+ fields: ["evidence_pattern_id", "control_id", "expected_artifact_type_ids"],
2358
+ note_id: "prepare.verification.by_ref"
2359
+ },
2360
+ related_by_control_outside_scope: {
2361
+ count: relatedByControlOutsideScope,
2362
+ ref: {
2363
+ tool: "resolve_entities",
2364
+ with: 'record_type="evidence_pattern", filters={"maps_to_control_id":{"in":[activated_scope.controls[].control_id]}}',
2365
+ note_id: "prepare.verification.related_by_control_outside_scope"
2366
+ }
2367
+ }
2368
+ };
2450
2369
  const g2Context = {
2451
2370
  control_objectives: activatedCOs.map((entity) => projectV1Entity(entity, g2Data)),
2452
2371
  mechanisms: activatedMechanisms.map((entity) => projectV1Entity(entity, g2Data)),
2453
2372
  practices: activatedPractices.map((entity) => projectV1Entity(entity, g2Data)),
2454
2373
  artifacts: activatedArtifacts.map((entity) => projectV1Entity(entity, g2Data)),
2455
- relations: activatedRelations.map(projectRelation),
2456
- evidence_patterns: keptEvidencePatterns.map(({ pattern, score }) => projectEvidencePattern(pattern, score))
2374
+ relations: activatedRelations.map(projectRelation)
2457
2375
  };
2458
2376
  // ----- Manual grounding ----------------------------------------------
2459
2377
  const manualGrounding = [];
@@ -2477,20 +2395,17 @@ function prepareCodegenContextCore(raw) {
2477
2395
  }
2478
2396
  // ----- Activated scope projection ------------------------------------
2479
2397
  const activatedScope = {
2480
- requirements: v0.requirements.map((requirement) => ({
2481
- requirement_id: requirement.requirement_id,
2482
- name: requirement.name,
2483
- category: requirement.category,
2484
- type: requirement.type,
2485
- source: "runtime_v0"
2486
- })),
2398
+ requirements: fusedRequirements,
2399
+ // 0.21 §1: a description publicada dos controlos DIRECTOS vai em todos os
2400
+ // níveis, o full incluído («não promete caber, promete não faltar»).
2487
2401
  controls: v0.controls.map((control) => ({
2488
2402
  control_id: control.control_id,
2489
2403
  name: control.name,
2490
2404
  domain: control.domain,
2491
2405
  control_type: control.control_type,
2492
2406
  source: "runtime_v0",
2493
- confidence: control.confidence
2407
+ confidence: control.confidence,
2408
+ ...(control.confidence === "direct" && control.description ? { description: control.description } : {})
2494
2409
  })),
2495
2410
  slices: activatedSlices.map((slice) => ({
2496
2411
  slice_id: slice.slice_id,
@@ -2598,16 +2513,12 @@ function prepareCodegenContextCore(raw) {
2598
2513
  lexical_share: selection.basis_summary.lexical_share,
2599
2514
  narrowed_out_ref: {
2600
2515
  tool: "select_sbd_toe_requirements",
2601
- note: "Categorias elegíveis sem sinal na tarefa foram excluídas pelo narrowing MP1 — " +
2602
- "a lista completa (por categoria, com razão) vem de select_sbd_toe_requirements com o mesmo contexto."
2516
+ note_id: "prepare.selection.narrowed_out_ref"
2603
2517
  }
2604
2518
  },
2605
2519
  v1_consistency_mismatches: g2Data.consistency.mismatches,
2606
2520
  v1_manifest_warnings: g2Data.consistency.warnings,
2607
- evidence_patterns_total: scoredEvidencePatterns.length,
2608
- evidence_patterns_returned: keptEvidencePatterns.length,
2609
- evidence_patterns_capped: cappedEvidencePatterns.length,
2610
- evidence_pattern_cap: EVIDENCE_PATTERN_CAP
2521
+ verification
2611
2522
  };
2612
2523
  // ----- Build LLM instructions + rationale template -------------------
2613
2524
  const citedIds = Object.keys(citationMap);
@@ -2618,12 +2529,33 @@ function prepareCodegenContextCore(raw) {
2618
2529
  riskLevel: input.risk_level
2619
2530
  });
2620
2531
  const security_rationale_template = buildSecurityRationaleTemplate(input.taskTrimmed);
2532
+ // ----- 0.21 §2: adjacência declarada -----------------------------------
2533
+ // Relativa à DECLARAÇÃO tal como o chamador a fez (aritmética sobre o vocabulário, nunca
2534
+ // leitura da tarefa); o módulo aplica risk_level L2 quando omitido.
2535
+ const adjacencyBase = {
2536
+ risk_level: input.risk_level ?? "L2",
2537
+ ...(input.concerns.length > 0 ? { concerns: [...input.concerns] } : {}),
2538
+ ...(input.exposure !== undefined ? { exposure: input.exposure } : {}),
2539
+ ...(input.data_sensitivity !== undefined ? { data_sensitivity: input.data_sensitivity } : {}),
2540
+ ...(declaredTechnologies.length > 0 ? { technologies: [...declaredTechnologies] } : {}),
2541
+ ...(input.changed_files.length > 0 ? { changed_files: [...input.changed_files] } : {})
2542
+ };
2543
+ const adjacencySummary = buildDeclaredAdjacency(adjacencyBase);
2544
+ const adjacency = {
2545
+ undeclared_that_would_change_the_set: adjacencySummary.undeclared_that_would_change_the_set,
2546
+ scanned: adjacencySummary.scanned,
2547
+ would_change_the_set: adjacencySummary.would_change_the_set,
2548
+ shown: adjacencySummary.shown,
2549
+ detail: declaredAdjacencyDetail(adjacencyBase)
2550
+ };
2621
2551
  const result = {
2622
2552
  status: "ready_for_codegen",
2553
+ notes: NOTES_HEADER,
2623
2554
  mode: input.mode,
2624
2555
  input_echo: inputEcho(raw),
2625
2556
  activation_trace: activation.trace,
2626
2557
  activated_scope: activatedScope,
2558
+ adjacency,
2627
2559
  g2_context: g2Context,
2628
2560
  manual_grounding: manualGrounding,
2629
2561
  regulatory_overlay: overlayResolution.context,
@@ -2642,23 +2574,15 @@ function prepareCodegenContextCore(raw) {
2642
2574
  }
2643
2575
  };
2644
2576
  if (input.debug) {
2645
- const cappedEntries = cappedEvidencePatterns.map(({ pattern, score }) => ({
2646
- source: "scope_gate",
2647
- produced: pattern.id,
2648
- trigger: pattern.maps_to_control_id ?? pattern.maps_to_requirement_id ?? "<no anchor>",
2649
- score,
2650
- confidence: "deterministic",
2651
- reason: `Evidence pattern dropped by the scope-membership cap (cap=${EVIDENCE_PATTERN_CAP}); within a membership tier the order is by id, not by relevance.`
2652
- }));
2653
2577
  result.debug = {
2654
- rejected_candidates: [...activation.rejected, ...cappedEntries],
2578
+ rejected_candidates: activation.rejected,
2655
2579
  notes: [
2656
2580
  ...activation.notes,
2657
2581
  `concerns: ${activation.concerns.join(", ") || "(none)"}`,
2658
2582
  `slice_families: ${activation.sliceFamilies.join(", ") || "(none)"}`,
2659
2583
  `overlay_status: ${overlayResolution.status}`,
2660
2584
  `estimated_v0_requirements: ${estimatedRequirements}`,
2661
- `evidence_patterns: total=${scoredEvidencePatterns.length} returned=${keptEvidencePatterns.length} capped=${cappedEvidencePatterns.length}`
2585
+ `verification: requirements=${verification.requirements} with_verify_and_evidence=${verification.with_verify_and_evidence} partial=${verification.partial} without_pattern=${verification.without_pattern} related_by_control_outside_scope=${verification.related_by_control_outside_scope.count}`
2662
2586
  ]
2663
2587
  };
2664
2588
  }