@c4a/context 0.7.5 → 0.7.8

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 (96) hide show
  1. package/README.md +12 -4
  2. package/README.zh-CN.md +11 -4
  3. package/docs/README.md +13 -1
  4. package/docs/README.zh-CN.md +13 -1
  5. package/docs/getting-started.md +95 -69
  6. package/docs/guides/agent-dialogue.md +19 -9
  7. package/docs/guides/agent-guide.md +42 -10
  8. package/docs/guides/code-indexer-skill-authoring.md +42 -11
  9. package/docs/guides/indexer-manifest-example.md +103 -0
  10. package/docs/guides/indexer-provider-and-customization.md +277 -13
  11. package/docs/guides/indexer-skill-creation.md +99 -0
  12. package/docs/guides/knowledge-updates.md +324 -0
  13. package/docs/guides/lark-resources.md +5 -1
  14. package/docs/guides/markdown-indexer-skill-authoring.md +16 -7
  15. package/docs/guides/note.md +37 -0
  16. package/docs/guides/package-outputs.md +22 -17
  17. package/docs/guides/sessions.md +50 -0
  18. package/docs/guides/workspace-commit.md +45 -0
  19. package/docs/guides/workspace-prepare.md +72 -0
  20. package/docs/guides/workspace-restore.md +59 -0
  21. package/docs/reference/code-extractors.md +23 -11
  22. package/docs/reference/indexer-provider-protocol.md +116 -22
  23. package/docs/reference/package-templates.md +10 -9
  24. package/docs/reference/project-api.md +47 -13
  25. package/docs/reference/template-variables.md +7 -7
  26. package/index.d.ts +11 -0
  27. package/index.js +1560 -572
  28. package/indexerAgentStepProtocol.d.ts +44 -0
  29. package/indexerApprovedKnowledge.d.ts +371 -0
  30. package/indexerArticlePlan.d.ts +83 -0
  31. package/indexerArtifact.d.ts +10 -7
  32. package/indexerArtifactDependencies.d.ts +5 -5
  33. package/indexerArtifactPolicy.d.ts +16 -16
  34. package/indexerArtifactResult.d.ts +76 -69
  35. package/indexerAuthoringFixture.d.ts +8 -8
  36. package/indexerAuthorizedWorksetView.d.ts +14 -14
  37. package/indexerBaseQuestionAmendment.d.ts +40 -0
  38. package/indexerCandidateCompile.d.ts +46 -36
  39. package/indexerCatalogFallback.d.ts +566 -48
  40. package/indexerContentLayers.d.ts +6 -4
  41. package/indexerContractDeclaration.d.ts +3 -0
  42. package/indexerControlledProgram.d.ts +1039 -238
  43. package/indexerCustomizationDraft.d.ts +188 -0
  44. package/indexerDependencyView.d.ts +17 -17
  45. package/indexerEffectiveArtifact.d.ts +26 -15
  46. package/indexerExampleFactDependencies.d.ts +17 -0
  47. package/indexerExampleIdentityAudit.d.ts +2 -2
  48. package/indexerInventoryDisposition.d.ts +44 -44
  49. package/indexerKnowledgeDependency.d.ts +46 -0
  50. package/indexerLayerComposition.d.ts +92 -54
  51. package/indexerLayoutChange.d.ts +8 -8
  52. package/indexerLayoutProposalSet.d.ts +15 -10
  53. package/indexerLayoutResolver.d.ts +15 -6
  54. package/indexerLayoutTransition.d.ts +8 -8
  55. package/indexerLifecycle.d.ts +1 -1
  56. package/indexerMainRunLedger.d.ts +3 -0
  57. package/indexerMainRunProtocol.d.ts +872 -196
  58. package/indexerMainWorkset.d.ts +50 -0
  59. package/indexerNavigationArtifactPlan.d.ts +2 -2
  60. package/indexerOverlayQuestionAmendment.d.ts +56 -16
  61. package/indexerOverlayQuestionApplyProposal.d.ts +98 -26
  62. package/indexerPartitionPlan.d.ts +585 -40
  63. package/indexerPhysicalArtifactAudit.d.ts +2 -2
  64. package/indexerPhysicalArtifactManifest.d.ts +24 -24
  65. package/indexerPostAuthorRunLedger.d.ts +60 -34
  66. package/indexerPrimaryProjection.d.ts +2 -2
  67. package/indexerProfileContract.d.ts +28 -28
  68. package/indexerProgramRunProtocol.d.ts +868 -194
  69. package/indexerProjectProposal.d.ts +36 -8
  70. package/indexerProjectedArtifactFanOutAudit.d.ts +2 -2
  71. package/indexerProvider.d.ts +72 -28
  72. package/indexerProviderComposition.d.ts +4 -4
  73. package/indexerProviderRouting.d.ts +52 -0
  74. package/indexerProviderSelectionProposal.d.ts +48 -0
  75. package/indexerPublicContractFacts.d.ts +7 -0
  76. package/indexerPublicContractTable.d.ts +11 -0
  77. package/indexerReaderTargetInventory.d.ts +6 -6
  78. package/indexerReferenceOnlyAudit.d.ts +2 -2
  79. package/indexerRegistry.d.ts +52 -0
  80. package/indexerRequirementConfirmation.d.ts +48 -16
  81. package/indexerRequirementLifecycle.d.ts +154 -42
  82. package/indexerResultReconciliation.d.ts +12 -11
  83. package/indexerSemanticInput.d.ts +27522 -3471
  84. package/{indexerGeneratedAuthoringAudit.d.ts → indexerStructuredClaims.d.ts} +0 -84
  85. package/indexerStructuredDeclaration.d.ts +8 -8
  86. package/indexerTemplateRendering.d.ts +7 -7
  87. package/indexerToolSnapshot.d.ts +16 -16
  88. package/managedSources.d.ts +15 -0
  89. package/package.json +1 -1
  90. package/phases.d.ts +0 -3
  91. package/processedScopes.d.ts +75 -0
  92. package/readingStructure.d.ts +188 -0
  93. package/sessionMetadata.d.ts +49 -0
  94. package/sources.d.ts +9 -3
  95. package/templates/package-templates/kb/skills/knowledge-query/SKILL.md +15 -10
  96. package/templates/package-templates.zh-CN/kb/skills/knowledge-query/SKILL.md +8 -8
package/index.js CHANGED
@@ -892,14 +892,14 @@ var require_foldFlowLines = __commonJS((exports) => {
892
892
  var FOLD_FLOW = "flow";
893
893
  var FOLD_BLOCK = "block";
894
894
  var FOLD_QUOTED = "quoted";
895
- function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) {
895
+ function foldFlowLines(text2, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) {
896
896
  if (!lineWidth || lineWidth < 0)
897
- return text;
897
+ return text2;
898
898
  if (lineWidth < minContentWidth)
899
899
  minContentWidth = 0;
900
900
  const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);
901
- if (text.length <= endStep)
902
- return text;
901
+ if (text2.length <= endStep)
902
+ return text2;
903
903
  const folds = [];
904
904
  const escapedFolds = {};
905
905
  let end = lineWidth - indent.length;
@@ -916,14 +916,14 @@ var require_foldFlowLines = __commonJS((exports) => {
916
916
  let escStart = -1;
917
917
  let escEnd = -1;
918
918
  if (mode === FOLD_BLOCK) {
919
- i = consumeMoreIndentedLines(text, i, indent.length);
919
+ i = consumeMoreIndentedLines(text2, i, indent.length);
920
920
  if (i !== -1)
921
921
  end = i + endStep;
922
922
  }
923
- for (let ch;ch = text[i += 1]; ) {
923
+ for (let ch;ch = text2[i += 1]; ) {
924
924
  if (mode === FOLD_QUOTED && ch === "\\") {
925
925
  escStart = i;
926
- switch (text[i + 1]) {
926
+ switch (text2[i + 1]) {
927
927
  case "x":
928
928
  i += 3;
929
929
  break;
@@ -941,13 +941,13 @@ var require_foldFlowLines = __commonJS((exports) => {
941
941
  if (ch === `
942
942
  `) {
943
943
  if (mode === FOLD_BLOCK)
944
- i = consumeMoreIndentedLines(text, i, indent.length);
944
+ i = consumeMoreIndentedLines(text2, i, indent.length);
945
945
  end = i + indent.length + endStep;
946
946
  split = undefined;
947
947
  } else {
948
948
  if (ch === " " && prev && prev !== " " && prev !== `
949
949
  ` && prev !== "\t") {
950
- const next = text[i + 1];
950
+ const next = text2[i + 1];
951
951
  if (next && next !== " " && next !== `
952
952
  ` && next !== "\t")
953
953
  split = i;
@@ -960,12 +960,12 @@ var require_foldFlowLines = __commonJS((exports) => {
960
960
  } else if (mode === FOLD_QUOTED) {
961
961
  while (prev === " " || prev === "\t") {
962
962
  prev = ch;
963
- ch = text[i += 1];
963
+ ch = text2[i += 1];
964
964
  overflow = true;
965
965
  }
966
966
  const j = i > escEnd + 1 ? i - 2 : escStart - 1;
967
967
  if (escapedFolds[j])
968
- return text;
968
+ return text2;
969
969
  folds.push(j);
970
970
  escapedFolds[j] = true;
971
971
  end = j + endStep;
@@ -980,40 +980,40 @@ var require_foldFlowLines = __commonJS((exports) => {
980
980
  if (overflow && onOverflow)
981
981
  onOverflow();
982
982
  if (folds.length === 0)
983
- return text;
983
+ return text2;
984
984
  if (onFold)
985
985
  onFold();
986
- let res = text.slice(0, folds[0]);
986
+ let res = text2.slice(0, folds[0]);
987
987
  for (let i2 = 0;i2 < folds.length; ++i2) {
988
988
  const fold = folds[i2];
989
- const end2 = folds[i2 + 1] || text.length;
989
+ const end2 = folds[i2 + 1] || text2.length;
990
990
  if (fold === 0)
991
991
  res = `
992
- ${indent}${text.slice(0, end2)}`;
992
+ ${indent}${text2.slice(0, end2)}`;
993
993
  else {
994
994
  if (mode === FOLD_QUOTED && escapedFolds[fold])
995
- res += `${text[fold]}\\`;
995
+ res += `${text2[fold]}\\`;
996
996
  res += `
997
- ${indent}${text.slice(fold + 1, end2)}`;
997
+ ${indent}${text2.slice(fold + 1, end2)}`;
998
998
  }
999
999
  }
1000
1000
  return res;
1001
1001
  }
1002
- function consumeMoreIndentedLines(text, i, indent) {
1002
+ function consumeMoreIndentedLines(text2, i, indent) {
1003
1003
  let end = i;
1004
1004
  let start = i + 1;
1005
- let ch = text[start];
1005
+ let ch = text2[start];
1006
1006
  while (ch === " " || ch === "\t") {
1007
1007
  if (i < start + indent) {
1008
- ch = text[++i];
1008
+ ch = text2[++i];
1009
1009
  } else {
1010
1010
  do {
1011
- ch = text[++i];
1011
+ ch = text2[++i];
1012
1012
  } while (ch && ch !== `
1013
1013
  `);
1014
1014
  end = i;
1015
1015
  start = i + 1;
1016
- ch = text[start];
1016
+ ch = text2[start];
1017
1017
  }
1018
1018
  }
1019
1019
  return end;
@@ -10994,7 +10994,7 @@ var indexerIdSchema = exports_external.string().regex(/^[a-z0-9][a-z0-9._/-]*$/u
10994
10994
  var indexerSnakeCaseIdSchema = exports_external.string().regex(/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/u);
10995
10995
  var indexerSemverSchema = exports_external.string().regex(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u);
10996
10996
  var indexerProtocolIdSchema = exports_external.string().regex(/^[a-z][a-z0-9.-]*(?:\.[a-z][a-z0-9.-]*)*\/v[1-9]\d*$/u);
10997
- var indexerCanonicalRefSchema = exports_external.string().regex(/^[a-z][a-z0-9.-]*:[A-Za-z0-9][A-Za-z0-9._~:/#@+-]*$/u);
10997
+ var indexerCanonicalRefSchema = exports_external.string().regex(/^[a-z][a-z0-9.-]*:[\p{L}\p{N}][\p{L}\p{N}._~:/#@+-]*$/u);
10998
10998
  var indexerProviderLayerRefSchema = indexerCanonicalRefSchema.refine((value) => !value.includes("#composer:"), "Provider layer ref cannot contain a composer suffix");
10999
10999
  var indexerComposerRefSchema = indexerCanonicalRefSchema.refine((value) => /#composer:[a-z0-9][a-z0-9._/-]*$/u.test(value), "composer ref must end with #composer:<id>");
11000
11000
  function isPortableIndexerPath(value) {
@@ -11052,6 +11052,278 @@ function addDuplicateIssues(values, context, field) {
11052
11052
  seen.add(value);
11053
11053
  });
11054
11054
  }
11055
+ // src/indexerPublicContractFacts.ts
11056
+ function record(value) {
11057
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
11058
+ }
11059
+ function propsName(value) {
11060
+ if (typeof value.propsType === "string" && /^[A-Za-z_$][\w$]*$/u.test(value.propsType))
11061
+ return value.propsType;
11062
+ return typeof value.typeAnnotation === "string" ? /^(?:React\.)?(?:FC|FunctionComponent)\s*<\s*([A-Za-z_$][\w$]*)\s*>$/u.exec(value.typeAnnotation)?.[1] : undefined;
11063
+ }
11064
+ function publicContractSupport(selected, available) {
11065
+ const refs = new Set(selected.map((fact) => fact.fact_ref));
11066
+ return available.filter((fact) => {
11067
+ if (refs.has(fact.fact_ref))
11068
+ return false;
11069
+ const value = record(fact.value);
11070
+ if (value?.kind !== "component" || value.visibility !== "exported" || !Array.isArray(value.members) || !value.members.length)
11071
+ return false;
11072
+ const name = propsName(value);
11073
+ if (!name)
11074
+ return false;
11075
+ return typeof value.file === "string" && selected.filter((target) => {
11076
+ const type = record(target.value);
11077
+ return type?.name === name && type.file === value.file && type.visibility === "exported" && (type.kind === "type" || type.kind === "interface") && Array.isArray(type.members) && target.subject_key.namespace === fact.subject_key.namespace && target.subject_key.kind === fact.subject_key.kind && target.subject_key.local_key === fact.subject_key.local_key;
11078
+ }).length === 1;
11079
+ }).sort((left, right) => compareIndexerCanonicalText(left.fact_ref, right.fact_ref));
11080
+ }
11081
+ function reconcilePublicContractFacts(facts) {
11082
+ const owners = new Map;
11083
+ const types2 = new Map;
11084
+ for (const component of facts) {
11085
+ const value = record(component.value);
11086
+ if (value?.kind !== "component" || value.visibility !== "exported" || !Array.isArray(value.members) || !value.members.length)
11087
+ continue;
11088
+ const name = propsName(value);
11089
+ if (!name || typeof value.file !== "string")
11090
+ continue;
11091
+ const matches = facts.filter((fact) => {
11092
+ const type2 = record(fact.value);
11093
+ return type2?.name === name && type2.file === value.file && type2.visibility === "exported" && (type2.kind === "type" || type2.kind === "interface") && Array.isArray(type2.members) && fact.subject_key.namespace === component.subject_key.namespace && fact.subject_key.kind === component.subject_key.kind && fact.subject_key.local_key === component.subject_key.local_key;
11094
+ });
11095
+ if (matches.length !== 1)
11096
+ continue;
11097
+ const type = matches[0];
11098
+ types2.set(component.fact_ref, type);
11099
+ owners.set(type.fact_ref, [...owners.get(type.fact_ref) ?? [], component]);
11100
+ }
11101
+ return facts.flatMap((fact) => {
11102
+ if (owners.has(fact.fact_ref))
11103
+ return [];
11104
+ const value = record(fact.value);
11105
+ const typeFact = types2.get(fact.fact_ref);
11106
+ if (!value || !typeFact)
11107
+ return [fact];
11108
+ const type = record(typeFact.value);
11109
+ const implementations = new Map(value.members.flatMap((item) => {
11110
+ const member = record(item);
11111
+ return typeof member?.name === "string" ? [[member.name, member]] : [];
11112
+ }));
11113
+ const members = type.members.map((item) => {
11114
+ const declaration = record(item);
11115
+ if (!declaration || typeof declaration.name !== "string")
11116
+ return item;
11117
+ const member = implementations.get(declaration.name);
11118
+ implementations.delete(declaration.name);
11119
+ if (!member)
11120
+ return item;
11121
+ const conflict = declaration.defaultValue !== undefined && member.defaultValue !== undefined && declaration.defaultValue !== member.defaultValue;
11122
+ return {
11123
+ ...member,
11124
+ ...declaration,
11125
+ ...member.defaultValue === undefined ? {} : { defaultValue: member.defaultValue },
11126
+ doc: [
11127
+ declaration.doc || member.doc,
11128
+ conflict ? `Default for ${String(value.name)}; declaration documents ${String(declaration.defaultValue)}.` : ""
11129
+ ].filter(Boolean).join(" ")
11130
+ };
11131
+ });
11132
+ members.push(...implementations.values());
11133
+ const name = owners.get(typeFact.fact_ref).length === 1 ? String(type.name) : `${String(type.name)} (${String(value.name)})`;
11134
+ return [
11135
+ { ...fact, value: { ...value, members: [], params: [] } },
11136
+ { ...typeFact, fact_ref: fact.fact_ref, value: { ...type, name, members } }
11137
+ ];
11138
+ });
11139
+ }
11140
+
11141
+ // src/indexerContractDeclaration.ts
11142
+ function compactContractDeclaration(raw, rows) {
11143
+ const normalize = (text) => text.replace(/\s+/gu, " ").trim();
11144
+ const notes = rows.map((row) => row[5] ?? "");
11145
+ let declaration = "";
11146
+ let plain = "";
11147
+ const flush = () => {
11148
+ declaration += plain.replace(/[ \t]*(?:\r?\n[ \t]*)+/gu, (space) => (space.includes(`\r
11149
+ `) ? `\r
11150
+ ` : `
11151
+ `) + (/[ \t]*$/u.exec(space)?.[0] ?? ""));
11152
+ plain = "";
11153
+ };
11154
+ for (let i = 0;i < raw.length; ) {
11155
+ const quote = raw[i];
11156
+ if (quote === '"' || quote === "'" || quote === "`") {
11157
+ const start = i++;
11158
+ while (i < raw.length) {
11159
+ if (raw[i] === "\\") {
11160
+ i += 2;
11161
+ continue;
11162
+ }
11163
+ if (raw[i++] === quote)
11164
+ break;
11165
+ }
11166
+ flush();
11167
+ declaration += raw.slice(start, i);
11168
+ } else if (raw.startsWith("//", i)) {
11169
+ const end = raw.indexOf(`
11170
+ `, i);
11171
+ const next = end < 0 ? raw.length : end;
11172
+ flush();
11173
+ declaration += raw.slice(i, next);
11174
+ i = next;
11175
+ } else if (raw.startsWith("/*", i)) {
11176
+ const end = raw.indexOf("*/", i + 2);
11177
+ if (end < 0) {
11178
+ flush();
11179
+ declaration += raw.slice(i);
11180
+ break;
11181
+ }
11182
+ const comment = raw.slice(i, end + 2);
11183
+ const body = comment.slice(2, -2).replace(/^\s*\* ?/gmu, "").trim();
11184
+ const prose = normalize(body.split(/@\w/u)[0] ?? "");
11185
+ const tags = [...body.matchAll(/@(\w+)/gu)].map((match) => match[1]);
11186
+ const duplicate = prose.length > 0 && notes.some((note) => normalize(note).includes(prose)) && tags.every((tag) => tag === "i18n" || (tag === "default" || tag === "defaultValue") && rows.some((row) => row[4] !== "unknown" && new RegExp(`@${tag}\\s+${row[4].replace(/[.*+?^${}()|[\]\\]/gu, "\\$&")}(?:\\s|$)`, "u").test(body)));
11187
+ if (duplicate)
11188
+ plain += " ";
11189
+ else {
11190
+ flush();
11191
+ declaration += comment;
11192
+ }
11193
+ i = end + 2;
11194
+ } else {
11195
+ plain += raw[i++];
11196
+ }
11197
+ }
11198
+ flush();
11199
+ declaration = declaration.trim();
11200
+ if (/^\{[^{}]*\}$/u.test(declaration) && !declaration.includes("/*") && !declaration.includes("//")) {
11201
+ const fields = declaration.slice(1, -1).split(";").map((item) => item.trim()).filter(Boolean);
11202
+ if (fields.length > 0 && fields.every((field) => {
11203
+ const match = /^(readonly\s+)?([\w$]+)(\?)?\s*:\s*(.+)$/su.exec(field);
11204
+ return match !== null && rows.some((row) => row[1] === match[2] && row[2].trim() === match[4].trim() && row[3] === (match[3] ? "optional" : "required") && (!match[1] || row[5]?.includes("readonly")));
11205
+ }))
11206
+ return;
11207
+ }
11208
+ return declaration;
11209
+ }
11210
+
11211
+ // src/indexerPublicContractTable.ts
11212
+ function record2(value) {
11213
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
11214
+ }
11215
+ var text = (value) => typeof value === "string" ? value : "";
11216
+ function projectIndexerPublicContractTable(fact) {
11217
+ const value = record2(fact.value);
11218
+ if (value === undefined)
11219
+ return;
11220
+ const rows = [];
11221
+ const add = (field, owner2) => {
11222
+ rows.push([
11223
+ owner2,
11224
+ text(field.name),
11225
+ text(field.typeAnnotation ?? field.type ?? field.signature),
11226
+ field.optional === true ? "optional" : field.optional === false ? "required" : "not declared",
11227
+ field.defaultValue === undefined ? "unknown" : typeof field.defaultValue === "string" ? field.defaultValue : JSON.stringify(field.defaultValue),
11228
+ [
11229
+ field.readonly === true ? "readonly" : "",
11230
+ field.rest === true ? "rest" : "",
11231
+ text(field.location),
11232
+ field.number === undefined ? "" : `field ${String(field.number)}`,
11233
+ field.repeated === true ? "repeated" : "",
11234
+ text(field.oneof),
11235
+ text(field.doc ?? field.description),
11236
+ field.constraints === undefined ? "" : JSON.stringify(field.constraints)
11237
+ ].filter(Boolean).join("; ")
11238
+ ]);
11239
+ if (Array.isArray(field.fields))
11240
+ for (const item of field.fields) {
11241
+ const child = record2(item);
11242
+ if (child !== undefined)
11243
+ add(child, `${owner2}.${text(field.name)}`);
11244
+ }
11245
+ };
11246
+ const owner = text(value.name ?? value.qualifiedName);
11247
+ const hasMembers = Array.isArray(value.members) && value.members.length > 0;
11248
+ if (!hasMembers && value.kind !== "component" && (typeof value.typeAnnotation === "string" || typeof value.initializer === "string")) {
11249
+ rows.push([owner, "declaration", [text(value.typeAnnotation), typeof value.initializer === "string" ? `= ${value.initializer}` : ""].filter(Boolean).join(" "), "", "", ""]);
11250
+ }
11251
+ const registration = record2(value.registration);
11252
+ if (registration !== undefined)
11253
+ rows.push([
11254
+ text(registration.kind),
11255
+ text(registration.key),
11256
+ text(registration.handler),
11257
+ "",
11258
+ "",
11259
+ [
11260
+ text(registration.method),
11261
+ Array.isArray(registration.middleware) ? registration.middleware.map(String).join(" → ") : ""
11262
+ ].filter(Boolean).join("; ")
11263
+ ]);
11264
+ if (Array.isArray(value.members))
11265
+ for (const member of value.members) {
11266
+ const field = record2(member);
11267
+ if (field === undefined)
11268
+ continue;
11269
+ const exportedTypeMember = value.visibility === "exported" && (value.kind === "type" || value.kind === "interface") && (field.kind === "prop" || field.kind === "method");
11270
+ const hidden = field.visibility === "private" || field.visibility === "protected" || /(?:^|\s)@(internal|private|protected)\b/u.test(text(field.doc));
11271
+ if (!hidden && (field.visibility !== "internal" || exportedTypeMember))
11272
+ add(field, owner);
11273
+ }
11274
+ if (Array.isArray(value.params) && value.kind !== "component")
11275
+ for (const parameter of value.params) {
11276
+ const field = record2(parameter);
11277
+ if (field !== undefined)
11278
+ add(field, owner);
11279
+ }
11280
+ if (Array.isArray(value.fields))
11281
+ for (const member of value.fields) {
11282
+ const field = record2(member);
11283
+ if (field !== undefined)
11284
+ add(field, owner);
11285
+ }
11286
+ if (Array.isArray(value.throws))
11287
+ for (const item of value.throws) {
11288
+ const field = record2(item);
11289
+ if (field !== undefined)
11290
+ add(field, `${owner} throws`);
11291
+ }
11292
+ for (const [key, label] of [["input_type", "request"], ["output_type", "response"], ["return_type", "return"]]) {
11293
+ if (typeof value[key] === "string")
11294
+ rows.push([owner, label, value[key], "", "", [
11295
+ key === "input_type" && value.client_streaming === true ? "client streaming" : "",
11296
+ key === "output_type" && value.server_streaming === true ? "server streaming" : "",
11297
+ value.oneway === true ? "oneway" : ""
11298
+ ].filter(Boolean).join("; ")]);
11299
+ }
11300
+ if (Array.isArray(value.overloads))
11301
+ for (const signature of value.overloads) {
11302
+ if (typeof signature === "string")
11303
+ rows.push([owner, "signature", signature, "", "", ""]);
11304
+ }
11305
+ else if (typeof value.signature === "string")
11306
+ rows.push([owner, "signature", value.signature, "", "", ""]);
11307
+ if (Array.isArray(value.publicEntrypoints))
11308
+ for (const entry of value.publicEntrypoints) {
11309
+ if (typeof entry === "string")
11310
+ rows.push([owner, "export entry", entry, "", "", ""]);
11311
+ }
11312
+ if (typeof value.handler === "string" && (typeof value.path === "string" || typeof value.method === "string")) {
11313
+ rows.push([text(value.method), text(value.path), value.handler, "", "", Array.isArray(value.middleware) ? value.middleware.map(String).join(" → ") : ""]);
11314
+ }
11315
+ if (rows.length === 0)
11316
+ return;
11317
+ const declaration = (hasMembers || value.kind === "component") && typeof value.typeAnnotation === "string" ? compactContractDeclaration(value.typeAnnotation, rows) : undefined;
11318
+ const redundantComponent = value.kind === "component" && value.contractResolution !== "declaration-only" && hasMembers && typeof value.propsType === "string" && [value.propsType, `FC<${value.propsType}>`, `React.FC<${value.propsType}>`].includes(declaration ?? "");
11319
+ return {
11320
+ columns: ["Contract", "Name", "Declaration", "Required", "Default", "Notes"],
11321
+ rows,
11322
+ declaration_status: redundantComponent ? "component-wrapper" : declaration !== undefined ? "retained" : typeof value.typeAnnotation === "string" && hasMembers ? "table-complete" : "not-provided",
11323
+ ...declaration !== undefined && !redundantComponent ? { declaration, declarationName: owner } : {}
11324
+ };
11325
+ }
11326
+
11055
11327
  // src/indexerSubjectIdentity.ts
11056
11328
  var normalizedSubjectFieldSchema = exports_external.string().min(1).refine((value) => value.normalize("NFC") === value, "SubjectKey fields must use Unicode NFC normalization");
11057
11329
  var indexerSubjectKeySchema = exports_external.object({
@@ -11084,6 +11356,8 @@ var indexerArtifactFactSchema = exports_external.object({
11084
11356
  var indexerDeterministicBlockRendererSchema = exports_external.enum([
11085
11357
  "bullet-list",
11086
11358
  "key-value-table",
11359
+ "multi-column-table",
11360
+ "public-contract-table",
11087
11361
  "json-code-block"
11088
11362
  ]);
11089
11363
  var deterministicArtifactBlockSchema = exports_external.object({
@@ -11127,6 +11401,47 @@ function renderIndexerDeterministicFacts(input) {
11127
11401
  }
11128
11402
  const facts = [...input.facts].sort((left, right) => compareIndexerCanonicalText(left.fact_ref, right.fact_ref));
11129
11403
  const value = projectIndexerFactValue(facts);
11404
+ if (input.renderer === "public-contract-table") {
11405
+ const support = publicContractSupport(facts, input.supporting_facts ?? []);
11406
+ const supportingRefs = new Set(support.map((fact) => fact.fact_ref));
11407
+ const tables = reconcilePublicContractFacts([...facts, ...support]).flatMap((fact) => {
11408
+ if (supportingRefs.has(fact.fact_ref) && typeof fact.value === "object" && fact.value !== null && !Array.isArray(fact.value) && fact.value.kind === "component")
11409
+ return [];
11410
+ const table = projectIndexerPublicContractTable(fact);
11411
+ return table === undefined ? [] : [table];
11412
+ });
11413
+ if (tables.length === 0)
11414
+ throw new TypeError("public-contract-table requires declared public contracts");
11415
+ const rendered = renderIndexerDeterministicFacts({ renderer: "multi-column-table", facts: [{
11416
+ ...facts[0],
11417
+ value: { columns: tables[0].columns, rows: tables.flatMap((table) => table.rows) }
11418
+ }] });
11419
+ const declarations = [...new Map(tables.filter((table) => table.declaration !== undefined).map((table) => [JSON.stringify([table.declarationName, table.declaration]), table])).values()];
11420
+ return [rendered, ...declarations.map((table) => {
11421
+ const declaration = table.declaration;
11422
+ const name = (table.declarationName || "Contract").replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
11423
+ const fence = "`".repeat(Math.max(3, ...[...declaration.matchAll(/`+/gu)].map((match) => match[0].length + 1)));
11424
+ return `<details>
11425
+ <summary>${name}: type details</summary>
11426
+
11427
+ ${fence}typescript
11428
+ ${declaration}
11429
+ ${fence}
11430
+
11431
+ </details>`;
11432
+ })].join(`
11433
+
11434
+ `);
11435
+ }
11436
+ if (input.renderer === "multi-column-table") {
11437
+ const table = exports_external.object({ columns: exports_external.array(exports_external.string()).min(1), rows: exports_external.array(exports_external.array(exports_external.string())) }).strict().parse(value);
11438
+ if (table.rows.some((row) => row.length !== table.columns.length)) {
11439
+ throw new TypeError("multi-column-table rows must match the declared columns");
11440
+ }
11441
+ const cell = (text2) => text2.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("|", "&#124;").replace(/\r?\n/gu, "<br>");
11442
+ return [table.columns, table.columns.map(() => "---"), ...table.rows].map((row) => `| ${row.map(cell).join(" | ")} |`).join(`
11443
+ `);
11444
+ }
11130
11445
  if (input.renderer === "bullet-list") {
11131
11446
  if (!Array.isArray(value) || !value.every((item) => typeof item === "string")) {
11132
11447
  throw new TypeError("bullet-list deterministic block requires a string-list Fact projection");
@@ -11185,8 +11500,12 @@ function validateIndexerRenderedContentBlock(value) {
11185
11500
  return block;
11186
11501
  }
11187
11502
  function materializeIndexerStructuredContent(input) {
11503
+ const key = input.render_cache === undefined ? undefined : indexerProtocolDigest({ blocks: input.blocks, facts: input.facts });
11504
+ const cached = key === undefined ? undefined : input.render_cache?.get(key);
11505
+ if (cached !== undefined)
11506
+ return structuredClone(cached);
11188
11507
  const facts = new Map(input.facts.map((fact) => [fact.fact_ref, fact]));
11189
- return input.blocks.map((block) => {
11508
+ const rendered = input.blocks.map((block) => {
11190
11509
  if (block.layer === "semantic-prose") {
11191
11510
  return buildIndexerRenderedContentBlock({
11192
11511
  layer: block.layer,
@@ -11201,16 +11520,25 @@ function materializeIndexerStructuredContent(input) {
11201
11520
  }
11202
11521
  return fact;
11203
11522
  });
11523
+ const support = block.renderer === "public-contract-table" ? publicContractSupport(referenced, input.facts) : [];
11524
+ const consumed = [...referenced, ...support];
11204
11525
  return buildIndexerRenderedContentBlock({
11205
11526
  layer: block.layer,
11206
11527
  markdown: renderIndexerDeterministicFacts({
11207
11528
  renderer: block.renderer,
11208
- facts: referenced
11529
+ facts: referenced,
11530
+ supporting_facts: support
11209
11531
  }),
11210
- fact_refs: referenced.map((fact) => fact.fact_ref),
11211
- evidence_refs: referenced.flatMap((fact) => fact.evidence_refs)
11532
+ fact_refs: consumed.map((fact) => fact.fact_ref),
11533
+ evidence_refs: consumed.flatMap((fact) => fact.evidence_refs)
11212
11534
  });
11213
11535
  });
11536
+ if (key !== undefined && input.render_cache !== undefined) {
11537
+ if (input.render_cache.size >= 256)
11538
+ input.render_cache.delete(input.render_cache.keys().next().value);
11539
+ input.render_cache.set(key, structuredClone(rendered));
11540
+ }
11541
+ return rendered;
11214
11542
  }
11215
11543
 
11216
11544
  // src/indexerArtifact.ts
@@ -11244,6 +11572,7 @@ var indexerTemplateArtifactSchema = exports_external.object({
11244
11572
  var indexerSectionArtifactSchema = exports_external.object({
11245
11573
  ...artifactCommonFields,
11246
11574
  representation: exports_external.literal("sections"),
11575
+ template_id: indexerIdSchema.optional(),
11247
11576
  sections: exports_external.array(indexerArtifactSectionSchema).min(1)
11248
11577
  }).strict();
11249
11578
  var indexerArtifactSchema = exports_external.discriminatedUnion("representation", [
@@ -12233,7 +12562,8 @@ function indexerParserLockedDependency(lockValue) {
12233
12562
  // src/indexerRestrictedSelector.ts
12234
12563
  var indexerSelectorFactPathSchema = exports_external.string().regex(/^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*$/u);
12235
12564
  var scalarSchema = exports_external.union([exports_external.string(), exports_external.number().finite(), exports_external.boolean()]);
12236
- var expressionSchema = exports_external.lazy(() => exports_external.union([
12565
+ var expressionSchema = exports_external.lazy(() => expressionVariantsSchema);
12566
+ var expressionVariantsSchema = exports_external.union([
12237
12567
  exports_external.object({
12238
12568
  op: exports_external.enum(["all", "any"]),
12239
12569
  args: exports_external.array(expressionSchema).min(1)
@@ -12265,7 +12595,7 @@ var expressionSchema = exports_external.lazy(() => exports_external.union([
12265
12595
  fact: indexerSelectorFactPathSchema,
12266
12596
  value: exports_external.number().finite()
12267
12597
  }).strict()
12268
- ]));
12598
+ ]);
12269
12599
  var indexerRestrictedSelectorSchema = exports_external.object({
12270
12600
  protocol: exports_external.literal("context.indexer.selector/v1"),
12271
12601
  expression: expressionSchema
@@ -12354,14 +12684,15 @@ var INDEXER_SELECTOR_OPERATORS = [
12354
12684
  ];
12355
12685
 
12356
12686
  // src/indexerProfileContract.ts
12357
- var canonicalParametersSchema = exports_external.lazy(() => exports_external.union([
12687
+ var canonicalParametersSchema = exports_external.lazy(() => canonicalParameterVariantsSchema);
12688
+ var canonicalParameterVariantsSchema = exports_external.union([
12358
12689
  exports_external.null(),
12359
12690
  exports_external.boolean(),
12360
12691
  exports_external.number().finite(),
12361
12692
  exports_external.string(),
12362
12693
  exports_external.array(canonicalParametersSchema),
12363
12694
  exports_external.record(canonicalParametersSchema)
12364
- ]));
12695
+ ]);
12365
12696
  var indexerOperatorContractSchema = exports_external.object({
12366
12697
  protocol: exports_external.literal("context.indexer.operator-contract/v1"),
12367
12698
  version: indexerSemverSchema,
@@ -12935,9 +13266,13 @@ var instructionResourceSchema = exports_external.object({
12935
13266
  addDuplicateIssues(value.profiles, context, "profiles");
12936
13267
  });
12937
13268
  var templateResourceSchema = exports_external.object({
13269
+ kind: exports_external.enum(["procedure", "page-program"]).optional(),
12938
13270
  id: indexerIdSchema,
12939
13271
  profile: indexerIdSchema,
12940
- path: portableIndexerPathSchema
13272
+ path: portableIndexerPathSchema,
13273
+ reader_goal: indexerIdSchema.optional(),
13274
+ guidance_path: portableIndexerPathSchema.optional(),
13275
+ delivery: exports_external.enum(["profile", "selected"]).optional()
12941
13276
  }).strict();
12942
13277
  var providerResourcesSchema = exports_external.object({
12943
13278
  program: indexerProgramSchema.optional(),
@@ -13104,6 +13439,21 @@ var indexerProviderManifestSchema = exports_external.object({
13104
13439
  });
13105
13440
  }
13106
13441
  });
13442
+ const supports = value.customization?.supports ?? [];
13443
+ if (supports.includes("config") && value.provider.config_schema === undefined) {
13444
+ context.addIssue({
13445
+ code: exports_external.ZodIssueCode.custom,
13446
+ message: "customization supports config but the Provider declares no config_schema",
13447
+ path: ["customization", "supports"]
13448
+ });
13449
+ }
13450
+ if (supports.includes("program-extend") && value.provider.program === undefined) {
13451
+ context.addIssue({
13452
+ code: exports_external.ZodIssueCode.custom,
13453
+ message: "customization supports program-extend but the Provider declares no program",
13454
+ path: ["customization", "supports"]
13455
+ });
13456
+ }
13107
13457
  });
13108
13458
  function parseYamlDocument(source, label) {
13109
13459
  const document = $parseDocument(source, { uniqueKeys: true });
@@ -13125,7 +13475,7 @@ function referencedProviderPaths(manifest) {
13125
13475
  ...manifest.authoring_inspector === undefined ? [] : [manifest.authoring_inspector.execution.entry],
13126
13476
  ...manifest.provider.program === undefined ? [] : [manifest.provider.program.execution.entry],
13127
13477
  ...(manifest.provider.instructions ?? []).map((item) => item.path),
13128
- ...(manifest.provider.templates ?? []).map((item) => item.path),
13478
+ ...(manifest.provider.templates ?? []).flatMap((item) => [item.path, ...item.guidance_path === undefined ? [] : [item.guidance_path]]),
13129
13479
  ...(manifest.provides.composers ?? []).flatMap((item) => item.contract === undefined ? [] : [item.contract.instruction]),
13130
13480
  ...manifest.provider.config_schema === undefined ? [] : [manifest.provider.config_schema],
13131
13481
  ...manifest.customization?.guide === undefined ? [] : [manifest.customization.guide],
@@ -13203,10 +13553,12 @@ var requirementQuestionSchema = exports_external.object({
13203
13553
  var requirementExclusionSchema = exports_external.object({
13204
13554
  id: indexerIdSchema,
13205
13555
  scope: targetScopeSchema,
13206
- reason: exports_external.string().min(1)
13556
+ reason: exports_external.string().min(1),
13557
+ paths: exports_external.array(exports_external.string().min(1).refine((path) => !path.startsWith("/") && !path.includes("\\") && !path.split("/").some((part) => part === ".." || part === ".") && !/[?*]/u.test(path), "Use an exact repository-relative file or directory path, without globs or traversal")).min(1).optional()
13207
13558
  }).strict();
13208
13559
  var indexRequirementSchema = exports_external.object({
13209
13560
  id: indexerIdSchema,
13561
+ purpose: exports_external.string().trim().min(1).optional(),
13210
13562
  reader_goals: exports_external.array(indexerIdSchema).min(1),
13211
13563
  coverage_domains: exports_external.record(indexerIdSchema, exports_external.enum(["required", "optional", "out-of-scope"])),
13212
13564
  questions: exports_external.array(requirementQuestionSchema).optional(),
@@ -14309,14 +14661,15 @@ function validateIndexerControlledInvocation(value) {
14309
14661
  return invocation;
14310
14662
  }
14311
14663
  // src/indexerParserFactView.ts
14312
- var canonicalJsonSchema2 = exports_external.lazy(() => exports_external.union([
14313
- exports_external.null(),
14314
- exports_external.boolean(),
14315
- exports_external.number().finite(),
14664
+ var canonicalJsonSchema2 = exports_external.lazy(() => canonicalJsonVariantsSchema);
14665
+ var canonicalJsonVariantsSchema = exports_external.union([
14316
14666
  exports_external.string(),
14667
+ exports_external.number().finite(),
14668
+ exports_external.boolean(),
14669
+ exports_external.null(),
14317
14670
  exports_external.array(canonicalJsonSchema2),
14318
14671
  exports_external.record(canonicalJsonSchema2)
14319
- ]));
14672
+ ]);
14320
14673
  var parserFactSchema = exports_external.object({
14321
14674
  fact_ref: indexerCanonicalRefSchema,
14322
14675
  kind: indexerIdSchema,
@@ -14648,6 +15001,164 @@ function buildIndexerMergedParserFactView(input) {
14648
15001
  });
14649
15002
  }
14650
15003
 
15004
+ // src/indexerKnowledgeDependency.ts
15005
+ var indexerKnowledgeDependencySchema = exports_external.object({
15006
+ artifact_ref: indexerCanonicalRefSchema,
15007
+ section_refs: exports_external.array(indexerCanonicalRefSchema).default([]),
15008
+ required: exports_external.boolean().default(true)
15009
+ }).strict();
15010
+
15011
+ class IndexerKnowledgeDependencyCycleError extends TypeError {
15012
+ artifact_refs;
15013
+ constructor(artifact_refs) {
15014
+ super(`Knowledge dependency cycle: ${artifact_refs.join(" -> ")}. Revise the Partition dependency plan.`);
15015
+ this.artifact_refs = artifact_refs;
15016
+ this.name = "IndexerKnowledgeDependencyCycleError";
15017
+ }
15018
+ }
15019
+ function validateIndexerKnowledgeDependencyGraph(nodes) {
15020
+ const graph = new Map;
15021
+ for (const node of nodes) {
15022
+ indexerCanonicalRefSchema.parse(node.artifact_ref);
15023
+ if (graph.has(node.artifact_ref))
15024
+ throw new TypeError(`Knowledge article has duplicate responsibility: ${node.artifact_ref}`);
15025
+ const dependencies = node.dependencies.map((dependency) => indexerKnowledgeDependencySchema.parse(dependency));
15026
+ if (new Set(dependencies.map((dependency) => dependency.artifact_ref)).size !== dependencies.length) {
15027
+ throw new TypeError(`Knowledge article repeats a dependency: ${node.artifact_ref}`);
15028
+ }
15029
+ if (dependencies.some((dependency) => new Set(dependency.section_refs).size !== dependency.section_refs.length)) {
15030
+ throw new TypeError(`Knowledge article repeats a supporting section: ${node.artifact_ref}`);
15031
+ }
15032
+ graph.set(node.artifact_ref, dependencies);
15033
+ }
15034
+ const complete = new Set;
15035
+ const active = new Set;
15036
+ const visit2 = (ref, trail) => {
15037
+ if (active.has(ref))
15038
+ throw new IndexerKnowledgeDependencyCycleError([...trail.slice(trail.indexOf(ref)), ref]);
15039
+ if (complete.has(ref))
15040
+ return;
15041
+ active.add(ref);
15042
+ for (const dependency of graph.get(ref) ?? [])
15043
+ visit2(dependency.artifact_ref, [...trail, ref]);
15044
+ active.delete(ref);
15045
+ complete.add(ref);
15046
+ };
15047
+ for (const ref of graph.keys())
15048
+ visit2(ref, []);
15049
+ }
15050
+ var indexerKnowledgeDependencyVersionSchema = exports_external.object({
15051
+ artifact_ref: indexerCanonicalRefSchema,
15052
+ approved_content_digest: indexerDigestSchema,
15053
+ projection_digest: indexerDigestSchema
15054
+ }).strict();
15055
+ function indexerKnowledgeDependencyFingerprint(versions) {
15056
+ const parsed = versions.map((version) => indexerKnowledgeDependencyVersionSchema.parse(version));
15057
+ if (new Set(parsed.map((version) => version.artifact_ref)).size !== parsed.length) {
15058
+ throw new TypeError("Knowledge dependency versions repeat an article");
15059
+ }
15060
+ return indexerProtocolDigest(parsed.sort((left, right) => compareIndexerCanonicalText(left.artifact_ref, right.artifact_ref)));
15061
+ }
15062
+ function impactedIndexerKnowledgeArticles(nodes, changed) {
15063
+ validateIndexerKnowledgeDependencyGraph(nodes);
15064
+ const reverse = new Map;
15065
+ for (const node of nodes)
15066
+ for (const dependency of node.dependencies) {
15067
+ const readers = reverse.get(dependency.artifact_ref) ?? new Set;
15068
+ readers.add(node.artifact_ref);
15069
+ reverse.set(dependency.artifact_ref, readers);
15070
+ }
15071
+ const impacted = new Set(changed);
15072
+ const queue = [...changed];
15073
+ for (let cursor = 0;cursor < queue.length; cursor++) {
15074
+ for (const reader of reverse.get(queue[cursor]) ?? []) {
15075
+ if (impacted.has(reader))
15076
+ continue;
15077
+ impacted.add(reader);
15078
+ queue.push(reader);
15079
+ }
15080
+ }
15081
+ return [...impacted].filter((ref) => !changed.has(ref)).sort();
15082
+ }
15083
+
15084
+ // src/indexerArticlePlan.ts
15085
+ var indexerArticleKeySchema = exports_external.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u);
15086
+ var indexerArticlePlanSchema = exports_external.object({
15087
+ key: indexerArticleKeySchema,
15088
+ title: exports_external.string().min(1),
15089
+ reader_task: exports_external.string().min(1),
15090
+ artifact_intent: exports_external.string().min(1),
15091
+ template_id: exports_external.string().min(1).optional(),
15092
+ required: exports_external.boolean(),
15093
+ sections: exports_external.array(exports_external.object({
15094
+ key: indexerArticleKeySchema,
15095
+ heading: exports_external.string().min(1),
15096
+ required: exports_external.boolean()
15097
+ }).strict()).min(1),
15098
+ question_targets: exports_external.array(exports_external.string().min(1)).default([]),
15099
+ knowledge_dependencies: exports_external.array(indexerKnowledgeDependencySchema).optional()
15100
+ }).strict();
15101
+ function validateIndexerArticlePlan(articles, targets) {
15102
+ if (!articles.length || !articles.some((article) => article.required)) {
15103
+ throw new TypeError("article plan needs at least one required article; revise the current Partition plan");
15104
+ }
15105
+ const keys = new Set, owners = new Set;
15106
+ for (const article of articles) {
15107
+ indexerArticlePlanSchema.parse(article);
15108
+ if (keys.has(article.key))
15109
+ throw new TypeError(`duplicate article key ${article.key}; choose stable unique keys in Partition`);
15110
+ keys.add(article.key);
15111
+ if (new Set(article.sections.map((section) => section.key)).size !== article.sections.length) {
15112
+ throw new TypeError(`article ${article.key} repeats a section key; revise its section plan`);
15113
+ }
15114
+ for (const target of article.question_targets) {
15115
+ if (!article.required || owners.has(target) || targets !== undefined && !targets.includes(target)) {
15116
+ throw new TypeError(`article ${article.key} has invalid question responsibility ${target}; assign each group target to one required article`);
15117
+ }
15118
+ owners.add(target);
15119
+ }
15120
+ }
15121
+ if (targets?.some((target) => !owners.has(target))) {
15122
+ throw new TypeError("article plan leaves a question without a primary article; revise the current Partition plan");
15123
+ }
15124
+ }
15125
+ function indexerArticleSectionKey(article, section) {
15126
+ return `${article}--${section}`;
15127
+ }
15128
+ function validateIndexerPlannedArticles(result, articles) {
15129
+ const warnings = [];
15130
+ validateIndexerArticlePlan(articles);
15131
+ const planned = new Map(articles.map((article) => [article.key, article]));
15132
+ for (const artifact of result.artifacts) {
15133
+ const article = planned.get(artifact.artifact_id);
15134
+ if (!article)
15135
+ throw new TypeError(`unplanned article ${artifact.artifact_id}; revise Partition before adding an article`);
15136
+ if (artifact.template_id !== article.template_id) {
15137
+ throw new TypeError(`article ${article.key} changes its accepted template; use the planned template or revise Partition`);
15138
+ }
15139
+ const sections = artifact.representation === "sections" ? artifact.sections : artifact.section_projections;
15140
+ const expected = new Map(article.sections.map((section) => [indexerArticleSectionKey(article.key, section.key), section]));
15141
+ for (const section of sections) {
15142
+ if (!expected.has(section.section_key))
15143
+ warnings.push({ code: "article-outline-drift", message: `Article ${article.key} includes additional section ${section.section_key}. Review its relevance; this does not block publication.` });
15144
+ const intent = [result.source_role, section.document_kind, section.reader_goal, section.artifact_kind].join("/");
15145
+ if (intent !== article.artifact_intent)
15146
+ throw new TypeError(`article ${article.key} changes its accepted intent; use ${article.artifact_intent}`);
15147
+ }
15148
+ for (const [key, section] of expected) {
15149
+ if (section.required && !sections.some((actual) => actual.section_key === key)) {
15150
+ warnings.push({ code: "article-outline-gap", message: `Article ${article.key} omits suggested section ${section.key}. Explain material limits or add useful evidence when available; this does not block publication.` });
15151
+ }
15152
+ }
15153
+ }
15154
+ for (const article of articles) {
15155
+ if (article.required && !result.artifacts.some((artifact) => artifact.artifact_id === article.key)) {
15156
+ throw new TypeError(`missing required article ${article.key}; complete the accepted article set before submitting`);
15157
+ }
15158
+ }
15159
+ return warnings;
15160
+ }
15161
+
14651
15162
  // src/indexerArtifactPolicy.ts
14652
15163
  var canonicalJsonSchema3 = exports_external.lazy(() => exports_external.union([
14653
15164
  exports_external.null(),
@@ -15672,7 +16183,7 @@ function validateTargetExists(input) {
15672
16183
  return;
15673
16184
  }
15674
16185
  const fact = file.facts.find((candidate) => candidate.fact_ref === target.source_fact_ref);
15675
- if (fact === undefined || fact.qualified_item_path !== target.qualified_item_path || fact.signature_digest !== target.signature_digest) {
16186
+ if (fact === undefined || fact.qualified_item_path !== target.qualified_item_path) {
15676
16187
  throw new TypeError("structured declaration source item does not exist");
15677
16188
  }
15678
16189
  }
@@ -15694,7 +16205,7 @@ function validateIndexerStructuredDeclarationSet(input) {
15694
16205
  throw new TypeError("structured declaration set is non-canonical or invalid");
15695
16206
  }
15696
16207
  const inventory = validateIndexerSourceIdentityInventory(input.source_identity_inventory);
15697
- if (value.source_identity_inventory_digest !== inventory.inventory_digest || inventory.source_ref !== input.expected_source_ref || inventory.module_ref !== input.expected_module_ref) {
16208
+ if (inventory.source_ref !== input.expected_source_ref || inventory.module_ref !== input.expected_module_ref) {
15698
16209
  throw new TypeError("structured declarations do not match current source identity");
15699
16210
  }
15700
16211
  const evidence = new Set(canonicalUnique4(input.known_evidence_refs, "known declaration evidence"));
@@ -15723,7 +16234,7 @@ function indexerSectionEvidenceCarrierRef(input) {
15723
16234
  return `section-evidence:${indexerProtocolDigest(input)}`;
15724
16235
  }
15725
16236
 
15726
- // src/indexerGeneratedAuthoringAudit.ts
16237
+ // src/indexerStructuredClaims.ts
15727
16238
  var structuredClaimOwnerSchema = exports_external.object({
15728
16239
  artifact_id: indexerIdSchema,
15729
16240
  section_key: indexerIdSchema
@@ -15742,53 +16253,6 @@ var indexerStructuredClaimSetSchema = exports_external.object({
15742
16253
  claims: exports_external.array(structuredClaimSchema).min(1),
15743
16254
  claims_digest: indexerDigestSchema
15744
16255
  }).strict();
15745
- var generatedAuthoringFindingSchema = exports_external.object({
15746
- code: exports_external.enum([
15747
- "generated-placeholder",
15748
- "empty-required-section"
15749
- ]),
15750
- artifact_id: indexerIdSchema,
15751
- section_key: indexerIdSchema.nullable(),
15752
- content_ref: exports_external.string().min(1)
15753
- }).strict();
15754
- var semanticProseReviewTargetSchema = exports_external.object({
15755
- artifact_id: indexerIdSchema,
15756
- section_key: indexerIdSchema.nullable(),
15757
- content_ref: exports_external.string().min(1),
15758
- advisory_code: exports_external.literal("semantic-prose-agent-review-required")
15759
- }).strict();
15760
- var indexerGeneratedAuthoringAuditSchema = exports_external.object({
15761
- protocol: exports_external.literal("context.indexer.generated-authoring-audit/v1"),
15762
- artifact_result_digest: indexerDigestSchema,
15763
- hard_findings: exports_external.array(generatedAuthoringFindingSchema),
15764
- structured_claim_count: exports_external.number().int().nonnegative(),
15765
- evidence_covered_structured_claim_count: exports_external.number().int().nonnegative(),
15766
- semantic_prose_review_targets: exports_external.array(semanticProseReviewTargetSchema),
15767
- agent_review_required: exports_external.boolean(),
15768
- audit_digest: indexerDigestSchema
15769
- }).strict();
15770
- function markdownProseOnly(markdown) {
15771
- const prose = [];
15772
- let fence;
15773
- for (const line of markdown.split(`
15774
- `)) {
15775
- const opening = line.match(/^ {0,3}(`{3,}|~{3,})/u)?.[1];
15776
- if (fence === undefined && opening !== undefined) {
15777
- fence = { marker: opening[0], length: opening.length };
15778
- continue;
15779
- }
15780
- if (fence !== undefined) {
15781
- const closing = line.match(/^ {0,3}(`{3,}|~{3,})\s*$/u)?.[1];
15782
- if (closing !== undefined && closing[0] === fence.marker && closing.length >= fence.length) {
15783
- fence = undefined;
15784
- }
15785
- continue;
15786
- }
15787
- prose.push(line.replace(/(`+)[^`]*?\1/gu, ""));
15788
- }
15789
- return prose.join(`
15790
- `);
15791
- }
15792
16256
  function assertCanonicalUnique(values, label) {
15793
16257
  const expected = [...new Set(values)].sort(compareIndexerCanonicalText);
15794
16258
  if (expected.length !== values.length || expected.some((value, index) => value !== values[index])) {
@@ -15848,135 +16312,6 @@ function validateIndexerStructuredClaimSet(input) {
15848
16312
  }
15849
16313
  return value;
15850
16314
  }
15851
- function containsIndexerControlledAuthoringPlaceholder(markdown) {
15852
- const prose = markdownProseOnly(markdown);
15853
- if (/\{\{|\}\}|<!--/u.test(prose))
15854
- return true;
15855
- if (/\[(?:TODO|TBD|待补充|待生成|placeholder(?:[^\]]*)?|example|your\s+[^\]]+)\]/iu.test(prose) || /<(?:TODO|TBD|待补充|待生成|placeholder(?:[^>]*)?|example|your[-_ ][^>]+)>/iu.test(prose)) {
15856
- return true;
15857
- }
15858
- return prose.split(`
15859
- `).some((line) => {
15860
- const marker = line.trim().replace(/^#{1,6}\s+/u, "").replace(/^[-*+]\s+/u, "").trim();
15861
- return /^(?:TODO|TBD|待补充|待生成|占位|placeholder|coming soon)[.!。!??…]*$/iu.test(marker);
15862
- });
15863
- }
15864
- function hasSubstantiveMarkdown(markdown) {
15865
- return markdown.split(`
15866
- `).some((line) => {
15867
- const value = line.trim();
15868
- return value.length > 0 && !/^#{1,6}(?:\s+.*)?$/u.test(value) && !/^[-|:\s]+$/u.test(value) && !/^<!--.*-->$/u.test(value) && !containsIndexerControlledAuthoringPlaceholder(value);
15869
- });
15870
- }
15871
- function stringLeaves(value) {
15872
- if (typeof value === "string")
15873
- return [value];
15874
- if (Array.isArray(value))
15875
- return value.flatMap(stringLeaves);
15876
- if (value !== null && typeof value === "object") {
15877
- return Object.values(value).flatMap(stringLeaves);
15878
- }
15879
- return [];
15880
- }
15881
- function auditPayload(value) {
15882
- return value;
15883
- }
15884
- function buildIndexerGeneratedAuthoringAudit(result) {
15885
- const hardFindings = [];
15886
- const reviewTargets = [];
15887
- for (const artifact of result.artifacts) {
15888
- if (artifact.representation === "sections") {
15889
- for (const section of artifact.sections) {
15890
- let sectionHasSubstance = false;
15891
- for (const block of section.blocks) {
15892
- if (block.layer === "deterministic-block") {
15893
- sectionHasSubstance = true;
15894
- continue;
15895
- }
15896
- const contentRef = `block:${block.block_id}`;
15897
- reviewTargets.push({
15898
- artifact_id: artifact.artifact_id,
15899
- section_key: section.section_key,
15900
- content_ref: contentRef,
15901
- advisory_code: "semantic-prose-agent-review-required"
15902
- });
15903
- if (containsIndexerControlledAuthoringPlaceholder(block.markdown)) {
15904
- hardFindings.push({
15905
- code: "generated-placeholder",
15906
- artifact_id: artifact.artifact_id,
15907
- section_key: section.section_key,
15908
- content_ref: contentRef
15909
- });
15910
- }
15911
- if (hasSubstantiveMarkdown(block.markdown))
15912
- sectionHasSubstance = true;
15913
- }
15914
- if (!sectionHasSubstance) {
15915
- hardFindings.push({
15916
- code: "empty-required-section",
15917
- artifact_id: artifact.artifact_id,
15918
- section_key: section.section_key,
15919
- content_ref: `section:${section.section_key}`
15920
- });
15921
- }
15922
- }
15923
- continue;
15924
- }
15925
- for (const [variableId, variable] of Object.entries(artifact.variables)) {
15926
- if (variable.fact_refs.length > 0)
15927
- continue;
15928
- const contentRef = `variable:${variableId}`;
15929
- reviewTargets.push({
15930
- artifact_id: artifact.artifact_id,
15931
- section_key: null,
15932
- content_ref: contentRef,
15933
- advisory_code: "semantic-prose-agent-review-required"
15934
- });
15935
- if (stringLeaves(variable.value).some(containsIndexerControlledAuthoringPlaceholder)) {
15936
- hardFindings.push({
15937
- code: "generated-placeholder",
15938
- artifact_id: artifact.artifact_id,
15939
- section_key: null,
15940
- content_ref: contentRef
15941
- });
15942
- }
15943
- }
15944
- }
15945
- hardFindings.sort((left, right) => compareIndexerCanonicalText(`${left.artifact_id}\x00${left.section_key ?? ""}\x00${left.content_ref}\x00${left.code}`, `${right.artifact_id}\x00${right.section_key ?? ""}\x00${right.content_ref}\x00${right.code}`));
15946
- reviewTargets.sort((left, right) => compareIndexerCanonicalText(`${left.artifact_id}\x00${left.section_key ?? ""}\x00${left.content_ref}`, `${right.artifact_id}\x00${right.section_key ?? ""}\x00${right.content_ref}`));
15947
- const claimCount = result.structured_claims?.claims.length ?? 0;
15948
- const payload = indexerGeneratedAuthoringAuditSchema.omit({ audit_digest: true }).parse({
15949
- protocol: "context.indexer.generated-authoring-audit/v1",
15950
- artifact_result_digest: result.output_digest,
15951
- hard_findings: hardFindings,
15952
- structured_claim_count: claimCount,
15953
- evidence_covered_structured_claim_count: claimCount,
15954
- semantic_prose_review_targets: reviewTargets,
15955
- agent_review_required: reviewTargets.length > 0
15956
- });
15957
- return indexerGeneratedAuthoringAuditSchema.parse({
15958
- ...payload,
15959
- audit_digest: indexerProtocolDigest(auditPayload(payload))
15960
- });
15961
- }
15962
- function validateIndexerGeneratedAuthoringAudit(value) {
15963
- const audit = indexerGeneratedAuthoringAuditSchema.parse(value);
15964
- if (audit.evidence_covered_structured_claim_count !== audit.structured_claim_count || audit.agent_review_required !== audit.semantic_prose_review_targets.length > 0) {
15965
- throw new TypeError("generated authoring audit coverage/review state is inconsistent");
15966
- }
15967
- const { audit_digest: _digest, ...payload } = audit;
15968
- if (audit.audit_digest !== indexerProtocolDigest(auditPayload(payload))) {
15969
- throw new TypeError("generated authoring audit digest is invalid");
15970
- }
15971
- return audit;
15972
- }
15973
- function assertIndexerGeneratedAuthoringAuditClear(audit) {
15974
- validateIndexerGeneratedAuthoringAudit(audit);
15975
- if (audit.hard_findings.length > 0) {
15976
- const finding = audit.hard_findings[0];
15977
- throw new TypeError(`generated authoring audit failed: ${finding.code} at ${finding.artifact_id}/${finding.content_ref}`);
15978
- }
15979
- }
15980
16315
 
15981
16316
  // src/indexerArtifactResult.ts
15982
16317
  var indexerEvidenceBindingSchema = exports_external.object({
@@ -16360,8 +16695,10 @@ function validateIndexerArtifactResult(input) {
16360
16695
  if (indexerArtifactResultDigest(payload) !== result.output_digest) {
16361
16696
  throw new TypeError("ArtifactResult output digest is invalid");
16362
16697
  }
16698
+ if (input.planned_articles !== undefined)
16699
+ validateIndexerPlannedArticles(result, input.planned_articles);
16363
16700
  const expectedProvider = input.expected_provider;
16364
- if (result.author_workset_digest !== input.workset.workset_digest || result.partition_plan_binding_digest !== input.workset.partition_plan_binding_digest || result.group_projection_digest !== input.workset.group_projection_digest || result.indexer_id !== input.workset.indexer_id || result.requirement_ref !== input.workset.requirement_ref || result.source_ref !== input.workset.source_ref || result.module_ref !== input.workset.module_ref || result.logical_unit.group_key !== input.workset.group_key || result.logical_unit.logical_unit_ref !== input.workset.logical_unit_ref || canonicalIndexerJson(result.logical_unit.subject_key) !== canonicalIndexerJson(input.expected_subject_key) || result.provider_layer_ref !== expectedProvider.layer_ref || result.provider_integrity !== expectedProvider.integrity || result.provider_bundle_digest !== expectedProvider.bundle_digest || result.config_fingerprint !== expectedProvider.config_fingerprint || result.customization_fingerprint !== expectedProvider.customization_fingerprint || result.input_digest !== input.expected_input_digest) {
16701
+ if (result.author_workset_digest !== input.workset.workset_digest || result.partition_plan_binding_digest !== input.workset.partition_plan_binding_digest || result.group_projection_digest !== input.workset.group_projection_digest || result.indexer_id !== input.workset.indexer_id || result.requirement_ref !== input.workset.requirement_ref || result.source_ref !== input.workset.source_ref || result.module_ref !== input.workset.module_ref || result.logical_unit.group_key !== input.workset.group_key || result.logical_unit.logical_unit_ref !== input.workset.logical_unit_ref || canonicalIndexerJson(result.logical_unit.subject_key) !== canonicalIndexerJson(input.expected_subject_key) || result.provider_layer_ref !== expectedProvider.layer_ref || result.input_digest !== input.expected_input_digest) {
16365
16702
  throw new TypeError("ArtifactResult does not match its author authority/workset");
16366
16703
  }
16367
16704
  if (!input.allowed_source_roles.includes(result.source_role)) {
@@ -16422,7 +16759,6 @@ function validateIndexerArtifactResult(input) {
16422
16759
  authorized_carriers: input.authorized_declaration_carriers
16423
16760
  });
16424
16761
  validateStructuredClaims({ result, evidence_refs: evidenceRefs, facts });
16425
- assertIndexerGeneratedAuthoringAuditClear(buildIndexerGeneratedAuthoringAudit(result));
16426
16762
  validateTargetResolution(result, input.workset.target_resolution_view, evidenceRefs);
16427
16763
  validateQuestions({ result, allowed_question_targets: input.allowed_question_targets });
16428
16764
  return result;
@@ -16478,12 +16814,12 @@ var logicalUnitNodeInputSchema = exports_external.object({
16478
16814
  targets: dependencyTargetsSchema
16479
16815
  }).strict();
16480
16816
  var resourceNodeInputSchema = exports_external.object({
16481
- kind: exports_external.enum(["template-policy-fragment", "contract-metric"]),
16817
+ kind: exports_external.enum(["template-policy-fragment", "contract-metric", "approved-knowledge"]),
16482
16818
  target_ref: indexerCanonicalRefSchema,
16483
16819
  content_digest: indexerDigestSchema,
16484
16820
  targets: dependencyTargetsSchema
16485
16821
  }).strict();
16486
- var indexerPositiveDependencyNodeInputSchema = exports_external.union([
16822
+ var indexerPositiveDependencyNodeInputSchema = exports_external.discriminatedUnion("kind", [
16487
16823
  sourceSpanNodeInputSchema,
16488
16824
  selectedFactNodeInputSchema,
16489
16825
  logicalUnitNodeInputSchema,
@@ -16515,7 +16851,7 @@ var indexerLogicalUnitDependencyNodeSchema = logicalUnitNodeInputSchema.extend({
16515
16851
  var indexerResourceDependencyNodeSchema = resourceNodeInputSchema.extend({
16516
16852
  node_ref: indexerCanonicalRefSchema
16517
16853
  }).strict();
16518
- var indexerPositiveDependencyNodeSchema = exports_external.union([
16854
+ var indexerPositiveDependencyNodeSchema = exports_external.discriminatedUnion("kind", [
16519
16855
  indexerSourceSpanDependencyNodeSchema,
16520
16856
  indexerSelectedFactDependencyNodeSchema,
16521
16857
  indexerLogicalUnitDependencyNodeSchema,
@@ -16708,6 +17044,171 @@ function compositionFactDependencies(input) {
16708
17044
  });
16709
17045
  }
16710
17046
 
17047
+ // src/indexerExampleIdentity.ts
17048
+ var exampleObservationSchema = exports_external.object({
17049
+ observation_ref: indexerCanonicalRefSchema,
17050
+ example_ref: indexerCanonicalRefSchema,
17051
+ public_target_ref: indexerCanonicalRefSchema,
17052
+ scenario_key: indexerIdSchema,
17053
+ source_ref: indexerCanonicalRefSchema,
17054
+ module_ref: indexerCanonicalRefSchema.nullable(),
17055
+ full_relative_path: portableIndexerPathSchema,
17056
+ content_digest: indexerDigestSchema,
17057
+ evidence_refs: exports_external.array(indexerCanonicalRefSchema).min(1)
17058
+ }).strict();
17059
+ var indexerExampleInventorySchema = exports_external.object({
17060
+ protocol: exports_external.literal("context.indexer.example-inventory/v1"),
17061
+ source_scope_digest: indexerDigestSchema,
17062
+ observations: exports_external.array(exampleObservationSchema),
17063
+ inventory_digest: indexerDigestSchema
17064
+ }).strict();
17065
+ function canonicalUnique5(values, field) {
17066
+ const sorted = [...values].sort(compareIndexerCanonicalText);
17067
+ if (new Set(sorted).size !== sorted.length) {
17068
+ throw new TypeError(`${field} must not contain duplicate identities`);
17069
+ }
17070
+ return sorted;
17071
+ }
17072
+ function normalizeIndexerExampleRelativePath(value) {
17073
+ const normalized = value.normalize("NFC").replaceAll("\\", "/").replace(/^\.\//u, "");
17074
+ return portableIndexerPathSchema.parse(normalized);
17075
+ }
17076
+ function indexerExampleRef(input) {
17077
+ const identity2 = {
17078
+ public_target_ref: indexerCanonicalRefSchema.parse(input.public_target_ref),
17079
+ scenario_key: indexerIdSchema.parse(input.scenario_key),
17080
+ full_relative_path: normalizeIndexerExampleRelativePath(input.full_relative_path)
17081
+ };
17082
+ return `example:${indexerProtocolDigest(identity2)}`;
17083
+ }
17084
+ function indexerExampleObservationRef(input) {
17085
+ return `example-observation:${indexerProtocolDigest(input)}`;
17086
+ }
17087
+ function indexerExampleInventoryDigest(value) {
17088
+ return indexerProtocolDigest(value);
17089
+ }
17090
+ function normalizeObservation(input) {
17091
+ const fullRelativePath = normalizeIndexerExampleRelativePath(input.full_relative_path);
17092
+ const publicTargetRef = indexerCanonicalRefSchema.parse(input.public_target_ref);
17093
+ const scenarioKey = indexerIdSchema.parse(input.scenario_key);
17094
+ const sourceRef = indexerCanonicalRefSchema.parse(input.source_ref);
17095
+ const moduleRef = input.module_ref === null ? null : indexerCanonicalRefSchema.parse(input.module_ref);
17096
+ const contentDigest = indexerDigestSchema.parse(input.content_digest);
17097
+ const exampleRef = indexerExampleRef({
17098
+ public_target_ref: publicTargetRef,
17099
+ scenario_key: scenarioKey,
17100
+ full_relative_path: fullRelativePath
17101
+ });
17102
+ return exampleObservationSchema.parse({
17103
+ observation_ref: indexerExampleObservationRef({
17104
+ example_ref: exampleRef,
17105
+ source_ref: sourceRef,
17106
+ module_ref: moduleRef,
17107
+ content_digest: contentDigest
17108
+ }),
17109
+ example_ref: exampleRef,
17110
+ public_target_ref: publicTargetRef,
17111
+ scenario_key: scenarioKey,
17112
+ source_ref: sourceRef,
17113
+ module_ref: moduleRef,
17114
+ full_relative_path: fullRelativePath,
17115
+ content_digest: contentDigest,
17116
+ evidence_refs: canonicalUnique5(input.evidence_refs, "example evidence_refs")
17117
+ });
17118
+ }
17119
+ function buildIndexerExampleInventory(input) {
17120
+ const byObservation = new Map;
17121
+ for (const observationInput of input.observations) {
17122
+ const observation = normalizeObservation(observationInput);
17123
+ const current = byObservation.get(observation.observation_ref);
17124
+ if (current === undefined) {
17125
+ byObservation.set(observation.observation_ref, observation);
17126
+ continue;
17127
+ }
17128
+ const currentCore = { ...current, evidence_refs: undefined };
17129
+ const nextCore = { ...observation, evidence_refs: undefined };
17130
+ if (canonicalIndexerJson(currentCore) !== canonicalIndexerJson(nextCore)) {
17131
+ throw new TypeError("example observation identity collision");
17132
+ }
17133
+ current.evidence_refs = [...new Set([
17134
+ ...current.evidence_refs,
17135
+ ...observation.evidence_refs
17136
+ ])].sort(compareIndexerCanonicalText);
17137
+ }
17138
+ const observations = [...byObservation.values()].sort((left, right) => compareIndexerCanonicalText(left.observation_ref, right.observation_ref));
17139
+ const payload = {
17140
+ protocol: "context.indexer.example-inventory/v1",
17141
+ source_scope_digest: indexerDigestSchema.parse(input.source_scope_digest),
17142
+ observations
17143
+ };
17144
+ return indexerExampleInventorySchema.parse({
17145
+ ...payload,
17146
+ inventory_digest: indexerExampleInventoryDigest(payload)
17147
+ });
17148
+ }
17149
+ function validateIndexerExampleInventory(input) {
17150
+ const value = indexerExampleInventorySchema.parse(input.value);
17151
+ const rebuilt = buildIndexerExampleInventory({
17152
+ source_scope_digest: value.source_scope_digest,
17153
+ observations: value.observations
17154
+ });
17155
+ if (canonicalIndexerJson(rebuilt) !== canonicalIndexerJson(value)) {
17156
+ throw new TypeError("example inventory is non-canonical or has an invalid digest");
17157
+ }
17158
+ if (input.expected_source_scope_digest !== undefined && value.source_scope_digest !== input.expected_source_scope_digest) {
17159
+ throw new TypeError("example inventory belongs to another source scope");
17160
+ }
17161
+ if (input.known_evidence_refs !== undefined) {
17162
+ const known = new Set(canonicalUnique5(input.known_evidence_refs, "known_evidence_refs"));
17163
+ if (value.observations.some((item) => item.evidence_refs.some((evidenceRef) => !known.has(evidenceRef)))) {
17164
+ throw new TypeError("example inventory references unknown evidence");
17165
+ }
17166
+ }
17167
+ return value;
17168
+ }
17169
+
17170
+ // src/indexerExampleFactDependencies.ts
17171
+ function exampleFactDependencies(input) {
17172
+ const examples = input.result.facts.filter((fact) => fact.fact_kind === "example-candidate");
17173
+ if (!examples.length)
17174
+ return [];
17175
+ const observationSchema = indexerExampleInventorySchema.shape.observations.element;
17176
+ const observations = examples.map((fact) => {
17177
+ if (fact.value === null || typeof fact.value !== "object" || Array.isArray(fact.value)) {
17178
+ throw new TypeError("Example selection must identify an authorized source observation");
17179
+ }
17180
+ const { inventory_digest, ...value } = fact.value;
17181
+ return { fact, inventory_digest, observation: observationSchema.parse(value) };
17182
+ });
17183
+ const inventory = validateIndexerExampleInventory({ value: {
17184
+ protocol: "context.indexer.example-inventory/v1",
17185
+ source_scope_digest: input.workset.source_scope_digest,
17186
+ observations: observations.map((item) => item.observation).sort((a, b) => compareIndexerCanonicalText(a.observation_ref, b.observation_ref)),
17187
+ inventory_digest: observations[0].inventory_digest
17188
+ }, expected_source_scope_digest: input.workset.source_scope_digest });
17189
+ const spans = new Map(input.dependency_view.positive_nodes.flatMap((node) => node.kind === "source-span" ? [[node.evidence_ref, node]] : []));
17190
+ return observations.map(({ fact, observation, inventory_digest }) => {
17191
+ if (inventory_digest !== inventory.inventory_digest || observation.public_target_ref !== input.workset.logical_unit_ref || fact.fact_ref !== `fact:example-${indexerProtocolDigest(observation).slice(7)}` || canonicalIndexerJson(fact.subject_key) !== canonicalIndexerJson(input.result.logical_unit.subject_key) || canonicalIndexerJson([...fact.evidence_refs].sort(compareIndexerCanonicalText)) !== canonicalIndexerJson(observation.evidence_refs)) {
17192
+ throw new TypeError("Example selection identity does not match its current task");
17193
+ }
17194
+ const sourceRefs = observation.evidence_refs.map((ref) => {
17195
+ const span = spans.get(ref);
17196
+ if (!span || span.source_ref !== observation.source_ref || span.module_ref !== observation.module_ref || span.locator.path !== observation.full_relative_path || span.content_digest !== observation.content_digest) {
17197
+ throw new TypeError("Example selection source is outside the current dependency view or has changed");
17198
+ }
17199
+ return span.node_ref;
17200
+ }).sort(compareIndexerCanonicalText);
17201
+ const node = {
17202
+ kind: "selected-fact",
17203
+ fact_ref: fact.fact_ref,
17204
+ fact_digest: indexerProtocolDigest(fact),
17205
+ source_span_node_refs: sourceRefs,
17206
+ targets: []
17207
+ };
17208
+ return { ...node, node_ref: indexerDependencyNodeRef({ polarity: "positive", node }) };
17209
+ });
17210
+ }
17211
+
16711
17212
  // src/indexerRunProtocolCommon.ts
16712
17213
  var indexerRunFinalAuthoritySchema = exports_external.object({
16713
17214
  layer_ref: indexerProviderLayerRefSchema,
@@ -16841,6 +17342,10 @@ function buildIndexerPrimaryRegistryProjection(input) {
16841
17342
  owned_scope: "ref" in binding.owned_scope ? binding.owned_scope : { targets: canonicalTargets2(binding.owned_scope.targets) }
16842
17343
  })).sort((left, right) => compareIndexerCanonicalText(indexerProtocolDigest(left), indexerProtocolDigest(right)));
16843
17344
  const additionalProfiles = [...entry.profile.additional ?? []].sort((left, right) => compareIndexerCanonicalText(`${left.provider}\x00${left.id}\x00${left.kind}`, `${right.provider}\x00${right.id}\x00${right.kind}`));
17345
+ const readRequirementIds = new Set(entry.read_scope.refs.flatMap((ref) => {
17346
+ const match = /^requirement:([^#]+)#/u.exec(ref);
17347
+ return match ? [match[1]] : [];
17348
+ }));
16844
17349
  const payload = {
16845
17350
  protocol: "context.indexer.primary-registry-projection/v1",
16846
17351
  indexer_id: entry.id,
@@ -16848,6 +17353,7 @@ function buildIndexerPrimaryRegistryProjection(input) {
16848
17353
  requirement_bindings: requirementBindings,
16849
17354
  read_scope: {
16850
17355
  refs: [...entry.read_scope.refs].sort(compareIndexerCanonicalText),
17356
+ requirements: input.registry.requirements.filter((requirement) => readRequirementIds.has(requirement.id)).sort((a, b) => compareIndexerCanonicalText(a.id, b.id)),
16851
17357
  ...entry.read_scope.extra_targets === undefined ? {} : { extra_targets: canonicalTargets2(entry.read_scope.extra_targets) }
16852
17358
  },
16853
17359
  profile: {
@@ -17156,7 +17662,7 @@ var indexerArtifactDependencySetSchema = exports_external.object({
17156
17662
  artifacts: exports_external.array(artifactDependencySchema),
17157
17663
  dependency_set_digest: indexerDigestSchema
17158
17664
  }).strict();
17159
- function canonicalUnique5(values) {
17665
+ function canonicalUnique6(values) {
17160
17666
  return [...new Set(values)].sort(compareIndexerCanonicalText);
17161
17667
  }
17162
17668
  function versionedPositive(node) {
@@ -17179,8 +17685,8 @@ function artifactDependency(value) {
17179
17685
  }
17180
17686
  function artifactSections(artifact) {
17181
17687
  if (artifact.representation === "template") {
17182
- const factRefs = canonicalUnique5(Object.values(artifact.variables).flatMap((variable) => variable.fact_refs));
17183
- const evidenceRefs = canonicalUnique5(Object.values(artifact.variables).flatMap((variable) => variable.evidence_refs));
17688
+ const factRefs = canonicalUnique6(Object.values(artifact.variables).flatMap((variable) => variable.fact_refs));
17689
+ const evidenceRefs = canonicalUnique6(Object.values(artifact.variables).flatMap((variable) => variable.evidence_refs));
17184
17690
  return artifact.section_projections.map((section) => ({
17185
17691
  section_key: section.section_key,
17186
17692
  fact_refs: factRefs,
@@ -17189,8 +17695,8 @@ function artifactSections(artifact) {
17189
17695
  }
17190
17696
  return artifact.sections.map((section) => ({
17191
17697
  section_key: section.section_key,
17192
- fact_refs: canonicalUnique5(section.blocks.flatMap((block) => block.layer === "deterministic-block" ? block.fact_refs : [])),
17193
- evidence_refs: canonicalUnique5(section.blocks.flatMap((block) => block.layer === "semantic-prose" ? block.evidence_refs : []))
17698
+ fact_refs: canonicalUnique6(section.blocks.flatMap((block) => block.layer === "deterministic-block" ? block.fact_refs : [])),
17699
+ evidence_refs: canonicalUnique6(section.blocks.flatMap((block) => block.layer === "semantic-prose" ? block.evidence_refs : []))
17194
17700
  }));
17195
17701
  }
17196
17702
  function dependencySetPayload(value) {
@@ -17202,7 +17708,7 @@ function indexerArtifactDependencySetDigest(value) {
17202
17708
  }
17203
17709
  function assertBoundInputs(input) {
17204
17710
  const { result, workset, runEnvelope, dependencyView } = input;
17205
- if (dependencyView.view_digest !== workset.group_dependency_view_digest || runEnvelope.dependency_view_digest !== dependencyView.view_digest || dependencyView.source_ref !== result.source_ref || dependencyView.module_ref !== result.module_ref || dependencyView.logical_unit_ref !== result.logical_unit.logical_unit_ref || runEnvelope.workset_digest !== workset.workset_digest || runEnvelope.logical_unit_ref !== result.logical_unit.logical_unit_ref || runEnvelope.source_ref !== result.source_ref || runEnvelope.module_ref !== result.module_ref || runEnvelope.indexer_id !== result.indexer_id || runEnvelope.source_role !== result.source_role || runEnvelope.provider_layer_ref !== result.provider_layer_ref || runEnvelope.provider_integrity !== result.provider_integrity || runEnvelope.provider_bundle_digest !== result.provider_bundle_digest || runEnvelope.config_fingerprint !== result.config_fingerprint || runEnvelope.customization_fingerprint !== result.customization_fingerprint) {
17711
+ if (dependencyView.view_digest !== workset.group_dependency_view_digest || runEnvelope.dependency_view_digest !== dependencyView.view_digest || dependencyView.source_ref !== result.source_ref || dependencyView.module_ref !== result.module_ref || dependencyView.logical_unit_ref !== result.logical_unit.logical_unit_ref || runEnvelope.workset_digest !== workset.workset_digest || runEnvelope.logical_unit_ref !== result.logical_unit.logical_unit_ref || runEnvelope.source_ref !== result.source_ref || runEnvelope.module_ref !== result.module_ref || runEnvelope.indexer_id !== result.indexer_id || runEnvelope.source_role !== result.source_role || runEnvelope.provider_layer_ref !== result.provider_layer_ref) {
17206
17712
  throw new TypeError("Artifact dependency inputs do not bind the same current author run");
17207
17713
  }
17208
17714
  const logical = dependencyView.positive_nodes.find((node) => node.kind === "logical-unit");
@@ -17231,6 +17737,7 @@ function buildIndexerArtifactDependencySet(input) {
17231
17737
  });
17232
17738
  const sourceNodes = dependencyView.positive_nodes.filter((node) => node.kind === "source-span");
17233
17739
  const sourceByEvidence = new Map(sourceNodes.map((node) => [node.evidence_ref, node]));
17740
+ const sourceByNode = new Map(sourceNodes.map((node) => [node.node_ref, node]));
17234
17741
  const evidenceByRef = new Map(input.result.evidence_bindings.map((evidence) => {
17235
17742
  let node = sourceByEvidence.get(evidence.evidence_ref);
17236
17743
  const belongsToPrimary = evidence.source_ref === input.workset.source_ref && evidence.module_ref === input.workset.module_ref;
@@ -17253,23 +17760,18 @@ function buildIndexerArtifactDependencySet(input) {
17253
17760
  node_ref: indexerDependencyNodeRef({ polarity: "positive", node: supplemental })
17254
17761
  });
17255
17762
  }
17256
- if (node === undefined || canonicalIndexerJson({
17257
- source_ref: node.source_ref,
17258
- module_ref: node.module_ref,
17259
- locator: node.locator,
17260
- content_digest: node.content_digest
17261
- }) !== canonicalIndexerJson({
17262
- source_ref: evidence.source_ref,
17263
- module_ref: evidence.module_ref,
17264
- locator: evidence.locator,
17265
- content_digest: evidence.content_digest
17266
- })) {
17267
- throw new TypeError(`evidence ${evidence.evidence_ref} is absent or stale in the dependency view`);
17763
+ if (node === undefined || node.source_ref !== evidence.source_ref || node.module_ref !== evidence.module_ref || node.locator.path !== evidence.locator.path || node.content_digest !== evidence.content_digest) {
17764
+ throw new TypeError(`Source ${evidence.evidence_ref} is unavailable or its file content changed; refresh the current task's source material`);
17268
17765
  }
17269
- return [evidence.evidence_ref, versionedPositive(node)];
17766
+ const current = { ...node, locator: evidence.locator };
17767
+ return [evidence.evidence_ref, versionedPositive({
17768
+ ...current,
17769
+ node_ref: indexerDependencyNodeRef({ polarity: "positive", node: current })
17770
+ })];
17270
17771
  }));
17271
17772
  const factNodes = [
17272
17773
  ...dependencyView.positive_nodes.filter((node) => node.kind === "selected-fact"),
17774
+ ...exampleFactDependencies({ workset: input.workset, dependency_view: dependencyView, result: input.result }),
17273
17775
  ...input.composition_input === undefined ? [] : compositionFactDependencies({
17274
17776
  composition_input: input.composition_input,
17275
17777
  workset: input.workset,
@@ -17280,27 +17782,35 @@ function buildIndexerArtifactDependencySet(input) {
17280
17782
  const factNodeByRef = new Map(factNodes.map((node) => [node.fact_ref, node]));
17281
17783
  const factByRef = new Map(input.result.facts.map((fact) => {
17282
17784
  const node = factNodeByRef.get(fact.fact_ref);
17283
- const sourceSpanNodeRefs = canonicalUnique5(fact.evidence_refs.map((ref) => {
17785
+ const sourceSpanNodeRefs = canonicalUnique6(fact.evidence_refs.map((ref) => {
17284
17786
  const evidence = evidenceByRef.get(ref);
17285
17787
  if (evidence === undefined) {
17286
17788
  throw new TypeError(`Fact ${fact.fact_ref} references evidence outside the dependency view`);
17287
17789
  }
17288
17790
  return evidence.node_ref;
17289
17791
  }));
17290
- if (node === undefined || node.fact_digest !== indexerProtocolDigest(fact) || canonicalIndexerJson(node.source_span_node_refs) !== canonicalIndexerJson(sourceSpanNodeRefs)) {
17291
- throw new TypeError(`Fact ${fact.fact_ref} is absent or stale in the dependency view`);
17792
+ if (node === undefined) {
17793
+ throw new TypeError(`Fact ${fact.fact_ref} is not available in the current task; use a supplied Fact or source_items reference`);
17292
17794
  }
17293
- return [fact.fact_ref, versionedPositive(node)];
17795
+ const expectedEvidence = canonicalUnique6(node.source_span_node_refs.map((ref) => sourceByNode.get(ref).evidence_ref));
17796
+ if (canonicalIndexerJson(expectedEvidence) !== canonicalIndexerJson(canonicalUnique6(fact.evidence_refs))) {
17797
+ throw new TypeError(`Fact ${fact.fact_ref} refers to a different source than the current task`);
17798
+ }
17799
+ return [fact.fact_ref, versionedPositive({
17800
+ ...node,
17801
+ fact_digest: indexerProtocolDigest(fact),
17802
+ source_span_node_refs: sourceSpanNodeRefs
17803
+ })];
17294
17804
  }));
17295
17805
  const logical = versionedPositive(dependencyView.positive_nodes.find((node) => node.kind === "logical-unit"));
17296
- const resources = dependencyView.positive_nodes.filter((node) => node.kind === "template-policy-fragment" || node.kind === "contract-metric").map(versionedPositive);
17806
+ const resources = dependencyView.positive_nodes.filter((node) => node.kind === "template-policy-fragment" || node.kind === "contract-metric" || node.kind === "approved-knowledge").map(versionedPositive);
17297
17807
  const negatives = dependencyView.negative_nodes.map(versionedNegative);
17298
17808
  const usedPositive = new Map([[logical.node_ref, logical]]);
17299
17809
  const usedNegative = new Map;
17300
17810
  const artifacts = input.result.artifacts.map((artifact) => {
17301
17811
  const sections = artifactSections(artifact).map((section) => {
17302
17812
  const facts = section.fact_refs.map((ref) => factByRef.get(ref));
17303
- const evidenceRefs = canonicalUnique5([
17813
+ const evidenceRefs = canonicalUnique6([
17304
17814
  ...section.evidence_refs,
17305
17815
  ...section.fact_refs.flatMap((ref) => input.result.facts.find((fact) => fact.fact_ref === ref).evidence_refs)
17306
17816
  ]);
@@ -17326,20 +17836,20 @@ function buildIndexerArtifactDependencySet(input) {
17326
17836
  }
17327
17837
  return sectionDependency({
17328
17838
  section_key: section.section_key,
17329
- positive_dependency_refs: canonicalUnique5([
17839
+ positive_dependency_refs: canonicalUnique6([
17330
17840
  logical.dependency_ref,
17331
17841
  ...facts.map((item) => item.dependency_ref),
17332
17842
  ...evidence.map((item) => item.dependency_ref),
17333
17843
  ...sectionResources.map((item) => item.dependency_ref)
17334
17844
  ]),
17335
- negative_dependency_refs: canonicalUnique5(sectionNegatives.map((item) => item.dependency_ref))
17845
+ negative_dependency_refs: canonicalUnique6(sectionNegatives.map((item) => item.dependency_ref))
17336
17846
  });
17337
17847
  }).sort((left, right) => compareIndexerCanonicalText(left.section_key, right.section_key));
17338
17848
  return artifactDependency({
17339
17849
  artifact_id: artifact.artifact_id,
17340
17850
  artifact_kind: artifact.artifact_kind,
17341
- positive_dependency_refs: canonicalUnique5(sections.flatMap((section) => section.positive_dependency_refs)),
17342
- negative_dependency_refs: canonicalUnique5(sections.flatMap((section) => section.negative_dependency_refs)),
17851
+ positive_dependency_refs: canonicalUnique6(sections.flatMap((section) => section.positive_dependency_refs)),
17852
+ negative_dependency_refs: canonicalUnique6(sections.flatMap((section) => section.negative_dependency_refs)),
17343
17853
  sections
17344
17854
  });
17345
17855
  }).sort((left, right) => compareIndexerCanonicalText(left.artifact_id, right.artifact_id));
@@ -17468,7 +17978,8 @@ function validateIndexerTargetResolutionView(value) {
17468
17978
  }
17469
17979
  var indexerRepairIntentPayloadSchema = exports_external.object({
17470
17980
  target_ref: exports_external.string().min(1),
17471
- instruction: exports_external.string().trim().min(1)
17981
+ instruction: exports_external.string().trim().min(1),
17982
+ current_markdown: exports_external.string().optional()
17472
17983
  }).strict();
17473
17984
  var indexerRepairIntentSchema = indexerRepairIntentPayloadSchema.extend({
17474
17985
  intent_digest: indexerDigestSchema
@@ -17739,6 +18250,15 @@ var partitionGroupSchema = exports_external.object({
17739
18250
  subject_intent: exports_external.enum(["primary", "enrich-or-independent"]),
17740
18251
  logical_unit_ref: indexerCanonicalRefSchema,
17741
18252
  label: exports_external.string().min(1),
18253
+ scope_change: exports_external.object({ removed_member_ids: exports_external.array(indexerCanonicalRefSchema).min(1) }).strict().optional(),
18254
+ reader_task: exports_external.string().min(1).optional(),
18255
+ outline: exports_external.array(exports_external.string().min(1)).optional(),
18256
+ artifact_intent: exports_external.string().min(1).optional(),
18257
+ template_id: exports_external.string().min(1).optional(),
18258
+ articles: exports_external.array(indexerArticlePlanSchema).min(1).optional(),
18259
+ priority: exports_external.number().int().nonnegative().optional(),
18260
+ delivery_boundary: exports_external.boolean().optional(),
18261
+ ready_for_author: exports_external.boolean().optional(),
17742
18262
  reader_question_refs: exports_external.array(indexerCanonicalRefSchema),
17743
18263
  question_target_bindings: exports_external.array(questionTargetBindingSchema),
17744
18264
  member_ids: exports_external.array(indexerCanonicalRefSchema).min(1)
@@ -17897,6 +18417,8 @@ function validateGroups(plan, allowedQuestions, allowedTargets) {
17897
18417
  if (targetRefs.some((ref) => !allowedTargets.has(ref))) {
17898
18418
  throw new TypeError(`partition group ${group.group_key} creates an unknown question target`);
17899
18419
  }
18420
+ if (group.articles !== undefined)
18421
+ validateIndexerArticlePlan(group.articles, group.question_target_bindings.filter((binding) => binding.role === "primary-carrier").map((binding) => binding.target_ref));
17900
18422
  groups.set(group.group_key, group);
17901
18423
  }
17902
18424
  return groups;
@@ -17982,11 +18504,13 @@ function validateIndexerPartitionPlan(input) {
17982
18504
  });
17983
18505
  if (plan.status === "complete") {
17984
18506
  if (plan.groups.length === 0) {
17985
- if (plan.reader_question_refs.length > 0 || (input.required_question_target_refs ?? input.workset.allowed_question_target_refs).length > 0 || plan.member_dispositions.some((item) => item.inventory_disposition === "owned")) {
18507
+ if (plan.reader_question_refs.length > 0 || input.workset.reader_question_refs.length > 0 || (input.required_question_target_refs ?? input.workset.allowed_question_target_refs).length > 0 && !plan.member_dispositions.every((item) => item.inventory_disposition === "excluded-with-reason") || plan.member_dispositions.some((item) => item.inventory_disposition === "owned")) {
17986
18508
  throw new TypeError("empty complete PartitionPlan requires no reader questions, no targets, and no owned members");
17987
18509
  }
17988
18510
  }
17989
- validateQuestionTargetClosure(plan, input.required_question_target_refs ?? input.workset.allowed_question_target_refs);
18511
+ if (plan.groups.length > 0 || plan.member_dispositions.length === 0) {
18512
+ validateQuestionTargetClosure(plan, input.required_question_target_refs ?? input.workset.allowed_question_target_refs);
18513
+ }
17990
18514
  } else {
17991
18515
  const closed = new Set(plan.member_dispositions.map((item) => item.member_id));
17992
18516
  const expectedUnassigned = canonicalInventory.map((member) => member.member_id).filter((id) => !closed.has(id)).sort();
@@ -18078,7 +18602,7 @@ function indexerCatalogFallbackImplementationDigest(cliReleaseDigest) {
18078
18602
  cli_release_digest: indexerDigestSchema.parse(cliReleaseDigest)
18079
18603
  });
18080
18604
  }
18081
- function canonicalUnique6(values, field) {
18605
+ function canonicalUnique7(values, field) {
18082
18606
  const sorted = [...values].sort(compareIndexerCanonicalText);
18083
18607
  if (new Set(sorted).size !== sorted.length) {
18084
18608
  throw new TypeError(`${field} must not contain duplicate identities`);
@@ -18116,7 +18640,7 @@ function assertLocalDeclarations(input) {
18116
18640
  if (!Number.isSafeInteger(declaration.priority) || declaration.priority < 0) {
18117
18641
  throw new TypeError("local partition strategy priority must be a non-negative integer");
18118
18642
  }
18119
- const profiles = canonicalUnique6(declaration.profiles, "local strategy profiles");
18643
+ const profiles = canonicalUnique7(declaration.profiles, "local strategy profiles");
18120
18644
  if (profiles.some((profile) => !input.selectedProfiles.has(profile))) {
18121
18645
  throw new TypeError("local partition strategy references an unselected profile");
18122
18646
  }
@@ -18136,7 +18660,7 @@ function providerImplementationDigest(input) {
18136
18660
  }
18137
18661
  function resolveIndexerPartitionStrategies(input) {
18138
18662
  const indexerId = indexerIdSchema.parse(input.indexer_id);
18139
- const selectedProfiles = canonicalUnique6(input.selected_profile_ids, "selected partition profiles");
18663
+ const selectedProfiles = canonicalUnique7(input.selected_profile_ids, "selected partition profiles");
18140
18664
  const selectedProfileSet = new Set(selectedProfiles);
18141
18665
  const manifest = indexerProviderManifestSchema.parse(input.provider.manifest);
18142
18666
  if (manifest.id !== input.provider.id || manifest.version !== input.provider.version) {
@@ -18276,7 +18800,7 @@ function resolveIndexerPartitionStrategies(input) {
18276
18800
  }
18277
18801
  function validateIndexerPartitionStrategyResolution(valueInput) {
18278
18802
  const value = indexerPartitionStrategyResolutionSchema.parse(valueInput);
18279
- if (canonicalIndexerJson(value.selected_profile_ids) !== canonicalIndexerJson(canonicalUnique6(value.selected_profile_ids, "resolved selected_profile_ids"))) {
18803
+ if (canonicalIndexerJson(value.selected_profile_ids) !== canonicalIndexerJson(canonicalUnique7(value.selected_profile_ids, "resolved selected_profile_ids"))) {
18280
18804
  throw new TypeError("resolved selected_profile_ids are not canonical");
18281
18805
  }
18282
18806
  const expected = [...value.strategies].sort((left, right) => compareIndexerCanonicalText(strategySortKey(left), strategySortKey(right)));
@@ -18483,26 +19007,26 @@ function validateAttemptDigest(attempt) {
18483
19007
  }
18484
19008
  }
18485
19009
  function validateIndexerPartitionConvergenceRecord(value) {
18486
- const record = indexerPartitionConvergenceRecordSchema.parse(value);
18487
- record.attempts.forEach((attempt, index) => {
19010
+ const record3 = indexerPartitionConvergenceRecordSchema.parse(value);
19011
+ record3.attempts.forEach((attempt, index) => {
18488
19012
  validateAttemptDigest(attempt);
18489
19013
  if (attempt.strategy_order !== index) {
18490
19014
  throw new TypeError("partition convergence attempts must use contiguous strategy order");
18491
19015
  }
18492
- const expectedPrevious = index === 0 ? null : record.attempts[index - 1].attempt_digest;
19016
+ const expectedPrevious = index === 0 ? null : record3.attempts[index - 1].attempt_digest;
18493
19017
  if (attempt.previous_attempt_digest !== expectedPrevious) {
18494
19018
  throw new TypeError("partition convergence attempt lineage is invalid");
18495
19019
  }
18496
19020
  });
18497
- const last = record.attempts.at(-1);
18498
- const validDecision = record.decision === "accepted" ? last.classification === "semantic" && record.accepted_plan_hash === last.partition_plan_hash && record.next_strategy_attempt === null && record.outcome === "completed" : record.decision === "retry-required" ? last.classification !== "semantic" && last.classification !== "blocking-input-damage" && record.accepted_plan_hash === null && record.next_strategy_attempt !== null && record.next_strategy_attempt.previous_attempt_digest === last.attempt_digest && record.outcome === "partial" : record.decision === "catalog-fallback-required" ? last.classification !== "semantic" && last.classification !== "blocking-input-damage" && record.accepted_plan_hash === null && record.next_strategy_attempt !== null && record.next_strategy_attempt.strategy_ref.kind === "cli-builtin" && record.next_strategy_attempt.strategy_ref.strategy_id === INDEXER_CATALOG_FALLBACK_STRATEGY_ID && record.next_strategy_attempt.previous_attempt_digest === last.attempt_digest && record.outcome === "partial" : last.classification === "blocking-input-damage" && record.accepted_plan_hash === null && record.next_strategy_attempt === null && record.outcome === "failed";
19021
+ const last = record3.attempts.at(-1);
19022
+ const validDecision = record3.decision === "accepted" ? last.classification === "semantic" && record3.accepted_plan_hash === last.partition_plan_hash && record3.next_strategy_attempt === null && record3.outcome === "completed" : record3.decision === "retry-required" ? last.classification !== "semantic" && last.classification !== "blocking-input-damage" && record3.accepted_plan_hash === null && record3.next_strategy_attempt !== null && record3.next_strategy_attempt.previous_attempt_digest === last.attempt_digest && record3.outcome === "partial" : record3.decision === "catalog-fallback-required" ? last.classification !== "semantic" && last.classification !== "blocking-input-damage" && record3.accepted_plan_hash === null && record3.next_strategy_attempt !== null && record3.next_strategy_attempt.strategy_ref.kind === "cli-builtin" && record3.next_strategy_attempt.strategy_ref.strategy_id === INDEXER_CATALOG_FALLBACK_STRATEGY_ID && record3.next_strategy_attempt.previous_attempt_digest === last.attempt_digest && record3.outcome === "partial" : last.classification === "blocking-input-damage" && record3.accepted_plan_hash === null && record3.next_strategy_attempt === null && record3.outcome === "failed";
18499
19023
  if (!validDecision)
18500
19024
  throw new TypeError("partition convergence decision is inconsistent");
18501
- const payload = Object.fromEntries(Object.entries(record).filter(([key]) => key !== "convergence_digest"));
18502
- if (indexerProtocolDigest(payload) !== record.convergence_digest) {
19025
+ const payload = Object.fromEntries(Object.entries(record3).filter(([key]) => key !== "convergence_digest"));
19026
+ if (indexerProtocolDigest(payload) !== record3.convergence_digest) {
18503
19027
  throw new TypeError("partition convergence digest is invalid");
18504
19028
  }
18505
- return record;
19029
+ return record3;
18506
19030
  }
18507
19031
  function convergeIndexerPartitionPlan(input) {
18508
19032
  const strategies = canonicalStrategies(input.authorized_strategies);
@@ -18696,7 +19220,6 @@ function validateIndexerMainRunResult(input) {
18696
19220
  throw new TypeError("main run Result does not match its request/stage/input view");
18697
19221
  }
18698
19222
  let operationResult;
18699
- let authoringAudit = null;
18700
19223
  let artifactDependencySet = null;
18701
19224
  const runEnvelope = buildIndexerRunEnvelope({
18702
19225
  workset: request.workset,
@@ -18730,6 +19253,7 @@ function validateIndexerMainRunResult(input) {
18730
19253
  expected_provider: request.final_authority,
18731
19254
  expected_input_digest: request.execution_request_digest,
18732
19255
  expected_subject_key: input.validation.expected_subject_key,
19256
+ ...input.validation.page_plan?.articles === undefined ? {} : { planned_articles: input.validation.page_plan.articles },
18733
19257
  artifact_policy_eligibility: input.validation.artifact_policy_eligibility,
18734
19258
  allowed_source_roles: input.validation.allowed_source_roles,
18735
19259
  ...input.validation.authorized_evidence_targets === undefined ? {} : {
@@ -18744,7 +19268,6 @@ function validateIndexerMainRunResult(input) {
18744
19268
  if (operationResult.source_role !== request.run_environment.source_role) {
18745
19269
  throw new TypeError("author Result source role does not match the run environment");
18746
19270
  }
18747
- authoringAudit = buildIndexerGeneratedAuthoringAudit(operationResult);
18748
19271
  artifactDependencySet = buildIndexerArtifactDependencySet({
18749
19272
  result: operationResult,
18750
19273
  workset: request.workset,
@@ -18762,7 +19285,6 @@ function validateIndexerMainRunResult(input) {
18762
19285
  request,
18763
19286
  result,
18764
19287
  operation_result: operationResult,
18765
- authoring_audit: authoringAudit,
18766
19288
  artifact_dependency_set: artifactDependencySet,
18767
19289
  run_envelope: runEnvelope
18768
19290
  };
@@ -19232,11 +19754,7 @@ function validateIndexerInspectorResult(input) {
19232
19754
  if (expectedVariants === undefined) {
19233
19755
  throw new TypeError("inspector projection targets an inactive profile");
19234
19756
  }
19235
- for (const [axisId, value] of Object.entries(expectedVariants)) {
19236
- if (item.payload.profile_variants[axisId] !== value) {
19237
- throw new TypeError("inspector projection variant drifted from the active Registry profile");
19238
- }
19239
- }
19757
+ assertIndexerInspectorProfileVariants(item.payload, expectedVariants);
19240
19758
  for (const sourceFactRef of item.payload.source_fact_refs) {
19241
19759
  if (!inputFactRefs.has(sourceFactRef)) {
19242
19760
  throw new TypeError("inspector projection references a fact outside its input View");
@@ -19258,6 +19776,15 @@ function validateIndexerInspectorResult(input) {
19258
19776
  }
19259
19777
  return { result, evidence, fact_payloads: result.fact_payloads };
19260
19778
  }
19779
+ function assertIndexerInspectorProfileVariants(projection, expected) {
19780
+ for (const [axis, expectedValue] of Object.entries(expected)) {
19781
+ const observed = projection.profile_variants[axis];
19782
+ if (observed === undefined && projection.status !== "available")
19783
+ continue;
19784
+ if (observed !== expectedValue)
19785
+ throw new TypeError("inspector projection variant drifted from the active Registry profile");
19786
+ }
19787
+ }
19261
19788
  // src/indexerAuthorizedWorksetView.ts
19262
19789
  function isIndexerJson(value, ancestors = new WeakSet) {
19263
19790
  if (value === null || typeof value === "string" || typeof value === "boolean") {
@@ -19338,7 +19865,7 @@ var indexerAuthorizedWorksetViewSchema = exports_external.object({
19338
19865
  addDuplicateIssues(value.projection_input_digests, context, "projection_input_digests");
19339
19866
  addDuplicateIssues(value.items.map((item) => item.ref), context, "items.ref");
19340
19867
  });
19341
- function canonicalUnique7(values, field) {
19868
+ function canonicalUnique8(values, field) {
19342
19869
  const sorted = [...values].sort(compareIndexerCanonicalText);
19343
19870
  if (new Set(sorted).size !== sorted.length) {
19344
19871
  throw new TypeError(`${field} must contain unique values`);
@@ -19358,7 +19885,7 @@ function canonicalItem(value) {
19358
19885
  function canonicalSource(value) {
19359
19886
  const payload = authorizedWorksetViewSourcePayloadSchema.parse({
19360
19887
  ...value,
19361
- input_digests: canonicalUnique7(value.input_digests, "source.input_digests"),
19888
+ input_digests: canonicalUnique8(value.input_digests, "source.input_digests"),
19362
19889
  items: canonicalItems(value.items)
19363
19890
  });
19364
19891
  return indexerAuthorizedWorksetViewSourceSchema.parse({
@@ -19674,7 +20201,7 @@ function buildIndexerAuthorizedWorksetView(input) {
19674
20201
  }
19675
20202
  function validateIndexerAuthorizedWorksetView(value) {
19676
20203
  const view = indexerAuthorizedWorksetViewSchema.parse(value);
19677
- const projectionInputDigests = canonicalUnique7(view.projection_input_digests, "projection_input_digests");
20204
+ const projectionInputDigests = canonicalUnique8(view.projection_input_digests, "projection_input_digests");
19678
20205
  if (projectionInputDigests.some((digest, index) => digest !== view.projection_input_digests[index])) {
19679
20206
  throw new TypeError("projection_input_digests must use canonical ordering");
19680
20207
  }
@@ -23031,7 +23558,7 @@ function compareCoverageDomains(oldRequirement, newRequirement, changes) {
23031
23558
  }
23032
23559
  }
23033
23560
  function exclusionCells(requirement) {
23034
- return new Set((requirement.exclusions ?? []).flatMap((exclusion) => [...targetCellSet2(exclusion.scope.targets)].map((cell) => `${exclusion.id}\x00${cell}`)));
23561
+ return new Set((requirement.exclusions ?? []).flatMap((exclusion) => [...targetCellSet2(exclusion.scope.targets)].map((cell) => `${exclusion.id}\x00${cell}\x00${JSON.stringify([...exclusion.paths ?? []].sort())}`)));
23035
23562
  }
23036
23563
  function questionViewMap(views) {
23037
23564
  return new Map(views.map((view) => [`${view.ref}\x00${view.contractDigest}`, view]));
@@ -23195,6 +23722,14 @@ function compareIndexRequirementContraction(oldRequirement, newRequirement, opti
23195
23722
  throw new TypeError("Requirement comparator cannot replace a requirement identity");
23196
23723
  }
23197
23724
  const changes = [];
23725
+ if (oldRequirement.purpose !== newRequirement.purpose) {
23726
+ addChange(changes, {
23727
+ area: "reader-goals",
23728
+ path: "purpose",
23729
+ relation: "incomparable",
23730
+ detail: "reader purpose changed; its semantic relationship requires the stated user decision"
23731
+ });
23732
+ }
23198
23733
  compareSetArea({
23199
23734
  oldValues: targetCellSet2(oldRequirement.target_scope.targets),
23200
23735
  newValues: targetCellSet2(newRequirement.target_scope.targets),
@@ -23568,6 +24103,7 @@ function normalizeRequirement(requirement) {
23568
24103
  })).sort((left, right) => compareIndexerCanonicalText(left.source_ref, right.source_ref));
23569
24104
  return {
23570
24105
  id: requirement.id,
24106
+ ...requirement.purpose === undefined ? {} : { purpose: requirement.purpose },
23571
24107
  reader_goals: sortedUnique4(requirement.reader_goals, "reader_goals"),
23572
24108
  coverage_domains: Object.fromEntries(Object.entries(requirement.coverage_domains).sort(([left], [right]) => compareIndexerCanonicalText(left, right))),
23573
24109
  ...requirement.questions === undefined ? {} : {
@@ -26735,7 +27271,7 @@ var DIRECT_FACT_KIND_MAPPING = {
26735
27271
  "downstream-callsite": "downstream-callsite",
26736
27272
  "state-transition": "state-transition"
26737
27273
  };
26738
- function record(value) {
27274
+ function record3(value) {
26739
27275
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
26740
27276
  }
26741
27277
  function parserFactMemberKind(fact) {
@@ -26744,7 +27280,7 @@ function parserFactMemberKind(fact) {
26744
27280
  return direct;
26745
27281
  if (fact.denominator !== "symbol")
26746
27282
  return null;
26747
- const symbolKind = record(fact.payload)?.kind;
27283
+ const symbolKind = record3(fact.payload)?.kind;
26748
27284
  return symbolKind === "component" ? "component" : "entry";
26749
27285
  }
26750
27286
  function buildIndexerPartitionInventoryFromParserFactView(value) {
@@ -26843,7 +27379,7 @@ function nodePolarity(node) {
26843
27379
  function nodeVersionRef(node) {
26844
27380
  return indexerDependencyVersionRef({ polarity: nodePolarity(node), node });
26845
27381
  }
26846
- function canonicalUnique8(values) {
27382
+ function canonicalUnique9(values) {
26847
27383
  return [...new Set(values)].sort(compareIndexerCanonicalText);
26848
27384
  }
26849
27385
  function validateImpactInputs(input) {
@@ -26894,7 +27430,7 @@ function refsForCurrentNode(input) {
26894
27430
  section_key: section.section_key
26895
27431
  })));
26896
27432
  return {
26897
- artifactIds: canonicalUnique8(sections.map((section) => section.artifact_id)),
27433
+ artifactIds: canonicalUnique9(sections.map((section) => section.artifact_id)),
26898
27434
  sections
26899
27435
  };
26900
27436
  }
@@ -26902,7 +27438,7 @@ function buildDependencyChanges(input) {
26902
27438
  const previousNodes = new Map([...input.previousView.positive_nodes, ...input.previousView.negative_nodes].map((node) => [node.node_ref, node]));
26903
27439
  const currentNodes = new Map([...input.currentView.positive_nodes, ...input.currentView.negative_nodes].map((node) => [node.node_ref, node]));
26904
27440
  const previousDependencies = new Map([...input.previousSet.positive_dependencies, ...input.previousSet.negative_dependencies].map((dependency) => [dependency.node_ref, dependency]));
26905
- return canonicalUnique8([...previousNodes.keys(), ...currentNodes.keys()]).flatMap((nodeRef) => {
27441
+ return canonicalUnique9([...previousNodes.keys(), ...currentNodes.keys()]).flatMap((nodeRef) => {
26906
27442
  const previous = previousNodes.get(nodeRef);
26907
27443
  const current = currentNodes.get(nodeRef);
26908
27444
  const previousRef = previous === undefined ? null : nodeVersionRef(previous);
@@ -26927,7 +27463,7 @@ function buildDependencyChanges(input) {
26927
27463
  change: previous === undefined ? "added" : current === undefined ? "removed" : "changed",
26928
27464
  previous_dependency_ref: previousRef,
26929
27465
  current_dependency_ref: currentRef,
26930
- affected_artifact_ids: canonicalUnique8([
27466
+ affected_artifact_ids: canonicalUnique9([
26931
27467
  ...fromPrevious.artifactIds,
26932
27468
  ...fromCurrent.artifactIds
26933
27469
  ]),
@@ -26974,14 +27510,14 @@ function buildIndexerIncrementalImpactReport(input) {
26974
27510
  }
26975
27511
  const artifacts = validated.previousSet.artifacts.map((artifact) => {
26976
27512
  const sections = artifact.sections.map((section) => {
26977
- const changed2 = canonicalUnique8(changedBySection.get(`${artifact.artifact_id}\x00${section.section_key}`) ?? []);
27513
+ const changed2 = canonicalUnique9(changedBySection.get(`${artifact.artifact_id}\x00${section.section_key}`) ?? []);
26978
27514
  return {
26979
27515
  section_key: section.section_key,
26980
27516
  state: changed2.length === 0 ? "current" : "stale",
26981
27517
  changed_node_refs: changed2
26982
27518
  };
26983
27519
  });
26984
- const changed = canonicalUnique8(sections.flatMap((section) => section.changed_node_refs));
27520
+ const changed = canonicalUnique9(sections.flatMap((section) => section.changed_node_refs));
26985
27521
  return {
26986
27522
  artifact_id: artifact.artifact_id,
26987
27523
  artifact_kind: artifact.artifact_kind,
@@ -27352,11 +27888,11 @@ var indexerMainAcceptedRecordSchema = exports_external.object({
27352
27888
  acceptance_digest: indexerDigestSchema
27353
27889
  }).strict();
27354
27890
  function validateIndexerMainAcceptedRecord(value) {
27355
- const record2 = indexerMainAcceptedRecordSchema.parse(value);
27356
- if (record2.stage === "author" !== (record2.artifact_dependency_set_digest !== null)) {
27891
+ const record4 = indexerMainAcceptedRecordSchema.parse(value);
27892
+ if (record4.stage === "author" !== (record4.artifact_dependency_set_digest !== null)) {
27357
27893
  throw new TypeError("accepted author records require an Artifact dependency set and partition records forbid one");
27358
27894
  }
27359
- return record2;
27895
+ return record4;
27360
27896
  }
27361
27897
  function buildIndexerMainAcceptedRecord(input) {
27362
27898
  const payload2 = {
@@ -27441,41 +27977,41 @@ var indexerMainWorksetStatusSchema = exports_external.object({
27441
27977
  function observeIndexerMainWorksetState(input) {
27442
27978
  const currentSet = validateIndexerMainWorksetSet(input.workset_set);
27443
27979
  const records = input.records.map((value) => {
27444
- const record2 = indexerMainStateRecordSchema.parse(value);
27445
- if (record2.state === "accepted") {
27446
- const { state: _state, ...accepted2 } = record2;
27980
+ const record4 = indexerMainStateRecordSchema.parse(value);
27981
+ if (record4.state === "accepted") {
27982
+ const { state: _state, ...accepted2 } = record4;
27447
27983
  validateIndexerMainAcceptedRecord(accepted2);
27448
27984
  }
27449
- return record2;
27985
+ return record4;
27450
27986
  });
27451
- if (new Set(records.map((record2) => record2.workset_digest)).size !== records.length) {
27987
+ if (new Set(records.map((record4) => record4.workset_digest)).size !== records.length) {
27452
27988
  throw new TypeError("main workset state contains duplicate workset records");
27453
27989
  }
27454
- const byDigest = new Map(records.map((record2) => [record2.workset_digest, record2]));
27990
+ const byDigest = new Map(records.map((record4) => [record4.workset_digest, record4]));
27455
27991
  const currentItems = new Map(currentSet.items.map((item) => [item.workset_digest, item]));
27456
- for (const record2 of records) {
27457
- const item = currentItems.get(record2.workset_digest);
27992
+ for (const record4 of records) {
27993
+ const item = currentItems.get(record4.workset_digest);
27458
27994
  if (item === undefined) {
27459
27995
  throw new TypeError("main workset state contains a record outside the current set");
27460
27996
  }
27461
- if (record2.state === "accepted") {
27997
+ if (record4.state === "accepted") {
27462
27998
  const payload3 = {
27463
- protocol: record2.protocol,
27464
- workset_digest: record2.workset_digest,
27465
- stage: record2.stage,
27466
- execution_request_digest: record2.execution_request_digest,
27467
- result_digest: record2.result_digest,
27468
- receipt_digest: record2.receipt_digest,
27469
- run_envelope_digest: record2.run_envelope_digest,
27470
- artifact_dependency_set_digest: record2.artifact_dependency_set_digest
27999
+ protocol: record4.protocol,
28000
+ workset_digest: record4.workset_digest,
28001
+ stage: record4.stage,
28002
+ execution_request_digest: record4.execution_request_digest,
28003
+ result_digest: record4.result_digest,
28004
+ receipt_digest: record4.receipt_digest,
28005
+ run_envelope_digest: record4.run_envelope_digest,
28006
+ artifact_dependency_set_digest: record4.artifact_dependency_set_digest
27471
28007
  };
27472
- if (record2.stage !== item.stage || indexerProtocolDigest(payload3) !== record2.acceptance_digest) {
28008
+ if (record4.stage !== item.stage || indexerProtocolDigest(payload3) !== record4.acceptance_digest) {
27473
28009
  throw new TypeError("accepted main result record is stale or has an invalid digest");
27474
28010
  }
27475
28011
  }
27476
- if (record2.state === "failed") {
27477
- const dependencies = [...record2.dependency_digests].sort(compareIndexerCanonicalText);
27478
- if (new Set(dependencies).size !== dependencies.length || dependencies.some((digest, index) => digest !== record2.dependency_digests[index])) {
28012
+ if (record4.state === "failed") {
28013
+ const dependencies = [...record4.dependency_digests].sort(compareIndexerCanonicalText);
28014
+ if (new Set(dependencies).size !== dependencies.length || dependencies.some((digest, index) => digest !== record4.dependency_digests[index])) {
27479
28015
  throw new TypeError("failed main result dependencies must be unique and canonical");
27480
28016
  }
27481
28017
  }
@@ -27488,22 +28024,22 @@ function observeIndexerMainWorksetState(input) {
27488
28024
  }
27489
28025
  }));
27490
28026
  const counts = {
27491
- pending: joined.filter(({ record: record2 }) => record2.state === "pending" || record2.state === "running").length,
27492
- accepted: joined.filter(({ record: record2 }) => record2.state === "accepted").length,
27493
- failed: joined.filter(({ record: record2 }) => record2.state === "failed").length,
27494
- stale: joined.filter(({ record: record2 }) => record2.state === "stale").length
28027
+ pending: joined.filter(({ record: record4 }) => record4.state === "pending" || record4.state === "running").length,
28028
+ accepted: joined.filter(({ record: record4 }) => record4.state === "accepted").length,
28029
+ failed: joined.filter(({ record: record4 }) => record4.state === "failed").length,
28030
+ stale: joined.filter(({ record: record4 }) => record4.state === "stale").length
27495
28031
  };
27496
- const nextRefs = joined.filter(({ record: record2 }) => record2.state !== "accepted" && record2.state !== "running").map(({ item, record: record2 }) => ({
28032
+ const nextRefs = joined.filter(({ record: record4 }) => record4.state !== "accepted" && record4.state !== "running").map(({ item, record: record4 }) => ({
27497
28033
  ...item,
27498
- state: record2.state
28034
+ state: record4.state
27499
28035
  }));
27500
- const accepted = joined.filter((item) => item.record.state === "accepted").map(({ record: record2 }) => ({
27501
- workset_digest: record2.workset_digest,
27502
- execution_request_digest: record2.execution_request_digest,
27503
- result_digest: record2.result_digest,
27504
- receipt_digest: record2.receipt_digest,
27505
- run_envelope_digest: record2.run_envelope_digest,
27506
- artifact_dependency_set_digest: record2.artifact_dependency_set_digest
28036
+ const accepted = joined.filter((item) => item.record.state === "accepted").map(({ record: record4 }) => ({
28037
+ workset_digest: record4.workset_digest,
28038
+ execution_request_digest: record4.execution_request_digest,
28039
+ result_digest: record4.result_digest,
28040
+ receipt_digest: record4.receipt_digest,
28041
+ run_envelope_digest: record4.run_envelope_digest,
28042
+ artifact_dependency_set_digest: record4.artifact_dependency_set_digest
27507
28043
  })).sort((left, right) => compareIndexerCanonicalText(left.workset_digest, right.workset_digest));
27508
28044
  const outcome = counts.failed > 0 ? "index-main-workset-failed" : counts.stale > 0 ? "index-main-workset-stale" : counts.pending > 0 ? "index-main-workset-pending" : "complete";
27509
28045
  const payload2 = {
@@ -27648,6 +28184,98 @@ function validateIndexerAgentStepInput(value) {
27648
28184
  }
27649
28185
  return input;
27650
28186
  }
28187
+ // src/readingStructure.ts
28188
+ var readingStructureEntrySchema = exports_external.object({
28189
+ key: exports_external.string().min(1),
28190
+ parent: exports_external.string().min(1).nullable(),
28191
+ title: exports_external.string().min(1),
28192
+ order: exports_external.number().finite().default(0),
28193
+ target: exports_external.object({
28194
+ artifact_ref: exports_external.string().min(1),
28195
+ section_key: exports_external.string().min(1).optional()
28196
+ }).strict().optional()
28197
+ }).strict();
28198
+ var readingStructureUpdateSchema = exports_external.object({
28199
+ expected_revision: exports_external.string().nullable(),
28200
+ upsert: exports_external.array(readingStructureEntrySchema).default([]),
28201
+ remove: exports_external.array(exports_external.string().min(1)).default([])
28202
+ }).strict();
28203
+ var readingStructureSchema = exports_external.object({
28204
+ protocol: exports_external.literal("context.reading-structure/v1"),
28205
+ revision: exports_external.string().min(1),
28206
+ entries: exports_external.array(readingStructureEntrySchema)
28207
+ }).strict();
28208
+ function validateEntries(entries) {
28209
+ const indexed = new Map(entries.map((entry) => [entry.key, entry]));
28210
+ if (indexed.size !== entries.length)
28211
+ throw new TypeError("reading entries must have unique keys");
28212
+ for (const entry of entries) {
28213
+ const visited = new Set;
28214
+ let current = entry;
28215
+ while (current !== undefined) {
28216
+ if (visited.has(current.key))
28217
+ throw new TypeError("reading structure contains a parent cycle");
28218
+ visited.add(current.key);
28219
+ if (current.parent === null)
28220
+ break;
28221
+ const parent = indexed.get(current.parent);
28222
+ if (parent === undefined)
28223
+ throw new TypeError(`reading entry ${current.key} has an unknown parent`);
28224
+ current = parent;
28225
+ }
28226
+ }
28227
+ }
28228
+ function validateReadingStructure(value) {
28229
+ const result = readingStructureSchema.parse(value);
28230
+ validateEntries(result.entries);
28231
+ const { revision, ...payload2 } = result;
28232
+ if (indexerProtocolDigest(payload2) !== revision)
28233
+ throw new TypeError("reading structure revision does not match its content");
28234
+ return result;
28235
+ }
28236
+ function updateReadingStructure(current, value) {
28237
+ const update = readingStructureUpdateSchema.parse(value);
28238
+ if ((current?.revision ?? null) !== update.expected_revision)
28239
+ throw new TypeError("reading structure changed; reread the current structure before applying this edit");
28240
+ const keys = update.upsert.map((entry) => entry.key);
28241
+ if (new Set(keys).size !== keys.length || new Set(update.remove).size !== update.remove.length || keys.some((key) => update.remove.includes(key))) {
28242
+ throw new TypeError("reading structure update contains conflicting entry identities");
28243
+ }
28244
+ const entries = new Map(current?.entries.map((entry) => [entry.key, entry]) ?? []);
28245
+ for (const key of update.remove)
28246
+ entries.delete(key);
28247
+ for (const entry of update.upsert)
28248
+ entries.set(entry.key, entry);
28249
+ const payload2 = {
28250
+ protocol: "context.reading-structure/v1",
28251
+ entries: [...entries.values()].sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0)
28252
+ };
28253
+ validateEntries(payload2.entries);
28254
+ return { ...payload2, revision: indexerProtocolDigest(payload2) };
28255
+ }
28256
+ function projectReadingStructure(structure, targets) {
28257
+ const children = new Map;
28258
+ for (const entry of structure.entries)
28259
+ children.set(entry.parent, [...children.get(entry.parent) ?? [], entry]);
28260
+ const warnings = [];
28261
+ function project(parent) {
28262
+ return (children.get(parent) ?? []).sort((a, b) => a.order - b.order || a.key.localeCompare(b.key)).flatMap((entry) => {
28263
+ const descendants = project(entry.key);
28264
+ const identity2 = entry.target === undefined ? undefined : readingTargetKey(entry.target);
28265
+ const href = identity2 === undefined ? undefined : targets.get(identity2);
28266
+ if (identity2 !== undefined && href === undefined)
28267
+ warnings.push({ entry: entry.key, code: "reading-target-unavailable", target: identity2 });
28268
+ if (href === undefined && descendants.length === 0)
28269
+ return [];
28270
+ return [{ key: entry.key, title: entry.title, ...href === undefined ? {} : { href }, children: descendants }];
28271
+ });
28272
+ }
28273
+ return { entries: project(null), warnings };
28274
+ }
28275
+ function readingTargetKey(target) {
28276
+ return target.section_key === undefined ? target.artifact_ref : `${target.artifact_ref}#${encodeURIComponent(target.section_key)}`;
28277
+ }
28278
+
27651
28279
  // src/indexerSemanticInput.ts
27652
28280
  var providerObservationSchema = exports_external.object({
27653
28281
  skill: exports_external.string().min(1),
@@ -27689,6 +28317,12 @@ var partitionGroupSchema2 = exports_external.object({
27689
28317
  key: exports_external.string().min(1),
27690
28318
  title: exports_external.string().min(1),
27691
28319
  reader_task: exports_external.string().min(1),
28320
+ artifact_intent: exports_external.string().min(1).optional(),
28321
+ template_id: exports_external.string().min(1).optional(),
28322
+ articles: exports_external.array(indexerArticlePlanSchema).min(1).optional(),
28323
+ priority: exports_external.number().int().nonnegative().optional(),
28324
+ delivery_boundary: exports_external.boolean().optional(),
28325
+ ready_for_author: exports_external.boolean().optional(),
27692
28326
  subject: subjectChoiceSchema,
27693
28327
  subject_intent: exports_external.enum(["primary", "enrich-or-independent"]),
27694
28328
  members: exports_external.array(exports_external.string().min(1)).min(1),
@@ -27741,18 +28375,38 @@ var indexerPartitionSemanticInputSchema = exports_external.union([
27741
28375
  function validateIndexerPartitionSemanticInput(value) {
27742
28376
  return indexerPartitionSemanticInputSchema.parse(value);
27743
28377
  }
28378
+ var authorVisualSchema = exports_external.object({
28379
+ resource: exports_external.string().min(1),
28380
+ also_read: exports_external.array(exports_external.string().min(1)).optional(),
28381
+ context: exports_external.array(exports_external.string()).default([]),
28382
+ requirements: exports_external.string().default(""),
28383
+ disposition: exports_external.enum(["converted", "retained"]),
28384
+ format: exports_external.enum(["mermaid", "table", "original"]),
28385
+ markdown: exports_external.string().optional(),
28386
+ reason: exports_external.string().optional()
28387
+ }).strict();
27744
28388
  var authorSectionSchema = exports_external.object({
27745
28389
  key: exports_external.string().min(1),
27746
28390
  heading: exports_external.string().min(1),
28391
+ visuals: exports_external.array(authorVisualSchema).optional(),
27747
28392
  markdown: exports_external.string().min(1),
27748
- source_items: exports_external.array(exports_external.string().min(1)).min(1),
28393
+ source_items: exports_external.array(exports_external.string().min(1)).default([]),
27749
28394
  facts: exports_external.array(exports_external.string().min(1)).default([]),
27750
28395
  answers: exports_external.array(exports_external.string().min(1)).default([])
27751
28396
  }).strict();
28397
+ var authorTemplateVariablesSchema = exports_external.record(exports_external.union([
28398
+ exports_external.string(),
28399
+ exports_external.object({
28400
+ value: exports_external.string(),
28401
+ source_items: exports_external.array(exports_external.string().min(1)).default([]),
28402
+ facts: exports_external.array(exports_external.string().min(1)).default([])
28403
+ }).strict()
28404
+ ]));
27752
28405
  var authorMemberDispositionSchema = exports_external.object({
27753
28406
  item: exports_external.string().min(1),
27754
28407
  state: exports_external.enum(["covered", "catalog-only", "unsupported"]),
27755
28408
  section: exports_external.string().min(1).optional(),
28409
+ article: indexerArticleKeySchema.optional(),
27756
28410
  reason_code: exports_external.string().min(1).optional()
27757
28411
  }).strict();
27758
28412
  var authorMaterialGapSchema = exports_external.object({
@@ -27764,11 +28418,24 @@ var authorDiagnosticSchema = exports_external.object({
27764
28418
  message: exports_external.string().min(1),
27765
28419
  target: exports_external.string().min(1).optional()
27766
28420
  }).strict();
27767
- var indexerAuthorSemanticInputSchema = exports_external.object({
28421
+ var authorInputBaseSchema = exports_external.object({
27768
28422
  stage: exports_external.literal("author"),
27769
28423
  group_key: exports_external.string().min(1),
27770
28424
  outcome: exports_external.enum(["publish", "catalog-only", "request-material", "unsupported"]),
28425
+ articles: exports_external.array(exports_external.object({
28426
+ key: indexerArticleKeySchema,
28427
+ title: exports_external.string().min(1),
28428
+ summary: exports_external.string().min(1),
28429
+ artifact_intent: exports_external.string().min(1).optional(),
28430
+ template_variables: authorTemplateVariablesSchema.optional(),
28431
+ sections: exports_external.array(authorSectionSchema).min(1)
28432
+ }).strict()).min(1).optional(),
27771
28433
  artifact_intent: exports_external.string().min(1).optional(),
28434
+ template_variables: authorTemplateVariablesSchema.optional(),
28435
+ example_candidates: exports_external.array(exports_external.object({
28436
+ scenario_key: indexerIdSchema,
28437
+ source_item: exports_external.string().min(1)
28438
+ }).strict()).optional(),
27772
28439
  policy: exports_external.string().min(1).optional(),
27773
28440
  target_resolutions: exports_external.array(exports_external.object({
27774
28441
  target: exports_external.string().min(1),
@@ -27778,32 +28445,36 @@ var indexerAuthorSemanticInputSchema = exports_external.object({
27778
28445
  title: exports_external.string().min(1).optional(),
27779
28446
  summary: exports_external.string().min(1).optional(),
27780
28447
  sections: exports_external.array(authorSectionSchema).default([]),
27781
- member_dispositions: exports_external.array(authorMemberDispositionSchema),
28448
+ member_dispositions: exports_external.array(exports_external.union([
28449
+ authorMemberDispositionSchema,
28450
+ authorMemberDispositionSchema.omit({ item: true }).extend({ items: exports_external.array(exports_external.string().min(1)).min(1) }).strict()
28451
+ ])).transform((entries) => entries.flatMap((entry) => {
28452
+ if ("item" in entry)
28453
+ return [entry];
28454
+ const { items, ...disposition } = entry;
28455
+ return items.map((item) => ({ item, ...disposition }));
28456
+ })),
27782
28457
  material_gaps: exports_external.array(authorMaterialGapSchema).default([]),
27783
28458
  diagnostics: exports_external.array(authorDiagnosticSchema).default([])
27784
- }).strict().superRefine((value, context) => {
27785
- if (value.outcome === "publish" && value.sections.length === 0) {
27786
- context.addIssue({
27787
- code: exports_external.ZodIssueCode.custom,
27788
- path: ["sections"],
27789
- message: "publish requires at least one reader-facing section"
27790
- });
27791
- }
27792
- if (value.outcome === "publish" && value.title === undefined) {
27793
- context.addIssue({
27794
- code: exports_external.ZodIssueCode.custom,
27795
- path: ["title"],
27796
- message: "publish requires a reader-facing title"
27797
- });
27798
- }
27799
- if (value.outcome === "publish" && value.summary === undefined) {
27800
- context.addIssue({
27801
- code: exports_external.ZodIssueCode.custom,
27802
- path: ["summary"],
27803
- message: "publish requires a reader-facing summary"
27804
- });
27805
- }
27806
- });
28459
+ }).strict();
28460
+ var indexerAuthorSemanticInputSchema = exports_external.union([
28461
+ authorInputBaseSchema.extend({
28462
+ outcome: exports_external.literal("publish"),
28463
+ title: exports_external.string().min(1),
28464
+ summary: exports_external.string().min(1),
28465
+ sections: exports_external.array(authorSectionSchema).min(1)
28466
+ }),
28467
+ authorInputBaseSchema.extend({
28468
+ outcome: exports_external.literal("publish"),
28469
+ articles: authorInputBaseSchema.shape.articles.unwrap(),
28470
+ title: exports_external.string().optional(),
28471
+ summary: exports_external.string().optional(),
28472
+ sections: exports_external.array(authorSectionSchema).max(0).default([])
28473
+ }),
28474
+ authorInputBaseSchema.extend({ outcome: exports_external.literal("catalog-only") }),
28475
+ authorInputBaseSchema.extend({ outcome: exports_external.literal("request-material") }),
28476
+ authorInputBaseSchema.extend({ outcome: exports_external.literal("unsupported") })
28477
+ ]);
27807
28478
  var indexerPartitionBatchSemanticInputSchema = exports_external.object({
27808
28479
  stage: exports_external.literal("partition"),
27809
28480
  results: exports_external.array(exports_external.object({
@@ -27846,10 +28517,11 @@ var indexerMainBatchSubmissionEnvelopeSchema = exports_external.object({
27846
28517
  var postAuthorSectionSchema = exports_external.object({
27847
28518
  key: exports_external.string().min(1),
27848
28519
  heading: exports_external.string().min(1),
28520
+ visuals: exports_external.array(authorVisualSchema).optional(),
27849
28521
  markdown: exports_external.string().min(1),
27850
28522
  source_refs: exports_external.array(exports_external.string().min(1)).min(1)
27851
28523
  }).strict();
27852
- var indexerPostAuthorSemanticInputSchema = exports_external.object({
28524
+ var postAuthorInputBaseSchema = exports_external.object({
27853
28525
  stage: exports_external.literal("post-author"),
27854
28526
  outcome: exports_external.enum(["complete", "failed"]),
27855
28527
  proposals: exports_external.array(exports_external.object({
@@ -27860,15 +28532,14 @@ var indexerPostAuthorSemanticInputSchema = exports_external.object({
27860
28532
  sections: exports_external.array(postAuthorSectionSchema).min(1)
27861
28533
  }).strict()).default([]),
27862
28534
  diagnostics: exports_external.array(authorDiagnosticSchema).default([])
27863
- }).strict().superRefine((value, context) => {
27864
- if (value.outcome === "failed" && value.diagnostics.length === 0) {
27865
- context.addIssue({
27866
- code: exports_external.ZodIssueCode.custom,
27867
- path: ["diagnostics"],
27868
- message: "failed post-author composition requires a diagnostic"
27869
- });
27870
- }
27871
- });
28535
+ }).strict();
28536
+ var indexerPostAuthorSemanticInputSchema = exports_external.discriminatedUnion("outcome", [
28537
+ postAuthorInputBaseSchema.extend({ outcome: exports_external.literal("complete") }),
28538
+ postAuthorInputBaseSchema.extend({
28539
+ outcome: exports_external.literal("failed"),
28540
+ diagnostics: exports_external.array(authorDiagnosticSchema).min(1)
28541
+ })
28542
+ ]);
27872
28543
  var indexerPostAuthorBatchSemanticInputSchema = exports_external.object({
27873
28544
  stage: exports_external.literal("post-author"),
27874
28545
  results: exports_external.array(exports_external.object({
@@ -27885,20 +28556,21 @@ var indexerPostAuthorBatchSemanticInputSchema = exports_external.object({
27885
28556
  });
27886
28557
  }
27887
28558
  });
27888
- var indexerStructureReviewInputSchema = exports_external.object({
28559
+ var structureReviewBaseSchema = exports_external.object({
27889
28560
  stage: exports_external.literal("structure-review"),
27890
- decision: exports_external.enum(["approved", "request-adjustment"]),
28561
+ reading_structure: readingStructureUpdateSchema.optional(),
28562
+ decision: exports_external.enum(["approved", "exclude-obsolete", "request-adjustment"]),
27891
28563
  feedback: exports_external.string().min(1).optional()
27892
- }).strict().superRefine((value, context) => {
27893
- if (value.decision === "request-adjustment" && value.feedback === undefined) {
27894
- context.addIssue({
27895
- code: exports_external.ZodIssueCode.custom,
27896
- path: ["feedback"],
27897
- message: "request-adjustment requires feedback"
27898
- });
27899
- }
27900
- });
27901
- var indexerLayoutConfirmationInputSchema = exports_external.object({
28564
+ }).strict();
28565
+ var indexerStructureReviewInputSchema = exports_external.discriminatedUnion("decision", [
28566
+ structureReviewBaseSchema.extend({ decision: exports_external.literal("approved") }),
28567
+ structureReviewBaseSchema.extend({ decision: exports_external.literal("exclude-obsolete") }),
28568
+ structureReviewBaseSchema.extend({
28569
+ decision: exports_external.literal("request-adjustment"),
28570
+ feedback: exports_external.string().min(1)
28571
+ })
28572
+ ]);
28573
+ var layoutConfirmationBaseSchema = exports_external.object({
27902
28574
  stage: exports_external.literal("layout-confirmation"),
27903
28575
  decision: exports_external.enum(["approved", "rejected"]),
27904
28576
  feedback: exports_external.string().min(1).optional(),
@@ -27906,23 +28578,57 @@ var indexerLayoutConfirmationInputSchema = exports_external.object({
27906
28578
  artifact_ref: exports_external.string().min(1),
27907
28579
  output_path: exports_external.string().min(1)
27908
28580
  }).strict()).min(1).optional()
27909
- }).strict().superRefine((value, context) => {
27910
- if (value.decision === "rejected" && value.feedback === undefined) {
27911
- context.addIssue({
27912
- code: exports_external.ZodIssueCode.custom,
27913
- path: ["feedback"],
27914
- message: "rejected layout confirmation requires feedback"
27915
- });
27916
- }
27917
- if (value.decision === "rejected" && value.paths !== undefined) {
27918
- context.addIssue({
27919
- code: exports_external.ZodIssueCode.custom,
27920
- path: ["paths"],
27921
- message: "only an approved layout can select output paths"
27922
- });
27923
- }
27924
- });
28581
+ }).strict();
28582
+ var indexerLayoutConfirmationInputSchema = exports_external.discriminatedUnion("decision", [
28583
+ layoutConfirmationBaseSchema.extend({ decision: exports_external.literal("approved") }),
28584
+ layoutConfirmationBaseSchema.omit({ paths: true }).extend({
28585
+ decision: exports_external.literal("rejected"),
28586
+ feedback: exports_external.string().min(1)
28587
+ })
28588
+ ]);
28589
+ var approvedRevisionSemanticInputSchema = exports_external.union([
28590
+ exports_external.object({ stage: exports_external.literal("approved-revision"), markdown: exports_external.string().min(1) }).strict(),
28591
+ exports_external.object({
28592
+ stage: exports_external.literal("approved-revision"),
28593
+ sections: exports_external.array(exports_external.object({
28594
+ section_id: exports_external.string().min(1),
28595
+ content: exports_external.array(exports_external.union([
28596
+ exports_external.object({ markdown: exports_external.string() }).strict(),
28597
+ exports_external.object({ program: exports_external.string().min(1) }).strict()
28598
+ ])).min(1)
28599
+ }).strict()).min(1)
28600
+ }).strict()
28601
+ ]);
28602
+ var sourceUpdateSemanticInputSchema = exports_external.object({
28603
+ stage: exports_external.literal("source-update"),
28604
+ decisions: exports_external.array(exports_external.object({
28605
+ path: exports_external.string().min(1),
28606
+ instruction: exports_external.string().trim().min(1).optional(),
28607
+ supporting_sources: exports_external.array(exports_external.string().min(1)).min(1).optional()
28608
+ }).strict()),
28609
+ scope_summary: exports_external.string().trim().min(1),
28610
+ new_topics: exports_external.array(exports_external.object({
28611
+ path: exports_external.string().trim().min(1),
28612
+ title: exports_external.string().trim().min(1),
28613
+ source_refs: exports_external.array(exports_external.string().min(1)).min(1),
28614
+ instruction: exports_external.string().trim().min(1)
28615
+ }).strict())
28616
+ }).strict();
28617
+ var indexerCurrentActionInputDefinitions = {
28618
+ sourceUpdate: sourceUpdateSemanticInputSchema,
28619
+ approvedRevision: approvedRevisionSemanticInputSchema,
28620
+ providerSelection: indexerProviderSelectionSemanticInputSchema,
28621
+ providerResolution: indexerProviderResolutionSemanticInputSchema,
28622
+ providerProgramAuthorization: indexerProviderProgramAuthorizationSemanticInputSchema,
28623
+ partitionBatch: indexerPartitionBatchSemanticInputSchema,
28624
+ authorBatch: indexerAuthorBatchSemanticInputSchema,
28625
+ postAuthor: indexerPostAuthorBatchSemanticInputSchema,
28626
+ structureReview: indexerStructureReviewInputSchema,
28627
+ layoutConfirmation: indexerLayoutConfirmationInputSchema
28628
+ };
27925
28629
  var indexerCurrentActionInputSchema = exports_external.union([
28630
+ sourceUpdateSemanticInputSchema,
28631
+ approvedRevisionSemanticInputSchema,
27926
28632
  indexerProviderSelectionSemanticInputSchema,
27927
28633
  indexerProviderResolutionSemanticInputSchema,
27928
28634
  indexerProviderProgramAuthorizationSemanticInputSchema,
@@ -27941,128 +28647,6 @@ function parseIndexerCurrentActionSubmission(value) {
27941
28647
  }
27942
28648
  return validateIndexerCurrentActionInput(value);
27943
28649
  }
27944
- // src/indexerExampleIdentity.ts
27945
- var exampleObservationSchema = exports_external.object({
27946
- observation_ref: indexerCanonicalRefSchema,
27947
- example_ref: indexerCanonicalRefSchema,
27948
- public_target_ref: indexerCanonicalRefSchema,
27949
- scenario_key: indexerIdSchema,
27950
- source_ref: indexerCanonicalRefSchema,
27951
- module_ref: indexerCanonicalRefSchema.nullable(),
27952
- full_relative_path: portableIndexerPathSchema,
27953
- content_digest: indexerDigestSchema,
27954
- evidence_refs: exports_external.array(indexerCanonicalRefSchema).min(1)
27955
- }).strict();
27956
- var indexerExampleInventorySchema = exports_external.object({
27957
- protocol: exports_external.literal("context.indexer.example-inventory/v1"),
27958
- source_scope_digest: indexerDigestSchema,
27959
- observations: exports_external.array(exampleObservationSchema),
27960
- inventory_digest: indexerDigestSchema
27961
- }).strict();
27962
- function canonicalUnique9(values, field) {
27963
- const sorted = [...values].sort(compareIndexerCanonicalText);
27964
- if (new Set(sorted).size !== sorted.length) {
27965
- throw new TypeError(`${field} must not contain duplicate identities`);
27966
- }
27967
- return sorted;
27968
- }
27969
- function normalizeIndexerExampleRelativePath(value) {
27970
- const normalized = value.normalize("NFC").replaceAll("\\", "/").replace(/^\.\//u, "");
27971
- return portableIndexerPathSchema.parse(normalized);
27972
- }
27973
- function indexerExampleRef(input) {
27974
- const identity2 = {
27975
- public_target_ref: indexerCanonicalRefSchema.parse(input.public_target_ref),
27976
- scenario_key: indexerIdSchema.parse(input.scenario_key),
27977
- full_relative_path: normalizeIndexerExampleRelativePath(input.full_relative_path)
27978
- };
27979
- return `example:${indexerProtocolDigest(identity2)}`;
27980
- }
27981
- function indexerExampleObservationRef(input) {
27982
- return `example-observation:${indexerProtocolDigest(input)}`;
27983
- }
27984
- function indexerExampleInventoryDigest(value) {
27985
- return indexerProtocolDigest(value);
27986
- }
27987
- function normalizeObservation(input) {
27988
- const fullRelativePath = normalizeIndexerExampleRelativePath(input.full_relative_path);
27989
- const publicTargetRef = indexerCanonicalRefSchema.parse(input.public_target_ref);
27990
- const scenarioKey = indexerIdSchema.parse(input.scenario_key);
27991
- const sourceRef = indexerCanonicalRefSchema.parse(input.source_ref);
27992
- const moduleRef = input.module_ref === null ? null : indexerCanonicalRefSchema.parse(input.module_ref);
27993
- const contentDigest2 = indexerDigestSchema.parse(input.content_digest);
27994
- const exampleRef = indexerExampleRef({
27995
- public_target_ref: publicTargetRef,
27996
- scenario_key: scenarioKey,
27997
- full_relative_path: fullRelativePath
27998
- });
27999
- return exampleObservationSchema.parse({
28000
- observation_ref: indexerExampleObservationRef({
28001
- example_ref: exampleRef,
28002
- source_ref: sourceRef,
28003
- module_ref: moduleRef,
28004
- content_digest: contentDigest2
28005
- }),
28006
- example_ref: exampleRef,
28007
- public_target_ref: publicTargetRef,
28008
- scenario_key: scenarioKey,
28009
- source_ref: sourceRef,
28010
- module_ref: moduleRef,
28011
- full_relative_path: fullRelativePath,
28012
- content_digest: contentDigest2,
28013
- evidence_refs: canonicalUnique9(input.evidence_refs, "example evidence_refs")
28014
- });
28015
- }
28016
- function buildIndexerExampleInventory(input) {
28017
- const byObservation = new Map;
28018
- for (const observationInput of input.observations) {
28019
- const observation = normalizeObservation(observationInput);
28020
- const current = byObservation.get(observation.observation_ref);
28021
- if (current === undefined) {
28022
- byObservation.set(observation.observation_ref, observation);
28023
- continue;
28024
- }
28025
- const currentCore = { ...current, evidence_refs: undefined };
28026
- const nextCore = { ...observation, evidence_refs: undefined };
28027
- if (canonicalIndexerJson(currentCore) !== canonicalIndexerJson(nextCore)) {
28028
- throw new TypeError("example observation identity collision");
28029
- }
28030
- current.evidence_refs = [...new Set([
28031
- ...current.evidence_refs,
28032
- ...observation.evidence_refs
28033
- ])].sort(compareIndexerCanonicalText);
28034
- }
28035
- const observations = [...byObservation.values()].sort((left, right) => compareIndexerCanonicalText(left.observation_ref, right.observation_ref));
28036
- const payload2 = {
28037
- protocol: "context.indexer.example-inventory/v1",
28038
- source_scope_digest: indexerDigestSchema.parse(input.source_scope_digest),
28039
- observations
28040
- };
28041
- return indexerExampleInventorySchema.parse({
28042
- ...payload2,
28043
- inventory_digest: indexerExampleInventoryDigest(payload2)
28044
- });
28045
- }
28046
- function validateIndexerExampleInventory(input) {
28047
- const value = indexerExampleInventorySchema.parse(input.value);
28048
- const rebuilt = buildIndexerExampleInventory({
28049
- source_scope_digest: value.source_scope_digest,
28050
- observations: value.observations
28051
- });
28052
- if (canonicalIndexerJson(rebuilt) !== canonicalIndexerJson(value)) {
28053
- throw new TypeError("example inventory is non-canonical or has an invalid digest");
28054
- }
28055
- if (input.expected_source_scope_digest !== undefined && value.source_scope_digest !== input.expected_source_scope_digest) {
28056
- throw new TypeError("example inventory belongs to another source scope");
28057
- }
28058
- if (input.known_evidence_refs !== undefined) {
28059
- const known = new Set(canonicalUnique9(input.known_evidence_refs, "known_evidence_refs"));
28060
- if (value.observations.some((item) => item.evidence_refs.some((evidenceRef) => !known.has(evidenceRef)))) {
28061
- throw new TypeError("example inventory references unknown evidence");
28062
- }
28063
- }
28064
- return value;
28065
- }
28066
28650
  // src/indexerExampleIdentityAudit.ts
28067
28651
  var collisionSchema = exports_external.object({
28068
28652
  example_ref: indexerCanonicalRefSchema,
@@ -28777,26 +29361,26 @@ function fallbackStrategy(input) {
28777
29361
  return attempt;
28778
29362
  }
28779
29363
  function validateIndexerCatalogFallbackRecord(value) {
28780
- const record2 = indexerCatalogFallbackRecordSchema.parse(value);
28781
- const payload2 = Object.fromEntries(Object.entries(record2).filter(([key]) => key !== "fallback_digest"));
28782
- if (indexerProtocolDigest(payload2) !== record2.fallback_digest) {
29364
+ const record4 = indexerCatalogFallbackRecordSchema.parse(value);
29365
+ const payload2 = Object.fromEntries(Object.entries(record4).filter(([key]) => key !== "fallback_digest"));
29366
+ if (indexerProtocolDigest(payload2) !== record4.fallback_digest) {
28783
29367
  throw new TypeError("catalog fallback digest is invalid");
28784
29368
  }
28785
- const planPayload2 = Object.fromEntries(Object.entries(record2.partition_plan).filter(([key]) => key !== "canonical_hash"));
28786
- const group = record2.partition_plan.groups[0];
28787
- const catalogMembers = [...record2.catalog_block.member_ids].sort(compareIndexerCanonicalText);
28788
- const ownedMembers2 = record2.partition_plan.member_dispositions.map((disposition) => {
29369
+ const planPayload2 = Object.fromEntries(Object.entries(record4.partition_plan).filter(([key]) => key !== "canonical_hash"));
29370
+ const group = record4.partition_plan.groups[0];
29371
+ const catalogMembers = [...record4.catalog_block.member_ids].sort(compareIndexerCanonicalText);
29372
+ const ownedMembers2 = record4.partition_plan.member_dispositions.map((disposition) => {
28789
29373
  if (disposition.inventory_disposition !== "owned" || disposition.group_key !== "catalog-root") {
28790
29374
  throw new TypeError("catalog fallback members must all belong to catalog-root");
28791
29375
  }
28792
29376
  return disposition.member_id;
28793
29377
  });
28794
- if (record2.partition_plan.status !== "complete" || record2.partition_plan.canonical_hash !== indexerPartitionPlanCanonicalHash(planPayload2) || record2.partition_plan.partition_axis !== INDEXER_CATALOG_FALLBACK_STRATEGY_ID || record2.partition_plan.groups.length !== 1 || group?.group_key !== "catalog-root" || group.subject_intent !== "primary" || group.question_target_bindings.some((binding) => binding.role !== "primary-carrier") || group.logical_unit_ref !== record2.catalog_block.logical_unit_ref || new Set(record2.catalog_block.member_ids).size !== record2.catalog_block.member_ids.length || canonicalIndexerJson(record2.catalog_block.member_ids) !== canonicalIndexerJson(catalogMembers) || canonicalIndexerJson(group.member_ids) !== canonicalIndexerJson(record2.catalog_block.member_ids) || canonicalIndexerJson(ownedMembers2.sort(compareIndexerCanonicalText)) !== canonicalIndexerJson(record2.catalog_block.member_ids) || record2.catalog_block.member_ids_digest !== indexerProtocolDigest({
28795
- member_ids: record2.catalog_block.member_ids
28796
- }) || record2.continuation_policy.split_of !== record2.catalog_block.logical_unit_ref || record2.continuation_policy.navigation_identity !== record2.catalog_block.logical_unit_ref || record2.continuation_policy.review_identity !== record2.catalog_block.logical_unit_ref) {
29378
+ if (record4.partition_plan.status !== "complete" || record4.partition_plan.canonical_hash !== indexerPartitionPlanCanonicalHash(planPayload2) || record4.partition_plan.partition_axis !== INDEXER_CATALOG_FALLBACK_STRATEGY_ID || record4.partition_plan.groups.length !== 1 || group?.group_key !== "catalog-root" || group.subject_intent !== "primary" || group.question_target_bindings.some((binding) => binding.role !== "primary-carrier") || group.logical_unit_ref !== record4.catalog_block.logical_unit_ref || new Set(record4.catalog_block.member_ids).size !== record4.catalog_block.member_ids.length || canonicalIndexerJson(record4.catalog_block.member_ids) !== canonicalIndexerJson(catalogMembers) || canonicalIndexerJson(group.member_ids) !== canonicalIndexerJson(record4.catalog_block.member_ids) || canonicalIndexerJson(ownedMembers2.sort(compareIndexerCanonicalText)) !== canonicalIndexerJson(record4.catalog_block.member_ids) || record4.catalog_block.member_ids_digest !== indexerProtocolDigest({
29379
+ member_ids: record4.catalog_block.member_ids
29380
+ }) || record4.continuation_policy.split_of !== record4.catalog_block.logical_unit_ref || record4.continuation_policy.navigation_identity !== record4.catalog_block.logical_unit_ref || record4.continuation_policy.review_identity !== record4.catalog_block.logical_unit_ref) {
28797
29381
  throw new TypeError("catalog fallback single-parent projection is inconsistent");
28798
29382
  }
28799
- return record2;
29383
+ return record4;
28800
29384
  }
28801
29385
  function buildIndexerCatalogFallback(input) {
28802
29386
  const convergence = validateIndexerPartitionConvergenceRecord(input.convergence);
@@ -29149,7 +29733,7 @@ var fanOutAuditPayloadSchema = exports_external.object({
29149
29733
  var indexerProjectedArtifactFanOutAuditSchema = fanOutAuditPayloadSchema.extend({
29150
29734
  audit_digest: indexerDigestSchema
29151
29735
  }).strict();
29152
- function auditPayload2(audit) {
29736
+ function auditPayload(audit) {
29153
29737
  const { audit_digest: _digest, ...payload3 } = audit;
29154
29738
  return payload3;
29155
29739
  }
@@ -29351,7 +29935,7 @@ function auditIndexerProjectedArtifactFanOut(input) {
29351
29935
  }
29352
29936
  function validateIndexerProjectedArtifactFanOutAudit(value) {
29353
29937
  const audit = indexerProjectedArtifactFanOutAuditSchema.parse(value);
29354
- if (indexerProtocolDigest(auditPayload2(audit)) !== audit.audit_digest) {
29938
+ if (indexerProtocolDigest(auditPayload(audit)) !== audit.audit_digest) {
29355
29939
  throw new TypeError("projected Artifact fan-out audit digest is invalid");
29356
29940
  }
29357
29941
  const expectedState = stateForCount(audit.summary.unassigned_projected_artifact_count);
@@ -29708,7 +30292,8 @@ var layoutProposalPayloadSchema = exports_external.object({
29708
30292
  node_ref: indexerCanonicalRefSchema,
29709
30293
  subject_key: indexerSubjectKeySchema
29710
30294
  }).strict(),
29711
- artifacts: exports_external.array(layoutArtifactSchema)
30295
+ artifacts: exports_external.array(layoutArtifactSchema),
30296
+ delivery_artifact_ids: exports_external.array(exports_external.string().min(1)).min(1).optional()
29712
30297
  }).strict();
29713
30298
  var indexerLayoutProposalSchema = layoutProposalPayloadSchema.extend({
29714
30299
  proposal_digest: indexerDigestSchema
@@ -29746,7 +30331,7 @@ function indexerLayoutSectionRef(currentArtifactRef, sectionIdentityRef) {
29746
30331
  section_identity_ref: sectionIdentityRef
29747
30332
  })}`;
29748
30333
  }
29749
- function viewRef(currentArtifactRef, collection) {
30334
+ function indexerLayoutViewRef(currentArtifactRef, collection) {
29750
30335
  return `view:artifact:${indexerProtocolDigest({
29751
30336
  protocol: "context.indexer.internal-view-identity/v1",
29752
30337
  artifact_ref: currentArtifactRef,
@@ -29770,11 +30355,12 @@ function outputPath(input) {
29770
30355
  const suffix = input.primary ? "" : input.duplicate_kind ? `-${readerPathSlug(input.artifact.artifact_kind)}-${readerPathSlug(input.artifact.artifact_id)}` : `-${readerPathSlug(input.artifact.artifact_kind)}`;
29771
30356
  return `knowledge/${input.collection}/${namespace}/${subject}${suffix}.md`;
29772
30357
  }
29773
- function structuredSections(artifact, facts) {
30358
+ function structuredSections(artifact, facts, render_cache) {
29774
30359
  return artifact.sections.map((section) => {
29775
30360
  const contentBlocks = materializeIndexerStructuredContent({
29776
30361
  blocks: section.blocks,
29777
- facts
30362
+ facts,
30363
+ render_cache
29778
30364
  });
29779
30365
  const evidenceRefs = [...new Set(contentBlocks.flatMap((block) => block.evidence_refs))].sort(compareIndexerCanonicalText);
29780
30366
  return {
@@ -29885,7 +30471,7 @@ function resolveIndexerLayout(input) {
29885
30471
  if (bundleEntry === undefined || bundleEntry.artifact_kind !== artifact.artifact_kind) {
29886
30472
  throw new TypeError(`Artifact ${artifact.artifact_id} is absent from its closed Bundle`);
29887
30473
  }
29888
- const sections = artifact.representation === "sections" ? structuredSections(artifact, result.facts) : (() => {
30474
+ const sections = artifact.representation === "sections" ? structuredSections(artifact, result.facts, input.render_cache) : (() => {
29889
30475
  const rendered = renderedById.get(artifact.artifact_id);
29890
30476
  if (rendered === undefined) {
29891
30477
  throw new TypeError(`template Artifact ${artifact.artifact_id} must be rendered before layout`);
@@ -29921,7 +30507,7 @@ function resolveIndexerLayout(input) {
29921
30507
  node_ref: nodeRef,
29922
30508
  artifact_id: artifact.artifact_id,
29923
30509
  artifact_kind: artifact.artifact_kind,
29924
- internal_view_ref: viewRef(currentArtifactRef, collection),
30510
+ internal_view_ref: indexerLayoutViewRef(currentArtifactRef, collection),
29925
30511
  collection,
29926
30512
  output_path: outputPath({
29927
30513
  collection,
@@ -29964,6 +30550,13 @@ function resolveIndexerLayout(input) {
29964
30550
  if (new Set(sectionIdentities).size !== sectionIdentities.length) {
29965
30551
  throw new TypeError("layout resolver produced colliding logical Section identities");
29966
30552
  }
30553
+ if (input.delivery_artifact_ids !== undefined) {
30554
+ const selected = new Set(input.delivery_artifact_ids);
30555
+ const available = new Set(artifacts.map((artifact) => artifact.artifact_id));
30556
+ if (selected.size !== input.delivery_artifact_ids.length || selected.size === 0 || [...selected].some((id) => !available.has(id))) {
30557
+ throw new TypeError("delivery layout requires unique, available Artifact identities");
30558
+ }
30559
+ }
29967
30560
  const payload3 = layoutProposalPayloadSchema.parse({
29968
30561
  protocol: "context.indexer.layout-proposal/v1",
29969
30562
  indexer_id: result.indexer_id,
@@ -29979,7 +30572,10 @@ function resolveIndexerLayout(input) {
29979
30572
  node_ref: nodeRef,
29980
30573
  subject_key: result.logical_unit.subject_key
29981
30574
  },
29982
- artifacts
30575
+ artifacts: input.delivery_artifact_ids === undefined ? artifacts : artifacts.filter((artifact) => input.delivery_artifact_ids.includes(artifact.artifact_id)),
30576
+ ...input.delivery_artifact_ids === undefined ? {} : {
30577
+ delivery_artifact_ids: [...input.delivery_artifact_ids].sort(compareIndexerCanonicalText)
30578
+ }
29983
30579
  });
29984
30580
  return indexerLayoutProposalSchema.parse({
29985
30581
  ...payload3,
@@ -29990,12 +30586,14 @@ function validateIndexerLayoutProposal(input) {
29990
30586
  const proposal = indexerLayoutProposalSchema.parse(input.proposal);
29991
30587
  const expected = resolveIndexerLayout({
29992
30588
  artifact_result: input.artifact_result,
30589
+ render_cache: input.render_cache,
29993
30590
  post_author_envelope: input.post_author_envelope,
29994
30591
  profile: proposal.profile,
29995
30592
  profile_contract: input.profile_contract,
29996
30593
  operator_contract: input.operator_contract,
29997
30594
  subject_key_schema_set: input.subject_key_schema_set,
29998
30595
  shared_artifact_fingerprint: proposal.shared_artifact_fingerprint,
30596
+ delivery_artifact_ids: proposal.delivery_artifact_ids,
29999
30597
  ...input.rendered_artifacts === undefined ? {} : { rendered_artifacts: input.rendered_artifacts }
30000
30598
  });
30001
30599
  if (canonicalIndexerJson(expected) !== canonicalIndexerJson(proposal)) {
@@ -30032,7 +30630,7 @@ function validateProposalDigest(value) {
30032
30630
  for (const artifact of proposal.artifacts) {
30033
30631
  if (artifact.purpose === "semantic-split") {
30034
30632
  const parent = artifact.split_of_artifact_ref === null ? undefined : artifacts.get(artifact.split_of_artifact_ref);
30035
- if (artifact.split_of_artifact_ref === null || artifact.split_boundary === null || artifact.split_of_artifact_ref === artifact.artifact_ref || parent === undefined || parent.purpose === "semantic-split" || parent.artifact_kind !== artifact.artifact_kind || compareIndexerCanonicalText(artifact.split_boundary.start_key, artifact.split_boundary.end_key) > 0) {
30633
+ if (artifact.split_of_artifact_ref === null || artifact.split_boundary === null || artifact.split_of_artifact_ref === artifact.artifact_ref || parent === undefined && proposal.delivery_artifact_ids === undefined || parent !== undefined && (parent.purpose === "semantic-split" || parent.artifact_kind !== artifact.artifact_kind) || compareIndexerCanonicalText(artifact.split_boundary.start_key, artifact.split_boundary.end_key) > 0) {
30036
30634
  throw new TypeError("semantic-split layout Artifact has invalid parent lineage");
30037
30635
  }
30038
30636
  } else if (artifact.split_of_artifact_ref !== null || artifact.split_boundary !== null) {
@@ -30804,21 +31402,7 @@ function normalizedReaderBody(markdown) {
30804
31402
  lines.splice(0, end + 2);
30805
31403
  }
30806
31404
  return lines.join(`
30807
- `).replace(/<!--[\s\S]*?-->/gu, "").trim();
30808
- }
30809
- function isReaderContentLine(line) {
30810
- const value = line.trim();
30811
- if (value.length === 0)
30812
- return false;
30813
- if (/^#{1,6}(?:\s+.*)?$/u.test(value))
30814
- return false;
30815
- if (/^(?:`{3,}|~{3,})(?:[^`]*)?$/u.test(value))
30816
- return false;
30817
- if (/^(?:[-=_*]\s*){3,}$/u.test(value))
30818
- return false;
30819
- if (/^(?:[-+*]|>)\s*$/u.test(value))
30820
- return false;
30821
- return true;
31405
+ `).trim();
30822
31406
  }
30823
31407
  function fileMetrics(markdown) {
30824
31408
  const readerBody = normalizedReaderBody(markdown);
@@ -30831,7 +31415,7 @@ function fileMetrics(markdown) {
30831
31415
  }),
30832
31416
  byteCount: Buffer2.byteLength(markdown, "utf8"),
30833
31417
  readerBodyLineCount: lines.length,
30834
- empty: !lines.some(isReaderContentLine)
31418
+ empty: readerBody.length === 0
30835
31419
  };
30836
31420
  }
30837
31421
  function physicalRef(outputPath2, markdownDigest) {
@@ -30972,7 +31556,7 @@ function logicalUnitRegistrations(input) {
30972
31556
  throw new TypeError(`layout Node ${proposal.node.node_ref} lacks an Artifact Bundle`);
30973
31557
  }
30974
31558
  const entries = bundleEntryById(bundle);
30975
- if (entries.size !== proposal.artifacts.length || entries.size !== bundle.artifacts.length) {
31559
+ if (proposal.delivery_artifact_ids === undefined && entries.size !== proposal.artifacts.length || entries.size !== bundle.artifacts.length) {
30976
31560
  throw new TypeError(`Artifact Bundle ${bundle.bundle_digest} does not close its layout Artifact set`);
30977
31561
  }
30978
31562
  return proposal.artifacts.map((artifact) => {
@@ -31333,7 +31917,8 @@ function structuredArtifactSections(input) {
31333
31917
  return input.artifact.sections.map((section) => {
31334
31918
  const blocks = materializeIndexerStructuredContent({
31335
31919
  blocks: section.blocks,
31336
- facts: input.result.facts
31920
+ facts: input.result.facts,
31921
+ render_cache: input.render_cache
31337
31922
  });
31338
31923
  const evidenceRefs = [...new Set(blocks.flatMap((block) => block.evidence_refs))].sort(compareIndexerCanonicalText);
31339
31924
  assertSectionIntegrity({
@@ -31401,7 +31986,7 @@ function candidateFiles(input) {
31401
31986
  artifact.artifact_id,
31402
31987
  artifact
31403
31988
  ]));
31404
- return input.accepted.effectiveArtifacts.map((artifact) => {
31989
+ return input.accepted.effectiveArtifacts.filter((artifact) => input.proposal.delivery_artifact_ids === undefined || input.proposal.delivery_artifact_ids.includes(artifact.artifact_id)).map((artifact) => {
31405
31990
  const layout = layoutById.get(artifact.artifact_id);
31406
31991
  if (layout === undefined) {
31407
31992
  throw new TypeError(`Candidate compile Result Artifact ${artifact.artifact_id} has no layout`);
@@ -31409,7 +31994,8 @@ function candidateFiles(input) {
31409
31994
  const sections = artifact.representation === "sections" ? structuredArtifactSections({
31410
31995
  result: input.accepted.artifactResult,
31411
31996
  proposal: input.proposal,
31412
- artifact
31997
+ artifact,
31998
+ render_cache: input.render_cache
31413
31999
  }) : (() => {
31414
32000
  const rendered = renderedById.get(artifact.artifact_id);
31415
32001
  if (rendered === undefined) {
@@ -31421,6 +32007,19 @@ function candidateFiles(input) {
31421
32007
  rendered
31422
32008
  });
31423
32009
  })();
32010
+ for (const section of sections) {
32011
+ if (input.markdown_projection === undefined)
32012
+ continue;
32013
+ section.markdown = input.markdown_projection({
32014
+ markdown: section.markdown,
32015
+ output_path: layout.output_path,
32016
+ artifact_ref: layout.artifact_ref
32017
+ });
32018
+ section.markdown_digest = indexerProtocolDigest({
32019
+ protocol: "context.indexer.physical-section-markdown/v1",
32020
+ markdown: section.markdown
32021
+ });
32022
+ }
31424
32023
  const markdown = sections.map((section) => section.markdown).join(`
31425
32024
 
31426
32025
  `);
@@ -31536,14 +32135,15 @@ function buildIndexerCandidateCompile(input) {
31536
32135
  profile_contract: input.profile_contract,
31537
32136
  operator_contract: input.operator_contract,
31538
32137
  subject_key_schema_set: input.subject_key_schema_set,
31539
- rendered_artifacts: item.renderedArtifacts
32138
+ rendered_artifacts: item.renderedArtifacts,
32139
+ render_cache: input.render_cache
31540
32140
  });
31541
32141
  const binding = resultBinding({ accepted: item, proposal });
31542
32142
  return {
31543
32143
  accepted: item,
31544
32144
  proposal,
31545
32145
  binding,
31546
- files: candidateFiles({ accepted: item, proposal, binding })
32146
+ files: candidateFiles({ accepted: item, proposal, binding, markdown_projection: input.markdown_projection, render_cache: input.render_cache })
31547
32147
  };
31548
32148
  }).sort((left, right) => compareIndexerCanonicalText(left.binding.artifact_result_digest, right.binding.artifact_result_digest));
31549
32149
  const files = entries.flatMap((entry) => entry.files).sort((left, right) => compareIndexerCanonicalText(left.output_path, right.output_path));
@@ -31657,7 +32257,12 @@ function validateIndexerProviderContractReferences(input) {
31657
32257
  ...variant.artifact_kinds.required,
31658
32258
  ...variant.artifact_kinds.discretionary
31659
32259
  ]));
31660
- const sourceRoles = new Set(targetProfiles.flatMap((profile) => profile.layout_mappings.flatMap((mapping) => mapping.source_roles)));
32260
+ const declaredProfileIds = selectedBaseProfileIds({
32261
+ manifest: input.manifest,
32262
+ selectedProfiles: input.manifest.provides.profiles,
32263
+ registeredProfiles: new Set(profilesById.keys())
32264
+ });
32265
+ const sourceRoles = new Set([...declaredProfileIds].flatMap((id) => profilesById.get(id).layout_mappings.flatMap((mapping) => mapping.source_roles)));
31661
32266
  for (const sourceRole of input.manifest.provides.source_roles ?? []) {
31662
32267
  if (!sourceRoles.has(sourceRole)) {
31663
32268
  throw new TypeError(`Provider references unregistered layout source role ${sourceRole}`);
@@ -31977,8 +32582,8 @@ function recoverIndexerMainRunLedger(input) {
31977
32582
  ]));
31978
32583
  const previousByItem = new Map(previous?.entries.map((entry) => [entry.item_ref, entry]));
31979
32584
  const acceptedByIdentity = new Map((input.accepted_records ?? []).map((candidate) => {
31980
- const record2 = validateIndexerMainAcceptedRecord(candidate);
31981
- return [indexerMainRunIdentityDigest(record2), record2];
32585
+ const record4 = validateIndexerMainAcceptedRecord(candidate);
32586
+ return [indexerMainRunIdentityDigest(record4), record4];
31982
32587
  }));
31983
32588
  if (acceptedByIdentity.size !== (input.accepted_records ?? []).length) {
31984
32589
  throw new TypeError("accepted main run cache contains duplicate identities");
@@ -32059,16 +32664,16 @@ function startIndexerMainRuns(input) {
32059
32664
  }
32060
32665
  function acceptIndexerMainRun(input) {
32061
32666
  const ledger = validateIndexerMainRunLedger(input.ledger);
32062
- const record2 = validateIndexerMainAcceptedRecord(input.accepted_record);
32667
+ const record4 = validateIndexerMainAcceptedRecord(input.accepted_record);
32063
32668
  return replaceEntry({
32064
32669
  ledger,
32065
- workset_digest: record2.workset_digest,
32670
+ workset_digest: record4.workset_digest,
32066
32671
  replace: (entry) => {
32067
32672
  if (entry.state !== "running") {
32068
32673
  throw new TypeError("main result requires a running ledger entry");
32069
32674
  }
32070
- assertAcceptedRecord({ record: record2, base: entry });
32071
- return { ...entry, state: "accepted", accepted_record: record2 };
32675
+ assertAcceptedRecord({ record: record4, base: entry });
32676
+ return { ...entry, state: "accepted", accepted_record: record4 };
32072
32677
  }
32073
32678
  });
32074
32679
  }
@@ -32167,6 +32772,21 @@ function observeIndexerMainRunLedger(value) {
32167
32772
  records
32168
32773
  });
32169
32774
  }
32775
+ function invalidateIndexerMainRunWorksets(value, worksets) {
32776
+ const ledger = validateIndexerMainRunLedger(value);
32777
+ if ([...worksets].some((digest) => !ledger.entries.some((entry) => entry.workset_digest === digest))) {
32778
+ throw new TypeError("adjusted workset is not in the current ledger");
32779
+ }
32780
+ return buildLedger({
32781
+ workset_set: ledger.workset_set,
32782
+ entries: ledger.entries.map((entry, index) => !worksets.has(entry.workset_digest) ? entry : {
32783
+ ...entryBase({ item: ledger.workset_set.items[index], execution_request_digest: entry.execution_request_digest }),
32784
+ state: "stale",
32785
+ previous_workset_digest: entry.workset_digest,
32786
+ previous_execution_request_digest: entry.execution_request_digest
32787
+ })
32788
+ });
32789
+ }
32170
32790
  // src/indexerPostAuthorRunLedger.ts
32171
32791
  var composerRefSchema = exports_external.string().regex(/^provider:[^#]+#layer:[^#]+#composer:[A-Za-z0-9._-]+$/u);
32172
32792
  var ledgerEntryBase = {
@@ -32567,9 +33187,10 @@ function sameEnvelope(candidate, expected) {
32567
33187
  return parsed.success && indexerProtocolDigest(parsed.data) === indexerProtocolDigest(expected);
32568
33188
  }
32569
33189
  function observeIndexerPostAuthorState(input) {
32570
- const ledger = recoverIndexerPostAuthorRunLedger({
33190
+ const previous = validateIndexerPostAuthorRunLedger(input.ledger);
33191
+ const ledger = previous.workset_set_digest === input.plan.workset_set.workset_set_digest ? previous : recoverIndexerPostAuthorRunLedger({
32571
33192
  plan: input.plan,
32572
- previous_ledger: input.ledger,
33193
+ previous_ledger: previous,
32573
33194
  validator_contract_digest: input.validator_contract_digest
32574
33195
  });
32575
33196
  const effectiveSet = validateIndexerEffectiveComposerSet(input.effective_composer_set);
@@ -32626,7 +33247,7 @@ function observeIndexerPostAuthorState(input) {
32626
33247
  };
32627
33248
  }
32628
33249
  const counts = {
32629
- pending: ledger.entries.filter((entry) => entry.state === "pending").length,
33250
+ pending: ledger.entries.filter((entry) => entry.state === "pending" || entry.state === "running").length,
32630
33251
  accepted: ledger.entries.filter((entry) => entry.state === "accepted").length,
32631
33252
  failed: ledger.entries.filter((entry) => entry.state === "failed").length,
32632
33253
  stale: ledger.entries.filter((entry) => entry.state === "stale").length
@@ -32856,13 +33477,126 @@ var customPhase = (id, run, io = {}) => ({
32856
33477
  writes: io.writes ?? [],
32857
33478
  run
32858
33479
  });
33480
+ // src/managedSources.ts
33481
+ import { readdir, lstat, realpath as realpath3, readFile as readFile3 } from "node:fs/promises";
33482
+ import { join, relative as relative3, isAbsolute as isAbsolute4 } from "node:path";
33483
+
33484
+ // src/sessionMetadata.ts
33485
+ var sessionChangeSchema = exports_external.object({
33486
+ repository: exports_external.string().trim().min(1).optional(),
33487
+ commit: exports_external.string().regex(/^(?:[a-fA-F0-9]{40}|[a-fA-F0-9]{64})$/u).optional(),
33488
+ mr: exports_external.string().url().refine((value) => /^https?:\/\//u.test(value), "MR/PR must be an HTTP(S) URL").optional()
33489
+ }).strict().refine((value) => value.commit !== undefined || value.mr !== undefined, "A session change needs a commit or MR/PR reference");
33490
+ var sessionChangesSchema = exports_external.array(sessionChangeSchema);
33491
+ function sourceHeader(markdown) {
33492
+ const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u.exec(markdown);
33493
+ if (!match)
33494
+ return;
33495
+ const document = $parseDocument(match[1], { uniqueKeys: true });
33496
+ if (document.errors.length)
33497
+ throw new TypeError(`Invalid sessions frontmatter: ${document.errors[0].message}`);
33498
+ const value = document.toJS();
33499
+ if (value !== null && (typeof value !== "object" || Array.isArray(value))) {
33500
+ throw new TypeError("Sessions frontmatter must be a mapping");
33501
+ }
33502
+ return { value: value ?? {}, body: markdown.slice(match[0].length) };
33503
+ }
33504
+ function readSessionChanges(markdown) {
33505
+ const value = sourceHeader(markdown)?.value.changes;
33506
+ return value === undefined ? undefined : sessionChangesSchema.parse(value);
33507
+ }
33508
+ function writeSessionChanges(markdown, changes) {
33509
+ if (changes === undefined) {
33510
+ readSessionChanges(markdown);
33511
+ return markdown;
33512
+ }
33513
+ const parsed = sessionChangesSchema.parse(changes);
33514
+ const header = sourceHeader(markdown);
33515
+ const metadata = { ...header?.value ?? {} };
33516
+ if (parsed.length)
33517
+ metadata.changes = parsed;
33518
+ else
33519
+ delete metadata.changes;
33520
+ const body = header?.body ?? markdown;
33521
+ if (!Object.keys(metadata).length)
33522
+ return body;
33523
+ return `---
33524
+ ${$stringify(metadata)}---
33525
+ ${body}`;
33526
+ }
33527
+
33528
+ // src/managedSources.ts
33529
+ function assertManagedDocumentName(name) {
33530
+ if (!/^\d{8}\/[^/\\\x00-\x1f\s:#?]+\.md$/u.test(name) || name.includes("/..")) {
33531
+ throw new TypeError("Managed document name must be YYYYMMDD/semantic-name.md inside sources/note or sources/sessions");
33532
+ }
33533
+ const date = name.slice(0, 8);
33534
+ const parsed = new Date(`${date.slice(0, 4)}-${date.slice(4, 6)}-${date.slice(6, 8)}T00:00:00Z`);
33535
+ if (!Number.isFinite(parsed.getTime()) || parsed.toISOString().slice(0, 10).replaceAll("-", "") !== date) {
33536
+ throw new TypeError("Managed document date must be a valid YYYYMMDD date");
33537
+ }
33538
+ }
33539
+ async function assertManagedDocumentPath(rootDir, type, name) {
33540
+ assertManagedDocumentName(name);
33541
+ const root = await realpath3(rootDir);
33542
+ const parts = ["sources", type, ...name.split("/")];
33543
+ let path = root;
33544
+ for (const part of parts) {
33545
+ path = join(path, part);
33546
+ try {
33547
+ if ((await lstat(path)).isSymbolicLink())
33548
+ throw new TypeError("Managed document paths must not traverse symlinks");
33549
+ } catch (error) {
33550
+ if (!(error && typeof error === "object" && ("code" in error) && error.code === "ENOENT"))
33551
+ throw error;
33552
+ }
33553
+ }
33554
+ const rel = relative3(root, path);
33555
+ if (isAbsolute4(rel) || rel.startsWith("../"))
33556
+ throw new TypeError("Managed document path leaves its workspace");
33557
+ return path;
33558
+ }
33559
+ async function discoverManagedDocuments(rootDir, type) {
33560
+ const base = join(rootDir, "sources", type);
33561
+ await assertManagedDocumentPath(rootDir, type, "20000101/discovery.md");
33562
+ let dates;
33563
+ try {
33564
+ dates = await readdir(base, { withFileTypes: true });
33565
+ } catch (error) {
33566
+ if (error && typeof error === "object" && "code" in error && error.code === "ENOENT")
33567
+ return [];
33568
+ throw error;
33569
+ }
33570
+ const entries = [];
33571
+ for (const date of dates.sort((a, b) => a.name.localeCompare(b.name))) {
33572
+ if (!date.isDirectory() || !/^\d{8}$/u.test(date.name))
33573
+ continue;
33574
+ for (const file of (await readdir(join(base, date.name), { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
33575
+ if (!file.isFile() || !file.name.endsWith(".md"))
33576
+ continue;
33577
+ const name = `${date.name}/${file.name}`;
33578
+ await assertManagedDocumentPath(rootDir, type, name);
33579
+ const changes = type === "sessions" ? readSessionChanges(await readFile3(join(base, name), "utf8")) : undefined;
33580
+ entries.push({
33581
+ ...changes === undefined ? {} : { changes },
33582
+ id: name,
33583
+ name,
33584
+ namespace: date.name,
33585
+ module: file.name,
33586
+ materializedAt: `sources/${type}/${name}`
33587
+ });
33588
+ }
33589
+ }
33590
+ return entries;
33591
+ }
33592
+
32859
33593
  // src/sources.ts
32860
- import { readFile as readFile3 } from "node:fs/promises";
33594
+ import { readFile as readFile4 } from "node:fs/promises";
32861
33595
  import { resolve as resolve3 } from "node:path";
32862
33596
  var DEFAULT_REPO_SOURCES_REGISTRY_PATH = "sources/repo/index.yaml";
32863
33597
  var DEFAULT_FILE_SOURCES_REGISTRY_PATH = "sources/file/index.yaml";
32864
33598
  var DEFAULT_LARK_SOURCES_REGISTRY_PATH = "sources/lark/index.yaml";
32865
- var SOURCE_TYPES = ["repo", "file", "lark"];
33599
+ var SOURCE_TYPES = ["repo", "file", "lark", "note", "sessions"];
32866
33600
  var SOURCE_NAME_PATTERN = /^[a-z0-9][a-z0-9._-]*$/u;
32867
33601
  var REPO_DATE_NAMESPACE_PATTERN = /^\d{8}$/u;
32868
33602
  function assertSourceType(value, field) {
@@ -33165,7 +33899,7 @@ var parseLarkSourcesRegistry = (input, registryPath) => {
33165
33899
  };
33166
33900
  var readYamlIfPresent = async (absolutePath, emptyValue) => {
33167
33901
  try {
33168
- const content = await readFile3(absolutePath, "utf8");
33902
+ const content = await readFile4(absolutePath, "utf8");
33169
33903
  return content.trim().length === 0 ? emptyValue : $parse(content);
33170
33904
  } catch (error) {
33171
33905
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
@@ -33217,7 +33951,9 @@ var loadSourcesRegistry = async (options = {}) => {
33217
33951
  },
33218
33952
  repos: repoRegistry.repos,
33219
33953
  files,
33220
- larks
33954
+ larks,
33955
+ notes: await discoverManagedDocuments(rootDir, "note"),
33956
+ sessions: await discoverManagedDocuments(rootDir, "sessions")
33221
33957
  };
33222
33958
  assertGlobalSourceUniqueness(registry);
33223
33959
  return registry;
@@ -33261,6 +33997,221 @@ var allSources = (type) => {
33261
33997
  type
33262
33998
  }];
33263
33999
  };
34000
+ // src/processedScopes.ts
34001
+ var reference = exports_external.string().min(1).refine((value) => value.trim() === value, {
34002
+ message: "scope references must not have surrounding whitespace"
34003
+ });
34004
+ var processedScopeSchema = exports_external.object({
34005
+ requirement_ref: reference,
34006
+ source_ref: reference,
34007
+ processed_version: reference,
34008
+ module_refs: exports_external.array(reference).min(1).optional()
34009
+ }).strict().superRefine((scope, context) => {
34010
+ if (scope.module_refs && new Set(scope.module_refs).size !== scope.module_refs.length) {
34011
+ context.addIssue({
34012
+ code: exports_external.ZodIssueCode.custom,
34013
+ path: ["module_refs"],
34014
+ message: "module_refs must not contain duplicates"
34015
+ });
34016
+ }
34017
+ });
34018
+ function processedScopeKey(scope) {
34019
+ return JSON.stringify([
34020
+ scope.requirement_ref,
34021
+ scope.source_ref,
34022
+ [...scope.module_refs ?? []].sort()
34023
+ ]);
34024
+ }
34025
+ var processedScopesSchema = exports_external.array(processedScopeSchema).superRefine((scopes, context) => {
34026
+ const seen = new Set;
34027
+ scopes.forEach((scope, index) => {
34028
+ const key = processedScopeKey(scope);
34029
+ if (seen.has(key)) {
34030
+ context.addIssue({
34031
+ code: exports_external.ZodIssueCode.custom,
34032
+ path: [index],
34033
+ message: "processed_scopes must contain only one latest version per exact scope"
34034
+ });
34035
+ }
34036
+ seen.add(key);
34037
+ });
34038
+ });
34039
+ function readProcessedScopes(structure) {
34040
+ return processedScopesSchema.parse(structure?.processed_scopes === undefined ? [] : structure.processed_scopes);
34041
+ }
34042
+ function containsScope(outer, inner) {
34043
+ return outer.requirement_ref === inner.requirement_ref && outer.source_ref === inner.source_ref && (outer.module_refs === undefined || inner.module_refs !== undefined && inner.module_refs.every((module) => outer.module_refs.includes(module)));
34044
+ }
34045
+ function mergeProcessedScopes(previous, completed) {
34046
+ const updates = processedScopesSchema.parse(completed);
34047
+ const retained = processedScopesSchema.parse(previous).filter((scope) => !updates.some((update) => containsScope(update, scope)));
34048
+ return [...retained, ...updates].sort((a, b) => processedScopeKey(a).localeCompare(processedScopeKey(b)));
34049
+ }
34050
+ function processedVersionForScope(scopes, scope) {
34051
+ const parsed = processedScopesSchema.parse(scopes);
34052
+ const exact = parsed.find((entry) => processedScopeKey(entry) === processedScopeKey(scope));
34053
+ if (exact)
34054
+ return exact.processed_version;
34055
+ const versions = new Set(parsed.filter((entry) => containsScope(entry, scope)).map((entry) => entry.processed_version));
34056
+ return versions.size === 1 ? [...versions][0] : undefined;
34057
+ }
34058
+ // src/indexerApprovedKnowledge.ts
34059
+ var indexerApprovedKnowledgeSchema = exports_external.object({
34060
+ protocol: exports_external.literal("context.indexer.approved-knowledge/v1"),
34061
+ artifact_ref: indexerCanonicalRefSchema,
34062
+ subject_key: indexerSubjectKeySchema,
34063
+ primary_indexer_id: exports_external.string().min(1).optional(),
34064
+ path: portableIndexerPathSchema,
34065
+ approved_content_digest: indexerDigestSchema,
34066
+ source_versions: exports_external.array(exports_external.object({
34067
+ source_ref: indexerCanonicalRefSchema,
34068
+ module_ref: indexerCanonicalRefSchema.nullable(),
34069
+ version: exports_external.string().min(1)
34070
+ }).strict()).min(1),
34071
+ sections: exports_external.array(exports_external.object({
34072
+ section_ref: indexerCanonicalRefSchema,
34073
+ section_key: exports_external.string().min(1).optional(),
34074
+ markdown: exports_external.string().min(1),
34075
+ fact_refs: exports_external.array(indexerCanonicalRefSchema),
34076
+ evidence_refs: exports_external.array(indexerCanonicalRefSchema).min(1)
34077
+ }).strict()).min(1),
34078
+ facts: exports_external.array(indexerArtifactFactSchema),
34079
+ evidence_bindings: exports_external.array(indexerEvidenceBindingSchema),
34080
+ dependencies: exports_external.array(indexerKnowledgeDependencySchema),
34081
+ dependency_versions: exports_external.array(indexerKnowledgeDependencyVersionSchema).optional(),
34082
+ snapshot_digest: indexerDigestSchema
34083
+ }).strict();
34084
+ var sourceKey = (source2) => JSON.stringify([source2.source_ref, source2.module_ref]);
34085
+ function validateIndexerApprovedKnowledge(value) {
34086
+ const snapshot2 = indexerApprovedKnowledgeSchema.parse(value);
34087
+ const { snapshot_digest, ...payload3 } = snapshot2;
34088
+ if (indexerProtocolDigest(payload3) !== snapshot_digest)
34089
+ throw new TypeError("Approved knowledge snapshot integrity changed");
34090
+ const facts = new Map(snapshot2.facts.map((fact) => [fact.fact_ref, fact]));
34091
+ const evidence = new Map(snapshot2.evidence_bindings.map((binding) => [binding.evidence_ref, binding]));
34092
+ const sources = new Set(snapshot2.source_versions.map(sourceKey));
34093
+ const versions = snapshot2.dependency_versions ?? [];
34094
+ if (new Set(versions.map((version) => version.artifact_ref)).size !== versions.length || versions.some((version) => !snapshot2.dependencies.some((dependency) => dependency.artifact_ref === version.artifact_ref))) {
34095
+ throw new TypeError("Approved knowledge has duplicate or undeclared dependency versions");
34096
+ }
34097
+ if (facts.size !== snapshot2.facts.length || evidence.size !== snapshot2.evidence_bindings.length || sources.size !== snapshot2.source_versions.length || new Set(snapshot2.sections.map((section) => section.section_ref)).size !== snapshot2.sections.length) {
34098
+ throw new TypeError("Approved knowledge snapshot repeats an identity");
34099
+ }
34100
+ for (const binding of evidence.values()) {
34101
+ if (!sources.has(sourceKey(binding)))
34102
+ throw new TypeError("Approved knowledge evidence has no source version");
34103
+ const { binding_digest, ...content } = binding;
34104
+ if (indexerProtocolDigest(content) !== binding_digest)
34105
+ throw new TypeError("Approved knowledge evidence binding changed");
34106
+ }
34107
+ for (const fact of facts.values()) {
34108
+ if (fact.evidence_refs.some((ref) => !evidence.has(ref)))
34109
+ throw new TypeError("Approved knowledge fact has unknown source evidence");
34110
+ }
34111
+ for (const section of snapshot2.sections) {
34112
+ if (section.evidence_refs.some((ref) => !evidence.has(ref)))
34113
+ throw new TypeError("Approved knowledge section has unknown source evidence");
34114
+ for (const ref of section.fact_refs) {
34115
+ const fact = facts.get(ref);
34116
+ if (!fact || fact.evidence_refs.some((evidenceRef) => !section.evidence_refs.includes(evidenceRef))) {
34117
+ throw new TypeError("Approved knowledge section fact is outside its evidence binding");
34118
+ }
34119
+ }
34120
+ }
34121
+ return snapshot2;
34122
+ }
34123
+ function buildIndexerApprovedKnowledge(payload3) {
34124
+ return validateIndexerApprovedKnowledge({ ...payload3, snapshot_digest: indexerProtocolDigest(payload3) });
34125
+ }
34126
+ function projectIndexerApprovedKnowledge(input) {
34127
+ const available = new Map(input.snapshots.map((snapshot2) => [snapshot2.artifact_ref, snapshot2]));
34128
+ if (available.size !== input.snapshots.length)
34129
+ throw new TypeError("Approved knowledge projection repeats an article");
34130
+ const scope = new Map(input.authorized_sources.map((source2) => [sourceKey(source2), source2.version]));
34131
+ if (scope.size !== input.authorized_sources.length || new Set(input.dependencies.map((dependency) => dependency.artifact_ref)).size !== input.dependencies.length) {
34132
+ throw new TypeError("Approved knowledge projection repeats a source or dependency identity");
34133
+ }
34134
+ const pending = [];
34135
+ const versions = [];
34136
+ const facts = [];
34137
+ const readingSections = [];
34138
+ const evidence = new Map;
34139
+ for (const value of input.dependencies) {
34140
+ const dependency = indexerKnowledgeDependencySchema.parse(value);
34141
+ const defer = (reason) => pending.push({ artifact_ref: dependency.artifact_ref, required: dependency.required, reason });
34142
+ const raw = available.get(dependency.artifact_ref);
34143
+ if (!raw) {
34144
+ defer("not-approved");
34145
+ continue;
34146
+ }
34147
+ const snapshot2 = validateIndexerApprovedKnowledge(raw);
34148
+ if (input.approved_versions.get(snapshot2.artifact_ref) !== snapshot2.approved_content_digest) {
34149
+ defer("approval-changed");
34150
+ continue;
34151
+ }
34152
+ const sections = dependency.section_refs.length ? snapshot2.sections.filter((section) => dependency.section_refs.includes(section.section_ref)) : snapshot2.sections;
34153
+ if (sections.length !== (dependency.section_refs.length || snapshot2.sections.length)) {
34154
+ defer("section-unavailable");
34155
+ continue;
34156
+ }
34157
+ const factRefs = new Set(sections.flatMap((section) => section.fact_refs));
34158
+ const evidenceRefs = new Set(sections.flatMap((section) => section.evidence_refs));
34159
+ const bindings = snapshot2.evidence_bindings.filter((binding) => evidenceRefs.has(binding.evidence_ref));
34160
+ const selectedSourceKeys = new Set(bindings.map(sourceKey));
34161
+ const sourceVersions = snapshot2.source_versions.filter((source2) => selectedSourceKeys.has(sourceKey(source2)));
34162
+ if (sourceVersions.some((source2) => !scope.has(sourceKey(source2)))) {
34163
+ throw new TypeError(`Approved knowledge is outside the current read scope: ${snapshot2.artifact_ref}`);
34164
+ }
34165
+ if (sourceVersions.some((source2) => scope.get(sourceKey(source2)) !== source2.version)) {
34166
+ defer("source-version-changed");
34167
+ continue;
34168
+ }
34169
+ if (bindings.some((binding) => !input.evidence_kinds.has(binding.kind)))
34170
+ throw new TypeError("Provider cannot consume the approved knowledge evidence kind");
34171
+ for (const binding of bindings) {
34172
+ const previous = evidence.get(binding.evidence_ref);
34173
+ if (previous && previous.binding_digest !== binding.binding_digest)
34174
+ throw new TypeError("Approved knowledge sources have conflicting evidence identities");
34175
+ evidence.set(binding.evidence_ref, binding);
34176
+ }
34177
+ const projectionDigest = indexerProtocolDigest({ snapshot: snapshot2.snapshot_digest, sections: sections.map((section) => section.section_ref).sort() });
34178
+ versions.push({ artifact_ref: snapshot2.artifact_ref, approved_content_digest: snapshot2.approved_content_digest, projection_digest: projectionDigest });
34179
+ for (const section of sections)
34180
+ readingSections.push({
34181
+ artifact_ref: snapshot2.artifact_ref,
34182
+ section_ref: section.section_ref,
34183
+ approved_content_digest: snapshot2.approved_content_digest,
34184
+ evidence_role: "approved-interpretation",
34185
+ markdown: section.markdown,
34186
+ evidence_refs: section.evidence_refs
34187
+ });
34188
+ for (const fact of snapshot2.facts.filter((fact2) => factRefs.has(fact2.fact_ref))) {
34189
+ const value2 = {
34190
+ approved_artifact_ref: snapshot2.artifact_ref,
34191
+ approved_content_digest: snapshot2.approved_content_digest,
34192
+ original_fact_ref: fact.fact_ref,
34193
+ original_subject: fact.subject_key,
34194
+ source_versions: sourceVersions,
34195
+ value: fact.value
34196
+ };
34197
+ facts.push({
34198
+ fact_ref: `fact:approved-${indexerProtocolDigest(value2).slice(7)}`,
34199
+ fact_kind: "approved-knowledge-fact",
34200
+ subject_key: input.subject_key,
34201
+ value: value2,
34202
+ evidence_refs: fact.evidence_refs
34203
+ });
34204
+ }
34205
+ }
34206
+ return {
34207
+ status: pending.some((item) => item.required) ? "waiting" : "ready",
34208
+ pending,
34209
+ versions,
34210
+ facts,
34211
+ reading_sections: readingSections,
34212
+ evidence_bindings: [...evidence.values()]
34213
+ };
34214
+ }
33264
34215
 
33265
34216
  // src/index.ts
33266
34217
  function assertUniquePhaseIds(phases) {
@@ -33480,9 +34431,11 @@ var llmsPackage = (definition) => ({
33480
34431
  ...createPackageDefinitionBase("llms", definition)
33481
34432
  });
33482
34433
  export {
34434
+ writeSessionChanges,
33483
34435
  validatedIndexerCustomizationDraftSchema,
33484
34436
  validateValidatedIndexerCustomizationDraft,
33485
34437
  validateResolvedProviderBundle,
34438
+ validateReadingStructure,
33486
34439
  validateIndexerToolSnapshot,
33487
34440
  validateIndexerTargetResolutionView,
33488
34441
  validateIndexerSubjectKeyForSchema,
@@ -33533,6 +34486,7 @@ export {
33533
34486
  validateIndexerPostAuthorRunLedger,
33534
34487
  validateIndexerPostAuthorFragmentResult,
33535
34488
  validateIndexerPostAuthorFragmentRequest,
34489
+ validateIndexerPlannedArticles,
33536
34490
  validateIndexerPhysicalArtifactAudit,
33537
34491
  validateIndexerPartitionStrategyResolution,
33538
34492
  validateIndexerPartitionStrategyAttempt,
@@ -33565,11 +34519,11 @@ export {
33565
34519
  validateIndexerLayoutProposal,
33566
34520
  validateIndexerLayoutChangeReport,
33567
34521
  validateIndexerLayerCompositionInput,
34522
+ validateIndexerKnowledgeDependencyGraph,
33568
34523
  validateIndexerInventoryDispositionSet,
33569
34524
  validateIndexerInspectorResult,
33570
34525
  validateIndexerInspectorRequest,
33571
34526
  validateIndexerIncrementalImpactReport,
33572
- validateIndexerGeneratedAuthoringAudit,
33573
34527
  validateIndexerFixedDependencySet,
33574
34528
  validateIndexerExampleLinkageAudit,
33575
34529
  validateIndexerExampleInventory,
@@ -33608,7 +34562,9 @@ export {
33608
34562
  validateIndexerArtifactDependencySet,
33609
34563
  validateIndexerArtifactBundlePolicy,
33610
34564
  validateIndexerArtifactBundle,
34565
+ validateIndexerArticlePlan,
33611
34566
  validateIndexerApprovedLayoutProjection,
34567
+ validateIndexerApprovedKnowledge,
33612
34568
  validateIndexerAgentStepInput,
33613
34569
  validateIndexerActivationResult,
33614
34570
  validateIndexerActivationRequest,
@@ -33619,10 +34575,14 @@ export {
33619
34575
  validateArtifactResults,
33620
34576
  validateAndRecordIndexerMainRun,
33621
34577
  validateAndMaterializeIndexerLayerFragment,
34578
+ updateReadingStructure,
33622
34579
  startIndexerPostAuthorRun,
33623
34580
  startIndexerMainRuns,
33624
34581
  startIndexerMainRun,
34582
+ sourceUpdateSemanticInputSchema,
33625
34583
  source,
34584
+ sessionChangesSchema,
34585
+ sessionChangeSchema,
33626
34586
  sameIndexerParserExecutionPlan,
33627
34587
  sameIndexerApprovedLayout,
33628
34588
  retryIndexerMainPartitionRun,
@@ -33649,10 +34609,23 @@ export {
33649
34609
  recoverIndexerPostAuthorRunLedger,
33650
34610
  recoverIndexerMainRunLedger,
33651
34611
  reconcileIndexerResults,
34612
+ readingTargetKey,
34613
+ readingStructureUpdateSchema,
34614
+ readingStructureSchema,
34615
+ readingStructureEntrySchema,
34616
+ readSessionChanges,
34617
+ readProcessedScopes,
33652
34618
  questionPairs,
34619
+ projectReadingStructure,
33653
34620
  projectIndexerSourceIdentityInventory,
34621
+ projectIndexerPublicContractTable,
33654
34622
  projectIndexerPartitionSubjects,
33655
34623
  projectIndexerFactValue,
34624
+ projectIndexerApprovedKnowledge,
34625
+ processedVersionForScope,
34626
+ processedScopesSchema,
34627
+ processedScopeSchema,
34628
+ processedScopeKey,
33656
34629
  planIndexerPostAuthorComposition,
33657
34630
  parseIndexerRegistry,
33658
34631
  parseIndexerProviderManifest,
@@ -33663,6 +34636,7 @@ export {
33663
34636
  observeIndexerMainRunLedger,
33664
34637
  normalizeIndexerRequirementSet,
33665
34638
  normalizeIndexerExampleRelativePath,
34639
+ mergeProcessedScopes,
33666
34640
  mergeIndexerEvidenceAdapterResults,
33667
34641
  mergeIndexerEvidenceAdapterExecutions,
33668
34642
  mdxJsonDocs,
@@ -33681,6 +34655,7 @@ export {
33681
34655
  isPortableIndexerPath,
33682
34656
  isIndexerProviderProtocol,
33683
34657
  isIndexerLayerFragmentKind,
34658
+ invalidateIndexerMainRunWorksets,
33684
34659
  initializeIndexerPostAuthorRunLedger,
33685
34660
  initializeIndexerMainRunLedger,
33686
34661
  inflationSensitiveHardMaximum,
@@ -33881,6 +34856,7 @@ export {
33881
34856
  indexerMainRunIdentityDigest,
33882
34857
  indexerMainAcceptedRecordSchema,
33883
34858
  indexerLogicalUnitDependencyNodeSchema,
34859
+ indexerLayoutViewRef,
33884
34860
  indexerLayoutTransitionSchema,
33885
34861
  indexerLayoutSectionRef,
33886
34862
  indexerLayoutSectionIdentityRef,
@@ -33896,6 +34872,9 @@ export {
33896
34872
  indexerLayerFragmentDigest,
33897
34873
  indexerLayerCompositionInputSchema,
33898
34874
  indexerLayerCompositionInputDigest,
34875
+ indexerKnowledgeDependencyVersionSchema,
34876
+ indexerKnowledgeDependencySchema,
34877
+ indexerKnowledgeDependencyFingerprint,
33899
34878
  indexerKnowledgeCollectionSchema2 as indexerKnowledgeCollectionSchema,
33900
34879
  indexerInventoryMembersDigest,
33901
34880
  indexerInventoryMemberSchema,
@@ -33910,7 +34889,6 @@ export {
33910
34889
  indexerIncrementalImpactReportDigest,
33911
34890
  indexerImplementationFingerprint,
33912
34891
  indexerHostExecutionCapabilitiesSchema,
33913
- indexerGeneratedAuthoringAuditSchema,
33914
34892
  indexerFixedDependencySetSchema,
33915
34893
  indexerExecutionSchema,
33916
34894
  indexerExampleRepresentationSchema,
@@ -33948,6 +34926,7 @@ export {
33948
34926
  indexerCustomizationLadderStepSchema,
33949
34927
  indexerCustomizationDraftSchema,
33950
34928
  indexerCurrentActionInputSchema,
34929
+ indexerCurrentActionInputDefinitions,
33951
34930
  indexerCoverageCompletionReportSchema,
33952
34931
  indexerControlledProgramResultSchema,
33953
34932
  indexerControlledProgramRequestSchema,
@@ -33998,13 +34977,18 @@ export {
33998
34977
  indexerArtifactDependencySetDigest,
33999
34978
  indexerArtifactContentBlockSchema,
34000
34979
  indexerArtifactBundleSchema,
34980
+ indexerArticleSectionKey,
34981
+ indexerArticlePlanSchema,
34982
+ indexerArticleKeySchema,
34001
34983
  indexerApprovedLayoutProjectionSchema,
34984
+ indexerApprovedKnowledgeSchema,
34002
34985
  indexerAgentStepInputSchema,
34003
34986
  indexerAgentStepInputDigest,
34004
34987
  indexerActivationResultSchema,
34005
34988
  indexerActivationRequestSchema,
34006
34989
  indexRequirementSetSchema,
34007
34990
  indexRequirementSchema,
34991
+ impactedIndexerKnowledgeArticles,
34008
34992
  failIndexerPostAuthorRun,
34009
34993
  failIndexerMainRun,
34010
34994
  expectedProviderResolutionFromAction,
@@ -34012,6 +34996,7 @@ export {
34012
34996
  evaluateIndexerCandidateMaterialization,
34013
34997
  enforceIndexerSubjectKeySchemaTransition,
34014
34998
  dispositionMap,
34999
+ discoverManagedDocuments,
34015
35000
  deriveIndexerProgramExecutionPolicy,
34016
35001
  defineProject,
34017
35002
  customPhase,
@@ -34019,7 +35004,6 @@ export {
34019
35004
  coverageDomainCompletionSchema,
34020
35005
  coverageCompletionReportPayloadSchema,
34021
35006
  convergeIndexerPartitionPlan,
34022
- containsIndexerControlledAuthoringPlaceholder,
34023
35007
  confirmIndexerRequirementWorkset,
34024
35008
  confirmIndexerRequirementChange,
34025
35009
  confirmIndexerRequirementAmendment,
@@ -34109,7 +35093,6 @@ export {
34109
35093
  buildIndexerInspectorWorksetViewSource,
34110
35094
  buildIndexerInspectorRequest,
34111
35095
  buildIndexerIncrementalImpactReport,
34112
- buildIndexerGeneratedAuthoringAudit,
34113
35096
  buildIndexerFixedDependencySet,
34114
35097
  buildIndexerExampleLinkageAudit,
34115
35098
  buildIndexerExampleInventory,
@@ -34136,6 +35119,7 @@ export {
34136
35119
  buildIndexerArtifactDependencySet,
34137
35120
  buildIndexerArtifactBundle,
34138
35121
  buildIndexerApprovedLayoutProjection,
35122
+ buildIndexerApprovedKnowledge,
34139
35123
  buildIndexerAgentStepInput,
34140
35124
  buildIndexerActivationRequest,
34141
35125
  authorizeIndexerSubjectReidentification,
@@ -34147,16 +35131,19 @@ export {
34147
35131
  assertTopLevelNamespace,
34148
35132
  assertOkfRoot,
34149
35133
  assertNoReferenceOnlyReaderTargets,
35134
+ assertManagedDocumentPath,
35135
+ assertManagedDocumentName,
34150
35136
  assertMainlineCollection,
34151
35137
  assertKnowledgeCollection,
34152
35138
  assertIndexerPhysicalArtifactAuditPassed,
34153
35139
  assertIndexerParserDependenciesLocked,
34154
- assertIndexerGeneratedAuthoringAuditClear,
35140
+ assertIndexerInspectorProfileVariants,
34155
35141
  assertIndexerExampleIdentityAuditPassed,
34156
35142
  assertIndexerExampleCandidateDecisionClosure,
34157
35143
  assertIndexerCanonicalOrder,
34158
35144
  assertDocumentMainlineCollection,
34159
35145
  assertDocumentEvidenceSectionMetadata,
35146
+ approvedRevisionSemanticInputSchema,
34160
35147
  analyzeIndexerSubjectKeySchemaTransition,
34161
35148
  allSources,
34162
35149
  acceptIndexerPostAuthorRun,
@@ -34165,6 +35152,7 @@ export {
34165
35152
  OKF_ROOTS,
34166
35153
  MAINLINE_COLLECTIONS,
34167
35154
  KNOWLEDGE_COLLECTIONS,
35155
+ IndexerKnowledgeDependencyCycleError,
34168
35156
  INDEXER_SUBJECT_NORMALIZATIONS,
34169
35157
  INDEXER_SUBJECT_DERIVATION_OPERATORS,
34170
35158
  INDEXER_STRUCTURED_DECLARATION_KINDS,