@c4a/context 0.7.5 → 0.7.9

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 (98) 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 +20 -9
  7. package/docs/guides/agent-guide.md +48 -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 +334 -15
  11. package/docs/guides/indexer-skill-creation.md +99 -0
  12. package/docs/guides/knowledge-updates.md +422 -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 +231 -60
  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 +135 -22
  23. package/docs/reference/package-templates.md +10 -9
  24. package/docs/reference/project-api.md +100 -13
  25. package/docs/reference/template-variables.md +7 -7
  26. package/index.d.ts +15 -0
  27. package/index.js +1708 -626
  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 +12 -12
  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/indexerProtocolHash.d.ts +2 -0
  72. package/indexerProvider.d.ts +102 -58
  73. package/indexerProviderComposition.d.ts +4 -4
  74. package/indexerProviderRouting.d.ts +52 -0
  75. package/indexerProviderSelectionProposal.d.ts +48 -0
  76. package/indexerPublicContractFacts.d.ts +7 -0
  77. package/indexerPublicContractTable.d.ts +11 -0
  78. package/indexerReaderTargetInventory.d.ts +6 -6
  79. package/indexerReferenceOnlyAudit.d.ts +2 -2
  80. package/indexerRegistry.d.ts +658 -0
  81. package/indexerRequirementConfirmation.d.ts +48 -16
  82. package/indexerRequirementLifecycle.d.ts +154 -42
  83. package/indexerResultReconciliation.d.ts +12 -11
  84. package/indexerSemanticInput.d.ts +27168 -3813
  85. package/{indexerGeneratedAuthoringAudit.d.ts → indexerStructuredClaims.d.ts} +0 -84
  86. package/indexerStructuredDeclaration.d.ts +8 -8
  87. package/indexerTemplateRendering.d.ts +7 -7
  88. package/indexerToolSnapshot.d.ts +16 -16
  89. package/knowledgeMap.d.ts +188 -0
  90. package/managedSources.d.ts +15 -0
  91. package/package.json +1 -1
  92. package/packageSite.d.ts +25 -0
  93. package/phases.d.ts +0 -3
  94. package/processedScopes.d.ts +75 -0
  95. package/sessionMetadata.d.ts +49 -0
  96. package/sources.d.ts +9 -3
  97. package/templates/package-templates/kb/skills/knowledge-query/SKILL.md +15 -10
  98. 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;
@@ -6915,55 +6915,6 @@ var require_public_api = __commonJS((exports) => {
6915
6915
  exports.stringify = stringify;
6916
6916
  });
6917
6917
 
6918
- // src/contracts.ts
6919
- var DEFAULT_PACKAGE_NAVIGATION = {
6920
- foldDirectoryIndexes: true,
6921
- maxInlineEntries: 50
6922
- };
6923
- var DOC_MAINLINE_COLLECTIONS = [
6924
- "business",
6925
- "product",
6926
- "architecture",
6927
- "sop",
6928
- "faq",
6929
- "standards",
6930
- "decision",
6931
- "incident",
6932
- "test"
6933
- ];
6934
- var MAINLINE_COLLECTIONS = ["codeindex", "codegraph", ...DOC_MAINLINE_COLLECTIONS];
6935
- var TOP_LEVEL_NAMESPACES = [...MAINLINE_COLLECTIONS, "feats"];
6936
- var OKF_ROOTS = ["guides", "rules", "wikis", "feats"];
6937
- var KNOWLEDGE_COLLECTIONS = TOP_LEVEL_NAMESPACES;
6938
- function assertKnowledgeCollection(value, field) {
6939
- if (!KNOWLEDGE_COLLECTIONS.includes(value)) {
6940
- throw new TypeError(`${field} must be one of ${KNOWLEDGE_COLLECTIONS.join(", ")}: ${value}`);
6941
- }
6942
- }
6943
- function assertDocumentMainlineCollection(value, field) {
6944
- if (!DOC_MAINLINE_COLLECTIONS.includes(value)) {
6945
- throw new TypeError(`${field} must be one of ${DOC_MAINLINE_COLLECTIONS.join(", ")}: ${value}`);
6946
- }
6947
- }
6948
- function assertMainlineCollection(value, field) {
6949
- if (!MAINLINE_COLLECTIONS.includes(value)) {
6950
- throw new TypeError(`${field} must be one of ${MAINLINE_COLLECTIONS.join(", ")}: ${value}`);
6951
- }
6952
- }
6953
- function assertTopLevelNamespace(value, field) {
6954
- if (!TOP_LEVEL_NAMESPACES.includes(value)) {
6955
- throw new TypeError(`${field} must be one of ${TOP_LEVEL_NAMESPACES.join(", ")}: ${value}`);
6956
- }
6957
- }
6958
- function assertOkfRoot(value, field) {
6959
- if (!OKF_ROOTS.includes(value)) {
6960
- throw new TypeError(`${field} must be one of ${OKF_ROOTS.join(", ")}: ${value}`);
6961
- }
6962
- }
6963
-
6964
- // src/indexerProtocolCommon.ts
6965
- import { createHash } from "node:crypto";
6966
-
6967
6918
  // ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/external.js
6968
6919
  var exports_external = {};
6969
6920
  __export(exports_external, {
@@ -10937,6 +10888,133 @@ var coerce = {
10937
10888
  date: (arg) => ZodDate.create({ ...arg, coerce: true })
10938
10889
  };
10939
10890
  var NEVER = INVALID;
10891
+ // src/packageSite.ts
10892
+ var packageSiteSchema = exports_external.object({
10893
+ title: exports_external.string().trim().min(1).optional(),
10894
+ description: exports_external.string().optional(),
10895
+ lang: exports_external.string().min(1).default("en-US"),
10896
+ base: exports_external.string().regex(/^\/(?:[a-zA-Z0-9_-]+\/)*$/, "Use / or a slash-delimited deployment path, such as /docs/").default("/")
10897
+ }).strict();
10898
+ function normalizePackageSite(value) {
10899
+ return value === undefined ? undefined : packageSiteSchema.parse(value);
10900
+ }
10901
+ // src/contracts.ts
10902
+ var DEFAULT_PACKAGE_NAVIGATION = {
10903
+ foldDirectoryIndexes: true,
10904
+ maxInlineEntries: 50
10905
+ };
10906
+ var DOC_MAINLINE_COLLECTIONS = [
10907
+ "business",
10908
+ "product",
10909
+ "architecture",
10910
+ "sop",
10911
+ "faq",
10912
+ "standards",
10913
+ "decision",
10914
+ "incident",
10915
+ "test"
10916
+ ];
10917
+ var MAINLINE_COLLECTIONS = ["codeindex", "codegraph", ...DOC_MAINLINE_COLLECTIONS];
10918
+ var TOP_LEVEL_NAMESPACES = [...MAINLINE_COLLECTIONS, "feats"];
10919
+ var OKF_ROOTS = ["guides", "rules", "wikis", "feats"];
10920
+ var KNOWLEDGE_COLLECTIONS = TOP_LEVEL_NAMESPACES;
10921
+ function assertKnowledgeCollection(value, field) {
10922
+ if (!KNOWLEDGE_COLLECTIONS.includes(value)) {
10923
+ throw new TypeError(`${field} must be one of ${KNOWLEDGE_COLLECTIONS.join(", ")}: ${value}`);
10924
+ }
10925
+ }
10926
+ function assertDocumentMainlineCollection(value, field) {
10927
+ if (!DOC_MAINLINE_COLLECTIONS.includes(value)) {
10928
+ throw new TypeError(`${field} must be one of ${DOC_MAINLINE_COLLECTIONS.join(", ")}: ${value}`);
10929
+ }
10930
+ }
10931
+ function assertMainlineCollection(value, field) {
10932
+ if (!MAINLINE_COLLECTIONS.includes(value)) {
10933
+ throw new TypeError(`${field} must be one of ${MAINLINE_COLLECTIONS.join(", ")}: ${value}`);
10934
+ }
10935
+ }
10936
+ function assertTopLevelNamespace(value, field) {
10937
+ if (!TOP_LEVEL_NAMESPACES.includes(value)) {
10938
+ throw new TypeError(`${field} must be one of ${TOP_LEVEL_NAMESPACES.join(", ")}: ${value}`);
10939
+ }
10940
+ }
10941
+ function assertOkfRoot(value, field) {
10942
+ if (!OKF_ROOTS.includes(value)) {
10943
+ throw new TypeError(`${field} must be one of ${OKF_ROOTS.join(", ")}: ${value}`);
10944
+ }
10945
+ }
10946
+
10947
+ // src/indexerProtocolHash.ts
10948
+ import { createHash } from "node:crypto";
10949
+ function hashCanonicalIndexerJson(value, fallback) {
10950
+ const hash = createHash("sha256");
10951
+ let buffer = "";
10952
+ const unsupported = Symbol("non-json value");
10953
+ const active = new Set;
10954
+ const append = (text) => {
10955
+ buffer += text;
10956
+ if (buffer.length >= 16384) {
10957
+ hash.update(buffer);
10958
+ buffer = "";
10959
+ }
10960
+ };
10961
+ const visit = (item) => {
10962
+ if (item === null || typeof item !== "object") {
10963
+ const text = JSON.stringify(item);
10964
+ if (text === undefined)
10965
+ throw unsupported;
10966
+ append(text);
10967
+ return;
10968
+ }
10969
+ if (active.has(item))
10970
+ throw unsupported;
10971
+ active.add(item);
10972
+ if (Array.isArray(item)) {
10973
+ append("[");
10974
+ for (let i = 0;i < item.length; i++) {
10975
+ if (i !== 0)
10976
+ append(",");
10977
+ const child = item[i];
10978
+ if (child === undefined || typeof child === "function" || typeof child === "symbol")
10979
+ append("null");
10980
+ else
10981
+ visit(child);
10982
+ }
10983
+ append("]");
10984
+ } else {
10985
+ const entries = Object.entries(item).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
10986
+ if (entries.some(([key, child]) => key === "toJSON" && typeof child === "function"))
10987
+ throw unsupported;
10988
+ const ordered = Object.fromEntries(entries);
10989
+ append("{");
10990
+ let first = true;
10991
+ for (const key of Object.keys(ordered)) {
10992
+ const child = ordered[key];
10993
+ if (child === undefined || typeof child === "function" || typeof child === "symbol")
10994
+ continue;
10995
+ if (!first)
10996
+ append(",");
10997
+ first = false;
10998
+ append(JSON.stringify(key));
10999
+ append(":");
11000
+ visit(child);
11001
+ }
11002
+ append("}");
11003
+ }
11004
+ active.delete(item);
11005
+ };
11006
+ try {
11007
+ visit(value);
11008
+ if (buffer)
11009
+ hash.update(buffer);
11010
+ return `sha256:${hash.digest("hex")}`;
11011
+ } catch (error) {
11012
+ if (error !== unsupported)
11013
+ throw error;
11014
+ return `sha256:${createHash("sha256").update(fallback(value)).digest("hex")}`;
11015
+ }
11016
+ }
11017
+
10940
11018
  // src/indexerProtocolCommon.ts
10941
11019
  var INDEXER_PROVIDER_MANIFEST_NAME = "context-indexer.yaml";
10942
11020
  var DEFAULT_INDEXER_REGISTRY_PATH = "src/indexers.yaml";
@@ -10994,7 +11072,7 @@ var indexerIdSchema = exports_external.string().regex(/^[a-z0-9][a-z0-9._/-]*$/u
10994
11072
  var indexerSnakeCaseIdSchema = exports_external.string().regex(/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/u);
10995
11073
  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
11074
  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);
11075
+ var indexerCanonicalRefSchema = exports_external.string().regex(/^[a-z][a-z0-9.-]*:[\p{L}\p{N}][\p{L}\p{N}._~:/#@+-]*$/u);
10998
11076
  var indexerProviderLayerRefSchema = indexerCanonicalRefSchema.refine((value) => !value.includes("#composer:"), "Provider layer ref cannot contain a composer suffix");
10999
11077
  var indexerComposerRefSchema = indexerCanonicalRefSchema.refine((value) => /#composer:[a-z0-9][a-z0-9._/-]*$/u.test(value), "composer ref must end with #composer:<id>");
11000
11078
  function isPortableIndexerPath(value) {
@@ -11031,7 +11109,7 @@ function canonicalIndexerJson(value) {
11031
11109
  return JSON.stringify(canonicalize(value));
11032
11110
  }
11033
11111
  function indexerProtocolDigest(value) {
11034
- return `sha256:${createHash("sha256").update(canonicalIndexerJson(value)).digest("hex")}`;
11112
+ return hashCanonicalIndexerJson(value, canonicalIndexerJson);
11035
11113
  }
11036
11114
  function formatIndexerSchemaIssues(issues) {
11037
11115
  return issues.map((issue) => {
@@ -11052,6 +11130,278 @@ function addDuplicateIssues(values, context, field) {
11052
11130
  seen.add(value);
11053
11131
  });
11054
11132
  }
11133
+ // src/indexerPublicContractFacts.ts
11134
+ function record(value) {
11135
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
11136
+ }
11137
+ function propsName(value) {
11138
+ if (typeof value.propsType === "string" && /^[A-Za-z_$][\w$]*$/u.test(value.propsType))
11139
+ return value.propsType;
11140
+ return typeof value.typeAnnotation === "string" ? /^(?:React\.)?(?:FC|FunctionComponent)\s*<\s*([A-Za-z_$][\w$]*)\s*>$/u.exec(value.typeAnnotation)?.[1] : undefined;
11141
+ }
11142
+ function publicContractSupport(selected, available) {
11143
+ const refs = new Set(selected.map((fact) => fact.fact_ref));
11144
+ return available.filter((fact) => {
11145
+ if (refs.has(fact.fact_ref))
11146
+ return false;
11147
+ const value = record(fact.value);
11148
+ if (value?.kind !== "component" || value.visibility !== "exported" || !Array.isArray(value.members) || !value.members.length)
11149
+ return false;
11150
+ const name = propsName(value);
11151
+ if (!name)
11152
+ return false;
11153
+ return typeof value.file === "string" && selected.filter((target) => {
11154
+ const type = record(target.value);
11155
+ 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;
11156
+ }).length === 1;
11157
+ }).sort((left, right) => compareIndexerCanonicalText(left.fact_ref, right.fact_ref));
11158
+ }
11159
+ function reconcilePublicContractFacts(facts) {
11160
+ const owners = new Map;
11161
+ const types2 = new Map;
11162
+ for (const component of facts) {
11163
+ const value = record(component.value);
11164
+ if (value?.kind !== "component" || value.visibility !== "exported" || !Array.isArray(value.members) || !value.members.length)
11165
+ continue;
11166
+ const name = propsName(value);
11167
+ if (!name || typeof value.file !== "string")
11168
+ continue;
11169
+ const matches = facts.filter((fact) => {
11170
+ const type2 = record(fact.value);
11171
+ 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;
11172
+ });
11173
+ if (matches.length !== 1)
11174
+ continue;
11175
+ const type = matches[0];
11176
+ types2.set(component.fact_ref, type);
11177
+ owners.set(type.fact_ref, [...owners.get(type.fact_ref) ?? [], component]);
11178
+ }
11179
+ return facts.flatMap((fact) => {
11180
+ if (owners.has(fact.fact_ref))
11181
+ return [];
11182
+ const value = record(fact.value);
11183
+ const typeFact = types2.get(fact.fact_ref);
11184
+ if (!value || !typeFact)
11185
+ return [fact];
11186
+ const type = record(typeFact.value);
11187
+ const implementations = new Map(value.members.flatMap((item) => {
11188
+ const member = record(item);
11189
+ return typeof member?.name === "string" ? [[member.name, member]] : [];
11190
+ }));
11191
+ const members = type.members.map((item) => {
11192
+ const declaration = record(item);
11193
+ if (!declaration || typeof declaration.name !== "string")
11194
+ return item;
11195
+ const member = implementations.get(declaration.name);
11196
+ implementations.delete(declaration.name);
11197
+ if (!member)
11198
+ return item;
11199
+ const conflict = declaration.defaultValue !== undefined && member.defaultValue !== undefined && declaration.defaultValue !== member.defaultValue;
11200
+ return {
11201
+ ...member,
11202
+ ...declaration,
11203
+ ...member.defaultValue === undefined ? {} : { defaultValue: member.defaultValue },
11204
+ doc: [
11205
+ declaration.doc || member.doc,
11206
+ conflict ? `Default for ${String(value.name)}; declaration documents ${String(declaration.defaultValue)}.` : ""
11207
+ ].filter(Boolean).join(" ")
11208
+ };
11209
+ });
11210
+ members.push(...implementations.values());
11211
+ const name = owners.get(typeFact.fact_ref).length === 1 ? String(type.name) : `${String(type.name)} (${String(value.name)})`;
11212
+ return [
11213
+ { ...fact, value: { ...value, members: [], params: [] } },
11214
+ { ...typeFact, fact_ref: fact.fact_ref, value: { ...type, name, members } }
11215
+ ];
11216
+ });
11217
+ }
11218
+
11219
+ // src/indexerContractDeclaration.ts
11220
+ function compactContractDeclaration(raw, rows) {
11221
+ const normalize = (text) => text.replace(/\s+/gu, " ").trim();
11222
+ const notes = rows.map((row) => row[5] ?? "");
11223
+ let declaration = "";
11224
+ let plain = "";
11225
+ const flush = () => {
11226
+ declaration += plain.replace(/[ \t]*(?:\r?\n[ \t]*)+/gu, (space) => (space.includes(`\r
11227
+ `) ? `\r
11228
+ ` : `
11229
+ `) + (/[ \t]*$/u.exec(space)?.[0] ?? ""));
11230
+ plain = "";
11231
+ };
11232
+ for (let i = 0;i < raw.length; ) {
11233
+ const quote = raw[i];
11234
+ if (quote === '"' || quote === "'" || quote === "`") {
11235
+ const start = i++;
11236
+ while (i < raw.length) {
11237
+ if (raw[i] === "\\") {
11238
+ i += 2;
11239
+ continue;
11240
+ }
11241
+ if (raw[i++] === quote)
11242
+ break;
11243
+ }
11244
+ flush();
11245
+ declaration += raw.slice(start, i);
11246
+ } else if (raw.startsWith("//", i)) {
11247
+ const end = raw.indexOf(`
11248
+ `, i);
11249
+ const next = end < 0 ? raw.length : end;
11250
+ flush();
11251
+ declaration += raw.slice(i, next);
11252
+ i = next;
11253
+ } else if (raw.startsWith("/*", i)) {
11254
+ const end = raw.indexOf("*/", i + 2);
11255
+ if (end < 0) {
11256
+ flush();
11257
+ declaration += raw.slice(i);
11258
+ break;
11259
+ }
11260
+ const comment = raw.slice(i, end + 2);
11261
+ const body = comment.slice(2, -2).replace(/^\s*\* ?/gmu, "").trim();
11262
+ const prose = normalize(body.split(/@\w/u)[0] ?? "");
11263
+ const tags = [...body.matchAll(/@(\w+)/gu)].map((match) => match[1]);
11264
+ 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)));
11265
+ if (duplicate)
11266
+ plain += " ";
11267
+ else {
11268
+ flush();
11269
+ declaration += comment;
11270
+ }
11271
+ i = end + 2;
11272
+ } else {
11273
+ plain += raw[i++];
11274
+ }
11275
+ }
11276
+ flush();
11277
+ declaration = declaration.trim();
11278
+ if (/^\{[^{}]*\}$/u.test(declaration) && !declaration.includes("/*") && !declaration.includes("//")) {
11279
+ const fields = declaration.slice(1, -1).split(";").map((item) => item.trim()).filter(Boolean);
11280
+ if (fields.length > 0 && fields.every((field) => {
11281
+ const match = /^(readonly\s+)?([\w$]+)(\?)?\s*:\s*(.+)$/su.exec(field);
11282
+ 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")));
11283
+ }))
11284
+ return;
11285
+ }
11286
+ return declaration;
11287
+ }
11288
+
11289
+ // src/indexerPublicContractTable.ts
11290
+ function record2(value) {
11291
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
11292
+ }
11293
+ var text = (value) => typeof value === "string" ? value : "";
11294
+ function projectIndexerPublicContractTable(fact) {
11295
+ const value = record2(fact.value);
11296
+ if (value === undefined)
11297
+ return;
11298
+ const rows = [];
11299
+ const add = (field, owner2) => {
11300
+ rows.push([
11301
+ owner2,
11302
+ text(field.name),
11303
+ text(field.typeAnnotation ?? field.type ?? field.signature),
11304
+ field.optional === true ? "optional" : field.optional === false ? "required" : "not declared",
11305
+ field.defaultValue === undefined ? "unknown" : typeof field.defaultValue === "string" ? field.defaultValue : JSON.stringify(field.defaultValue),
11306
+ [
11307
+ field.readonly === true ? "readonly" : "",
11308
+ field.rest === true ? "rest" : "",
11309
+ text(field.location),
11310
+ field.number === undefined ? "" : `field ${String(field.number)}`,
11311
+ field.repeated === true ? "repeated" : "",
11312
+ text(field.oneof),
11313
+ text(field.doc ?? field.description),
11314
+ field.constraints === undefined ? "" : JSON.stringify(field.constraints)
11315
+ ].filter(Boolean).join("; ")
11316
+ ]);
11317
+ if (Array.isArray(field.fields))
11318
+ for (const item of field.fields) {
11319
+ const child = record2(item);
11320
+ if (child !== undefined)
11321
+ add(child, `${owner2}.${text(field.name)}`);
11322
+ }
11323
+ };
11324
+ const owner = text(value.name ?? value.qualifiedName);
11325
+ const hasMembers = Array.isArray(value.members) && value.members.length > 0;
11326
+ if (!hasMembers && value.kind !== "component" && (typeof value.typeAnnotation === "string" || typeof value.initializer === "string")) {
11327
+ rows.push([owner, "declaration", [text(value.typeAnnotation), typeof value.initializer === "string" ? `= ${value.initializer}` : ""].filter(Boolean).join(" "), "", "", ""]);
11328
+ }
11329
+ const registration = record2(value.registration);
11330
+ if (registration !== undefined)
11331
+ rows.push([
11332
+ text(registration.kind),
11333
+ text(registration.key),
11334
+ text(registration.handler),
11335
+ "",
11336
+ "",
11337
+ [
11338
+ text(registration.method),
11339
+ Array.isArray(registration.middleware) ? registration.middleware.map(String).join(" → ") : ""
11340
+ ].filter(Boolean).join("; ")
11341
+ ]);
11342
+ if (Array.isArray(value.members))
11343
+ for (const member of value.members) {
11344
+ const field = record2(member);
11345
+ if (field === undefined)
11346
+ continue;
11347
+ const exportedTypeMember = value.visibility === "exported" && (value.kind === "type" || value.kind === "interface") && (field.kind === "prop" || field.kind === "method");
11348
+ const hidden = field.visibility === "private" || field.visibility === "protected" || /(?:^|\s)@(internal|private|protected)\b/u.test(text(field.doc));
11349
+ if (!hidden && (field.visibility !== "internal" || exportedTypeMember))
11350
+ add(field, owner);
11351
+ }
11352
+ if (Array.isArray(value.params) && value.kind !== "component")
11353
+ for (const parameter of value.params) {
11354
+ const field = record2(parameter);
11355
+ if (field !== undefined)
11356
+ add(field, owner);
11357
+ }
11358
+ if (Array.isArray(value.fields))
11359
+ for (const member of value.fields) {
11360
+ const field = record2(member);
11361
+ if (field !== undefined)
11362
+ add(field, owner);
11363
+ }
11364
+ if (Array.isArray(value.throws))
11365
+ for (const item of value.throws) {
11366
+ const field = record2(item);
11367
+ if (field !== undefined)
11368
+ add(field, `${owner} throws`);
11369
+ }
11370
+ for (const [key, label] of [["input_type", "request"], ["output_type", "response"], ["return_type", "return"]]) {
11371
+ if (typeof value[key] === "string")
11372
+ rows.push([owner, label, value[key], "", "", [
11373
+ key === "input_type" && value.client_streaming === true ? "client streaming" : "",
11374
+ key === "output_type" && value.server_streaming === true ? "server streaming" : "",
11375
+ value.oneway === true ? "oneway" : ""
11376
+ ].filter(Boolean).join("; ")]);
11377
+ }
11378
+ if (Array.isArray(value.overloads))
11379
+ for (const signature of value.overloads) {
11380
+ if (typeof signature === "string")
11381
+ rows.push([owner, "signature", signature, "", "", ""]);
11382
+ }
11383
+ else if (typeof value.signature === "string")
11384
+ rows.push([owner, "signature", value.signature, "", "", ""]);
11385
+ if (Array.isArray(value.publicEntrypoints))
11386
+ for (const entry of value.publicEntrypoints) {
11387
+ if (typeof entry === "string")
11388
+ rows.push([owner, "export entry", entry, "", "", ""]);
11389
+ }
11390
+ if (typeof value.handler === "string" && (typeof value.path === "string" || typeof value.method === "string")) {
11391
+ rows.push([text(value.method), text(value.path), value.handler, "", "", Array.isArray(value.middleware) ? value.middleware.map(String).join(" → ") : ""]);
11392
+ }
11393
+ if (rows.length === 0)
11394
+ return;
11395
+ const declaration = (hasMembers || value.kind === "component") && typeof value.typeAnnotation === "string" ? compactContractDeclaration(value.typeAnnotation, rows) : undefined;
11396
+ 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 ?? "");
11397
+ return {
11398
+ columns: ["Contract", "Name", "Declaration", "Required", "Default", "Notes"],
11399
+ rows,
11400
+ declaration_status: redundantComponent ? "component-wrapper" : declaration !== undefined ? "retained" : typeof value.typeAnnotation === "string" && hasMembers ? "table-complete" : "not-provided",
11401
+ ...declaration !== undefined && !redundantComponent ? { declaration, declarationName: owner } : {}
11402
+ };
11403
+ }
11404
+
11055
11405
  // src/indexerSubjectIdentity.ts
11056
11406
  var normalizedSubjectFieldSchema = exports_external.string().min(1).refine((value) => value.normalize("NFC") === value, "SubjectKey fields must use Unicode NFC normalization");
11057
11407
  var indexerSubjectKeySchema = exports_external.object({
@@ -11084,6 +11434,8 @@ var indexerArtifactFactSchema = exports_external.object({
11084
11434
  var indexerDeterministicBlockRendererSchema = exports_external.enum([
11085
11435
  "bullet-list",
11086
11436
  "key-value-table",
11437
+ "multi-column-table",
11438
+ "public-contract-table",
11087
11439
  "json-code-block"
11088
11440
  ]);
11089
11441
  var deterministicArtifactBlockSchema = exports_external.object({
@@ -11127,6 +11479,47 @@ function renderIndexerDeterministicFacts(input) {
11127
11479
  }
11128
11480
  const facts = [...input.facts].sort((left, right) => compareIndexerCanonicalText(left.fact_ref, right.fact_ref));
11129
11481
  const value = projectIndexerFactValue(facts);
11482
+ if (input.renderer === "public-contract-table") {
11483
+ const support = publicContractSupport(facts, input.supporting_facts ?? []);
11484
+ const supportingRefs = new Set(support.map((fact) => fact.fact_ref));
11485
+ const tables = reconcilePublicContractFacts([...facts, ...support]).flatMap((fact) => {
11486
+ if (supportingRefs.has(fact.fact_ref) && typeof fact.value === "object" && fact.value !== null && !Array.isArray(fact.value) && fact.value.kind === "component")
11487
+ return [];
11488
+ const table = projectIndexerPublicContractTable(fact);
11489
+ return table === undefined ? [] : [table];
11490
+ });
11491
+ if (tables.length === 0)
11492
+ throw new TypeError("public-contract-table requires declared public contracts");
11493
+ const rendered = renderIndexerDeterministicFacts({ renderer: "multi-column-table", facts: [{
11494
+ ...facts[0],
11495
+ value: { columns: tables[0].columns, rows: tables.flatMap((table) => table.rows) }
11496
+ }] });
11497
+ const declarations = [...new Map(tables.filter((table) => table.declaration !== undefined).map((table) => [JSON.stringify([table.declarationName, table.declaration]), table])).values()];
11498
+ return [rendered, ...declarations.map((table) => {
11499
+ const declaration = table.declaration;
11500
+ const name = (table.declarationName || "Contract").replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
11501
+ const fence = "`".repeat(Math.max(3, ...[...declaration.matchAll(/`+/gu)].map((match) => match[0].length + 1)));
11502
+ return `<details>
11503
+ <summary>${name}: type details</summary>
11504
+
11505
+ ${fence}typescript
11506
+ ${declaration}
11507
+ ${fence}
11508
+
11509
+ </details>`;
11510
+ })].join(`
11511
+
11512
+ `);
11513
+ }
11514
+ if (input.renderer === "multi-column-table") {
11515
+ 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);
11516
+ if (table.rows.some((row) => row.length !== table.columns.length)) {
11517
+ throw new TypeError("multi-column-table rows must match the declared columns");
11518
+ }
11519
+ const cell = (text2) => text2.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("|", "&#124;").replace(/\r?\n/gu, "<br>");
11520
+ return [table.columns, table.columns.map(() => "---"), ...table.rows].map((row) => `| ${row.map(cell).join(" | ")} |`).join(`
11521
+ `);
11522
+ }
11130
11523
  if (input.renderer === "bullet-list") {
11131
11524
  if (!Array.isArray(value) || !value.every((item) => typeof item === "string")) {
11132
11525
  throw new TypeError("bullet-list deterministic block requires a string-list Fact projection");
@@ -11185,8 +11578,12 @@ function validateIndexerRenderedContentBlock(value) {
11185
11578
  return block;
11186
11579
  }
11187
11580
  function materializeIndexerStructuredContent(input) {
11581
+ const key = input.render_cache === undefined ? undefined : indexerProtocolDigest({ blocks: input.blocks, facts: input.facts });
11582
+ const cached = key === undefined ? undefined : input.render_cache?.get(key);
11583
+ if (cached !== undefined)
11584
+ return structuredClone(cached);
11188
11585
  const facts = new Map(input.facts.map((fact) => [fact.fact_ref, fact]));
11189
- return input.blocks.map((block) => {
11586
+ const rendered = input.blocks.map((block) => {
11190
11587
  if (block.layer === "semantic-prose") {
11191
11588
  return buildIndexerRenderedContentBlock({
11192
11589
  layer: block.layer,
@@ -11201,16 +11598,25 @@ function materializeIndexerStructuredContent(input) {
11201
11598
  }
11202
11599
  return fact;
11203
11600
  });
11601
+ const support = block.renderer === "public-contract-table" ? publicContractSupport(referenced, input.facts) : [];
11602
+ const consumed = [...referenced, ...support];
11204
11603
  return buildIndexerRenderedContentBlock({
11205
11604
  layer: block.layer,
11206
11605
  markdown: renderIndexerDeterministicFacts({
11207
11606
  renderer: block.renderer,
11208
- facts: referenced
11607
+ facts: referenced,
11608
+ supporting_facts: support
11209
11609
  }),
11210
- fact_refs: referenced.map((fact) => fact.fact_ref),
11211
- evidence_refs: referenced.flatMap((fact) => fact.evidence_refs)
11610
+ fact_refs: consumed.map((fact) => fact.fact_ref),
11611
+ evidence_refs: consumed.flatMap((fact) => fact.evidence_refs)
11212
11612
  });
11213
11613
  });
11614
+ if (key !== undefined && input.render_cache !== undefined) {
11615
+ if (input.render_cache.size >= 256)
11616
+ input.render_cache.delete(input.render_cache.keys().next().value);
11617
+ input.render_cache.set(key, structuredClone(rendered));
11618
+ }
11619
+ return rendered;
11214
11620
  }
11215
11621
 
11216
11622
  // src/indexerArtifact.ts
@@ -11244,6 +11650,7 @@ var indexerTemplateArtifactSchema = exports_external.object({
11244
11650
  var indexerSectionArtifactSchema = exports_external.object({
11245
11651
  ...artifactCommonFields,
11246
11652
  representation: exports_external.literal("sections"),
11653
+ template_id: indexerIdSchema.optional(),
11247
11654
  sections: exports_external.array(indexerArtifactSectionSchema).min(1)
11248
11655
  }).strict();
11249
11656
  var indexerArtifactSchema = exports_external.discriminatedUnion("representation", [
@@ -12233,7 +12640,8 @@ function indexerParserLockedDependency(lockValue) {
12233
12640
  // src/indexerRestrictedSelector.ts
12234
12641
  var indexerSelectorFactPathSchema = exports_external.string().regex(/^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*$/u);
12235
12642
  var scalarSchema = exports_external.union([exports_external.string(), exports_external.number().finite(), exports_external.boolean()]);
12236
- var expressionSchema = exports_external.lazy(() => exports_external.union([
12643
+ var expressionSchema = exports_external.lazy(() => expressionVariantsSchema);
12644
+ var expressionVariantsSchema = exports_external.union([
12237
12645
  exports_external.object({
12238
12646
  op: exports_external.enum(["all", "any"]),
12239
12647
  args: exports_external.array(expressionSchema).min(1)
@@ -12265,7 +12673,7 @@ var expressionSchema = exports_external.lazy(() => exports_external.union([
12265
12673
  fact: indexerSelectorFactPathSchema,
12266
12674
  value: exports_external.number().finite()
12267
12675
  }).strict()
12268
- ]));
12676
+ ]);
12269
12677
  var indexerRestrictedSelectorSchema = exports_external.object({
12270
12678
  protocol: exports_external.literal("context.indexer.selector/v1"),
12271
12679
  expression: expressionSchema
@@ -12354,14 +12762,15 @@ var INDEXER_SELECTOR_OPERATORS = [
12354
12762
  ];
12355
12763
 
12356
12764
  // src/indexerProfileContract.ts
12357
- var canonicalParametersSchema = exports_external.lazy(() => exports_external.union([
12765
+ var canonicalParametersSchema = exports_external.lazy(() => canonicalParameterVariantsSchema);
12766
+ var canonicalParameterVariantsSchema = exports_external.union([
12358
12767
  exports_external.null(),
12359
12768
  exports_external.boolean(),
12360
12769
  exports_external.number().finite(),
12361
12770
  exports_external.string(),
12362
12771
  exports_external.array(canonicalParametersSchema),
12363
12772
  exports_external.record(canonicalParametersSchema)
12364
- ]));
12773
+ ]);
12365
12774
  var indexerOperatorContractSchema = exports_external.object({
12366
12775
  protocol: exports_external.literal("context.indexer.operator-contract/v1"),
12367
12776
  version: indexerSemverSchema,
@@ -12935,9 +13344,13 @@ var instructionResourceSchema = exports_external.object({
12935
13344
  addDuplicateIssues(value.profiles, context, "profiles");
12936
13345
  });
12937
13346
  var templateResourceSchema = exports_external.object({
13347
+ kind: exports_external.enum(["procedure", "page-program"]).optional(),
12938
13348
  id: indexerIdSchema,
12939
13349
  profile: indexerIdSchema,
12940
- path: portableIndexerPathSchema
13350
+ path: portableIndexerPathSchema,
13351
+ reader_goal: indexerIdSchema.optional(),
13352
+ guidance_path: portableIndexerPathSchema.optional(),
13353
+ delivery: exports_external.enum(["profile", "selected"]).optional()
12941
13354
  }).strict();
12942
13355
  var providerResourcesSchema = exports_external.object({
12943
13356
  program: indexerProgramSchema.optional(),
@@ -13104,6 +13517,21 @@ var indexerProviderManifestSchema = exports_external.object({
13104
13517
  });
13105
13518
  }
13106
13519
  });
13520
+ const supports = value.customization?.supports ?? [];
13521
+ if (supports.includes("config") && value.provider.config_schema === undefined) {
13522
+ context.addIssue({
13523
+ code: exports_external.ZodIssueCode.custom,
13524
+ message: "customization supports config but the Provider declares no config_schema",
13525
+ path: ["customization", "supports"]
13526
+ });
13527
+ }
13528
+ if (supports.includes("program-extend") && value.provider.program === undefined) {
13529
+ context.addIssue({
13530
+ code: exports_external.ZodIssueCode.custom,
13531
+ message: "customization supports program-extend but the Provider declares no program",
13532
+ path: ["customization", "supports"]
13533
+ });
13534
+ }
13107
13535
  });
13108
13536
  function parseYamlDocument(source, label) {
13109
13537
  const document = $parseDocument(source, { uniqueKeys: true });
@@ -13125,7 +13553,7 @@ function referencedProviderPaths(manifest) {
13125
13553
  ...manifest.authoring_inspector === undefined ? [] : [manifest.authoring_inspector.execution.entry],
13126
13554
  ...manifest.provider.program === undefined ? [] : [manifest.provider.program.execution.entry],
13127
13555
  ...(manifest.provider.instructions ?? []).map((item) => item.path),
13128
- ...(manifest.provider.templates ?? []).map((item) => item.path),
13556
+ ...(manifest.provider.templates ?? []).flatMap((item) => [item.path, ...item.guidance_path === undefined ? [] : [item.guidance_path]]),
13129
13557
  ...(manifest.provides.composers ?? []).flatMap((item) => item.contract === undefined ? [] : [item.contract.instruction]),
13130
13558
  ...manifest.provider.config_schema === undefined ? [] : [manifest.provider.config_schema],
13131
13559
  ...manifest.customization?.guide === undefined ? [] : [manifest.customization.guide],
@@ -13203,10 +13631,12 @@ var requirementQuestionSchema = exports_external.object({
13203
13631
  var requirementExclusionSchema = exports_external.object({
13204
13632
  id: indexerIdSchema,
13205
13633
  scope: targetScopeSchema,
13206
- reason: exports_external.string().min(1)
13634
+ reason: exports_external.string().min(1),
13635
+ 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
13636
  }).strict();
13208
13637
  var indexRequirementSchema = exports_external.object({
13209
13638
  id: indexerIdSchema,
13639
+ purpose: exports_external.string().trim().min(1).optional(),
13210
13640
  reader_goals: exports_external.array(indexerIdSchema).min(1),
13211
13641
  coverage_domains: exports_external.record(indexerIdSchema, exports_external.enum(["required", "optional", "out-of-scope"])),
13212
13642
  questions: exports_external.array(requirementQuestionSchema).optional(),
@@ -13371,7 +13801,7 @@ var providerLayerSchema = exports_external.object({
13371
13801
  });
13372
13802
  }
13373
13803
  });
13374
- var indexerRegistryEntrySchema = exports_external.object({
13804
+ var indexerRegistryEntryInputSchema = exports_external.object({
13375
13805
  id: indexerIdSchema,
13376
13806
  operations: exports_external.array(exports_external.enum(INDEXER_SEMANTIC_OPERATIONS)).min(1).default(["main-index"]),
13377
13807
  requirement_bindings: exports_external.array(requirementBindingSchema).min(1),
@@ -13385,7 +13815,8 @@ var indexerRegistryEntrySchema = exports_external.object({
13385
13815
  customization: exports_external.object({
13386
13816
  mode: exports_external.enum(["extend", "replace"])
13387
13817
  }).strict().optional()
13388
- }).strict().transform((value) => ({
13818
+ }).strict();
13819
+ var indexerRegistryEntrySchema = indexerRegistryEntryInputSchema.transform((value) => ({
13389
13820
  ...value,
13390
13821
  read_scope: value.read_scope ?? {
13391
13822
  refs: [...new Set(value.requirement_bindings.flatMap((binding) => binding.role === "primary" ? [
@@ -14309,14 +14740,15 @@ function validateIndexerControlledInvocation(value) {
14309
14740
  return invocation;
14310
14741
  }
14311
14742
  // 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(),
14743
+ var canonicalJsonSchema2 = exports_external.lazy(() => canonicalJsonVariantsSchema);
14744
+ var canonicalJsonVariantsSchema = exports_external.union([
14316
14745
  exports_external.string(),
14746
+ exports_external.number().finite(),
14747
+ exports_external.boolean(),
14748
+ exports_external.null(),
14317
14749
  exports_external.array(canonicalJsonSchema2),
14318
14750
  exports_external.record(canonicalJsonSchema2)
14319
- ]));
14751
+ ]);
14320
14752
  var parserFactSchema = exports_external.object({
14321
14753
  fact_ref: indexerCanonicalRefSchema,
14322
14754
  kind: indexerIdSchema,
@@ -14648,6 +15080,164 @@ function buildIndexerMergedParserFactView(input) {
14648
15080
  });
14649
15081
  }
14650
15082
 
15083
+ // src/indexerKnowledgeDependency.ts
15084
+ var indexerKnowledgeDependencySchema = exports_external.object({
15085
+ artifact_ref: indexerCanonicalRefSchema,
15086
+ section_refs: exports_external.array(indexerCanonicalRefSchema).default([]),
15087
+ required: exports_external.boolean().default(true)
15088
+ }).strict();
15089
+
15090
+ class IndexerKnowledgeDependencyCycleError extends TypeError {
15091
+ artifact_refs;
15092
+ constructor(artifact_refs) {
15093
+ super(`Knowledge dependency cycle: ${artifact_refs.join(" -> ")}. Revise the Partition dependency plan.`);
15094
+ this.artifact_refs = artifact_refs;
15095
+ this.name = "IndexerKnowledgeDependencyCycleError";
15096
+ }
15097
+ }
15098
+ function validateIndexerKnowledgeDependencyGraph(nodes) {
15099
+ const graph = new Map;
15100
+ for (const node of nodes) {
15101
+ indexerCanonicalRefSchema.parse(node.artifact_ref);
15102
+ if (graph.has(node.artifact_ref))
15103
+ throw new TypeError(`Knowledge article has duplicate responsibility: ${node.artifact_ref}`);
15104
+ const dependencies = node.dependencies.map((dependency) => indexerKnowledgeDependencySchema.parse(dependency));
15105
+ if (new Set(dependencies.map((dependency) => dependency.artifact_ref)).size !== dependencies.length) {
15106
+ throw new TypeError(`Knowledge article repeats a dependency: ${node.artifact_ref}`);
15107
+ }
15108
+ if (dependencies.some((dependency) => new Set(dependency.section_refs).size !== dependency.section_refs.length)) {
15109
+ throw new TypeError(`Knowledge article repeats a supporting section: ${node.artifact_ref}`);
15110
+ }
15111
+ graph.set(node.artifact_ref, dependencies);
15112
+ }
15113
+ const complete = new Set;
15114
+ const active = new Set;
15115
+ const visit2 = (ref, trail) => {
15116
+ if (active.has(ref))
15117
+ throw new IndexerKnowledgeDependencyCycleError([...trail.slice(trail.indexOf(ref)), ref]);
15118
+ if (complete.has(ref))
15119
+ return;
15120
+ active.add(ref);
15121
+ for (const dependency of graph.get(ref) ?? [])
15122
+ visit2(dependency.artifact_ref, [...trail, ref]);
15123
+ active.delete(ref);
15124
+ complete.add(ref);
15125
+ };
15126
+ for (const ref of graph.keys())
15127
+ visit2(ref, []);
15128
+ }
15129
+ var indexerKnowledgeDependencyVersionSchema = exports_external.object({
15130
+ artifact_ref: indexerCanonicalRefSchema,
15131
+ approved_content_digest: indexerDigestSchema,
15132
+ projection_digest: indexerDigestSchema
15133
+ }).strict();
15134
+ function indexerKnowledgeDependencyFingerprint(versions) {
15135
+ const parsed = versions.map((version) => indexerKnowledgeDependencyVersionSchema.parse(version));
15136
+ if (new Set(parsed.map((version) => version.artifact_ref)).size !== parsed.length) {
15137
+ throw new TypeError("Knowledge dependency versions repeat an article");
15138
+ }
15139
+ return indexerProtocolDigest(parsed.sort((left, right) => compareIndexerCanonicalText(left.artifact_ref, right.artifact_ref)));
15140
+ }
15141
+ function impactedIndexerKnowledgeArticles(nodes, changed) {
15142
+ validateIndexerKnowledgeDependencyGraph(nodes);
15143
+ const reverse = new Map;
15144
+ for (const node of nodes)
15145
+ for (const dependency of node.dependencies) {
15146
+ const readers = reverse.get(dependency.artifact_ref) ?? new Set;
15147
+ readers.add(node.artifact_ref);
15148
+ reverse.set(dependency.artifact_ref, readers);
15149
+ }
15150
+ const impacted = new Set(changed);
15151
+ const queue = [...changed];
15152
+ for (let cursor = 0;cursor < queue.length; cursor++) {
15153
+ for (const reader of reverse.get(queue[cursor]) ?? []) {
15154
+ if (impacted.has(reader))
15155
+ continue;
15156
+ impacted.add(reader);
15157
+ queue.push(reader);
15158
+ }
15159
+ }
15160
+ return [...impacted].filter((ref) => !changed.has(ref)).sort();
15161
+ }
15162
+
15163
+ // src/indexerArticlePlan.ts
15164
+ var indexerArticleKeySchema = exports_external.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u);
15165
+ var indexerArticlePlanSchema = exports_external.object({
15166
+ key: indexerArticleKeySchema,
15167
+ title: exports_external.string().min(1),
15168
+ reader_task: exports_external.string().min(1),
15169
+ artifact_intent: exports_external.string().min(1),
15170
+ template_id: exports_external.string().min(1).optional(),
15171
+ required: exports_external.boolean(),
15172
+ sections: exports_external.array(exports_external.object({
15173
+ key: indexerArticleKeySchema,
15174
+ heading: exports_external.string().min(1),
15175
+ required: exports_external.boolean()
15176
+ }).strict()).min(1),
15177
+ question_targets: exports_external.array(exports_external.string().min(1)).default([]),
15178
+ knowledge_dependencies: exports_external.array(indexerKnowledgeDependencySchema).optional()
15179
+ }).strict();
15180
+ function validateIndexerArticlePlan(articles, targets) {
15181
+ if (!articles.length || !articles.some((article) => article.required)) {
15182
+ throw new TypeError("article plan needs at least one required article; revise the current Partition plan");
15183
+ }
15184
+ const keys = new Set, owners = new Set;
15185
+ for (const article of articles) {
15186
+ indexerArticlePlanSchema.parse(article);
15187
+ if (keys.has(article.key))
15188
+ throw new TypeError(`duplicate article key ${article.key}; choose stable unique keys in Partition`);
15189
+ keys.add(article.key);
15190
+ if (new Set(article.sections.map((section) => section.key)).size !== article.sections.length) {
15191
+ throw new TypeError(`article ${article.key} repeats a section key; revise its section plan`);
15192
+ }
15193
+ for (const target of article.question_targets) {
15194
+ if (!article.required || owners.has(target) || targets !== undefined && !targets.includes(target)) {
15195
+ throw new TypeError(`article ${article.key} has invalid question responsibility ${target}; assign each group target to one required article`);
15196
+ }
15197
+ owners.add(target);
15198
+ }
15199
+ }
15200
+ if (targets?.some((target) => !owners.has(target))) {
15201
+ throw new TypeError("article plan leaves a question without a primary article; revise the current Partition plan");
15202
+ }
15203
+ }
15204
+ function indexerArticleSectionKey(article, section) {
15205
+ return `${article}--${section}`;
15206
+ }
15207
+ function validateIndexerPlannedArticles(result, articles) {
15208
+ const warnings = [];
15209
+ validateIndexerArticlePlan(articles);
15210
+ const planned = new Map(articles.map((article) => [article.key, article]));
15211
+ for (const artifact of result.artifacts) {
15212
+ const article = planned.get(artifact.artifact_id);
15213
+ if (!article)
15214
+ throw new TypeError(`unplanned article ${artifact.artifact_id}; revise Partition before adding an article`);
15215
+ if (artifact.template_id !== article.template_id) {
15216
+ throw new TypeError(`article ${article.key} changes its accepted template; use the planned template or revise Partition`);
15217
+ }
15218
+ const sections = artifact.representation === "sections" ? artifact.sections : artifact.section_projections;
15219
+ const expected = new Map(article.sections.map((section) => [indexerArticleSectionKey(article.key, section.key), section]));
15220
+ for (const section of sections) {
15221
+ if (!expected.has(section.section_key))
15222
+ warnings.push({ code: "article-outline-drift", message: `Article ${article.key} includes additional section ${section.section_key}. Review its relevance; this does not block publication.` });
15223
+ const intent = [result.source_role, section.document_kind, section.reader_goal, section.artifact_kind].join("/");
15224
+ if (intent !== article.artifact_intent)
15225
+ throw new TypeError(`article ${article.key} changes its accepted intent; use ${article.artifact_intent}`);
15226
+ }
15227
+ for (const [key, section] of expected) {
15228
+ if (section.required && !sections.some((actual) => actual.section_key === key)) {
15229
+ 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.` });
15230
+ }
15231
+ }
15232
+ }
15233
+ for (const article of articles) {
15234
+ if (article.required && !result.artifacts.some((artifact) => artifact.artifact_id === article.key)) {
15235
+ throw new TypeError(`missing required article ${article.key}; complete the accepted article set before submitting`);
15236
+ }
15237
+ }
15238
+ return warnings;
15239
+ }
15240
+
14651
15241
  // src/indexerArtifactPolicy.ts
14652
15242
  var canonicalJsonSchema3 = exports_external.lazy(() => exports_external.union([
14653
15243
  exports_external.null(),
@@ -15672,7 +16262,7 @@ function validateTargetExists(input) {
15672
16262
  return;
15673
16263
  }
15674
16264
  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) {
16265
+ if (fact === undefined || fact.qualified_item_path !== target.qualified_item_path) {
15676
16266
  throw new TypeError("structured declaration source item does not exist");
15677
16267
  }
15678
16268
  }
@@ -15694,7 +16284,7 @@ function validateIndexerStructuredDeclarationSet(input) {
15694
16284
  throw new TypeError("structured declaration set is non-canonical or invalid");
15695
16285
  }
15696
16286
  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) {
16287
+ if (inventory.source_ref !== input.expected_source_ref || inventory.module_ref !== input.expected_module_ref) {
15698
16288
  throw new TypeError("structured declarations do not match current source identity");
15699
16289
  }
15700
16290
  const evidence = new Set(canonicalUnique4(input.known_evidence_refs, "known declaration evidence"));
@@ -15723,7 +16313,7 @@ function indexerSectionEvidenceCarrierRef(input) {
15723
16313
  return `section-evidence:${indexerProtocolDigest(input)}`;
15724
16314
  }
15725
16315
 
15726
- // src/indexerGeneratedAuthoringAudit.ts
16316
+ // src/indexerStructuredClaims.ts
15727
16317
  var structuredClaimOwnerSchema = exports_external.object({
15728
16318
  artifact_id: indexerIdSchema,
15729
16319
  section_key: indexerIdSchema
@@ -15742,53 +16332,6 @@ var indexerStructuredClaimSetSchema = exports_external.object({
15742
16332
  claims: exports_external.array(structuredClaimSchema).min(1),
15743
16333
  claims_digest: indexerDigestSchema
15744
16334
  }).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
16335
  function assertCanonicalUnique(values, label) {
15793
16336
  const expected = [...new Set(values)].sort(compareIndexerCanonicalText);
15794
16337
  if (expected.length !== values.length || expected.some((value, index) => value !== values[index])) {
@@ -15848,135 +16391,6 @@ function validateIndexerStructuredClaimSet(input) {
15848
16391
  }
15849
16392
  return value;
15850
16393
  }
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
16394
 
15981
16395
  // src/indexerArtifactResult.ts
15982
16396
  var indexerEvidenceBindingSchema = exports_external.object({
@@ -16360,8 +16774,10 @@ function validateIndexerArtifactResult(input) {
16360
16774
  if (indexerArtifactResultDigest(payload) !== result.output_digest) {
16361
16775
  throw new TypeError("ArtifactResult output digest is invalid");
16362
16776
  }
16777
+ if (input.planned_articles !== undefined)
16778
+ validateIndexerPlannedArticles(result, input.planned_articles);
16363
16779
  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) {
16780
+ 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
16781
  throw new TypeError("ArtifactResult does not match its author authority/workset");
16366
16782
  }
16367
16783
  if (!input.allowed_source_roles.includes(result.source_role)) {
@@ -16422,7 +16838,6 @@ function validateIndexerArtifactResult(input) {
16422
16838
  authorized_carriers: input.authorized_declaration_carriers
16423
16839
  });
16424
16840
  validateStructuredClaims({ result, evidence_refs: evidenceRefs, facts });
16425
- assertIndexerGeneratedAuthoringAuditClear(buildIndexerGeneratedAuthoringAudit(result));
16426
16841
  validateTargetResolution(result, input.workset.target_resolution_view, evidenceRefs);
16427
16842
  validateQuestions({ result, allowed_question_targets: input.allowed_question_targets });
16428
16843
  return result;
@@ -16478,12 +16893,12 @@ var logicalUnitNodeInputSchema = exports_external.object({
16478
16893
  targets: dependencyTargetsSchema
16479
16894
  }).strict();
16480
16895
  var resourceNodeInputSchema = exports_external.object({
16481
- kind: exports_external.enum(["template-policy-fragment", "contract-metric"]),
16896
+ kind: exports_external.enum(["template-policy-fragment", "contract-metric", "approved-knowledge"]),
16482
16897
  target_ref: indexerCanonicalRefSchema,
16483
16898
  content_digest: indexerDigestSchema,
16484
16899
  targets: dependencyTargetsSchema
16485
16900
  }).strict();
16486
- var indexerPositiveDependencyNodeInputSchema = exports_external.union([
16901
+ var indexerPositiveDependencyNodeInputSchema = exports_external.discriminatedUnion("kind", [
16487
16902
  sourceSpanNodeInputSchema,
16488
16903
  selectedFactNodeInputSchema,
16489
16904
  logicalUnitNodeInputSchema,
@@ -16515,7 +16930,7 @@ var indexerLogicalUnitDependencyNodeSchema = logicalUnitNodeInputSchema.extend({
16515
16930
  var indexerResourceDependencyNodeSchema = resourceNodeInputSchema.extend({
16516
16931
  node_ref: indexerCanonicalRefSchema
16517
16932
  }).strict();
16518
- var indexerPositiveDependencyNodeSchema = exports_external.union([
16933
+ var indexerPositiveDependencyNodeSchema = exports_external.discriminatedUnion("kind", [
16519
16934
  indexerSourceSpanDependencyNodeSchema,
16520
16935
  indexerSelectedFactDependencyNodeSchema,
16521
16936
  indexerLogicalUnitDependencyNodeSchema,
@@ -16708,6 +17123,171 @@ function compositionFactDependencies(input) {
16708
17123
  });
16709
17124
  }
16710
17125
 
17126
+ // src/indexerExampleIdentity.ts
17127
+ var exampleObservationSchema = exports_external.object({
17128
+ observation_ref: indexerCanonicalRefSchema,
17129
+ example_ref: indexerCanonicalRefSchema,
17130
+ public_target_ref: indexerCanonicalRefSchema,
17131
+ scenario_key: indexerIdSchema,
17132
+ source_ref: indexerCanonicalRefSchema,
17133
+ module_ref: indexerCanonicalRefSchema.nullable(),
17134
+ full_relative_path: portableIndexerPathSchema,
17135
+ content_digest: indexerDigestSchema,
17136
+ evidence_refs: exports_external.array(indexerCanonicalRefSchema).min(1)
17137
+ }).strict();
17138
+ var indexerExampleInventorySchema = exports_external.object({
17139
+ protocol: exports_external.literal("context.indexer.example-inventory/v1"),
17140
+ source_scope_digest: indexerDigestSchema,
17141
+ observations: exports_external.array(exampleObservationSchema),
17142
+ inventory_digest: indexerDigestSchema
17143
+ }).strict();
17144
+ function canonicalUnique5(values, field) {
17145
+ const sorted = [...values].sort(compareIndexerCanonicalText);
17146
+ if (new Set(sorted).size !== sorted.length) {
17147
+ throw new TypeError(`${field} must not contain duplicate identities`);
17148
+ }
17149
+ return sorted;
17150
+ }
17151
+ function normalizeIndexerExampleRelativePath(value) {
17152
+ const normalized = value.normalize("NFC").replaceAll("\\", "/").replace(/^\.\//u, "");
17153
+ return portableIndexerPathSchema.parse(normalized);
17154
+ }
17155
+ function indexerExampleRef(input) {
17156
+ const identity2 = {
17157
+ public_target_ref: indexerCanonicalRefSchema.parse(input.public_target_ref),
17158
+ scenario_key: indexerIdSchema.parse(input.scenario_key),
17159
+ full_relative_path: normalizeIndexerExampleRelativePath(input.full_relative_path)
17160
+ };
17161
+ return `example:${indexerProtocolDigest(identity2)}`;
17162
+ }
17163
+ function indexerExampleObservationRef(input) {
17164
+ return `example-observation:${indexerProtocolDigest(input)}`;
17165
+ }
17166
+ function indexerExampleInventoryDigest(value) {
17167
+ return indexerProtocolDigest(value);
17168
+ }
17169
+ function normalizeObservation(input) {
17170
+ const fullRelativePath = normalizeIndexerExampleRelativePath(input.full_relative_path);
17171
+ const publicTargetRef = indexerCanonicalRefSchema.parse(input.public_target_ref);
17172
+ const scenarioKey = indexerIdSchema.parse(input.scenario_key);
17173
+ const sourceRef = indexerCanonicalRefSchema.parse(input.source_ref);
17174
+ const moduleRef = input.module_ref === null ? null : indexerCanonicalRefSchema.parse(input.module_ref);
17175
+ const contentDigest = indexerDigestSchema.parse(input.content_digest);
17176
+ const exampleRef = indexerExampleRef({
17177
+ public_target_ref: publicTargetRef,
17178
+ scenario_key: scenarioKey,
17179
+ full_relative_path: fullRelativePath
17180
+ });
17181
+ return exampleObservationSchema.parse({
17182
+ observation_ref: indexerExampleObservationRef({
17183
+ example_ref: exampleRef,
17184
+ source_ref: sourceRef,
17185
+ module_ref: moduleRef,
17186
+ content_digest: contentDigest
17187
+ }),
17188
+ example_ref: exampleRef,
17189
+ public_target_ref: publicTargetRef,
17190
+ scenario_key: scenarioKey,
17191
+ source_ref: sourceRef,
17192
+ module_ref: moduleRef,
17193
+ full_relative_path: fullRelativePath,
17194
+ content_digest: contentDigest,
17195
+ evidence_refs: canonicalUnique5(input.evidence_refs, "example evidence_refs")
17196
+ });
17197
+ }
17198
+ function buildIndexerExampleInventory(input) {
17199
+ const byObservation = new Map;
17200
+ for (const observationInput of input.observations) {
17201
+ const observation = normalizeObservation(observationInput);
17202
+ const current = byObservation.get(observation.observation_ref);
17203
+ if (current === undefined) {
17204
+ byObservation.set(observation.observation_ref, observation);
17205
+ continue;
17206
+ }
17207
+ const currentCore = { ...current, evidence_refs: undefined };
17208
+ const nextCore = { ...observation, evidence_refs: undefined };
17209
+ if (canonicalIndexerJson(currentCore) !== canonicalIndexerJson(nextCore)) {
17210
+ throw new TypeError("example observation identity collision");
17211
+ }
17212
+ current.evidence_refs = [...new Set([
17213
+ ...current.evidence_refs,
17214
+ ...observation.evidence_refs
17215
+ ])].sort(compareIndexerCanonicalText);
17216
+ }
17217
+ const observations = [...byObservation.values()].sort((left, right) => compareIndexerCanonicalText(left.observation_ref, right.observation_ref));
17218
+ const payload = {
17219
+ protocol: "context.indexer.example-inventory/v1",
17220
+ source_scope_digest: indexerDigestSchema.parse(input.source_scope_digest),
17221
+ observations
17222
+ };
17223
+ return indexerExampleInventorySchema.parse({
17224
+ ...payload,
17225
+ inventory_digest: indexerExampleInventoryDigest(payload)
17226
+ });
17227
+ }
17228
+ function validateIndexerExampleInventory(input) {
17229
+ const value = indexerExampleInventorySchema.parse(input.value);
17230
+ const rebuilt = buildIndexerExampleInventory({
17231
+ source_scope_digest: value.source_scope_digest,
17232
+ observations: value.observations
17233
+ });
17234
+ if (canonicalIndexerJson(rebuilt) !== canonicalIndexerJson(value)) {
17235
+ throw new TypeError("example inventory is non-canonical or has an invalid digest");
17236
+ }
17237
+ if (input.expected_source_scope_digest !== undefined && value.source_scope_digest !== input.expected_source_scope_digest) {
17238
+ throw new TypeError("example inventory belongs to another source scope");
17239
+ }
17240
+ if (input.known_evidence_refs !== undefined) {
17241
+ const known = new Set(canonicalUnique5(input.known_evidence_refs, "known_evidence_refs"));
17242
+ if (value.observations.some((item) => item.evidence_refs.some((evidenceRef) => !known.has(evidenceRef)))) {
17243
+ throw new TypeError("example inventory references unknown evidence");
17244
+ }
17245
+ }
17246
+ return value;
17247
+ }
17248
+
17249
+ // src/indexerExampleFactDependencies.ts
17250
+ function exampleFactDependencies(input) {
17251
+ const examples = input.result.facts.filter((fact) => fact.fact_kind === "example-candidate");
17252
+ if (!examples.length)
17253
+ return [];
17254
+ const observationSchema = indexerExampleInventorySchema.shape.observations.element;
17255
+ const observations = examples.map((fact) => {
17256
+ if (fact.value === null || typeof fact.value !== "object" || Array.isArray(fact.value)) {
17257
+ throw new TypeError("Example selection must identify an authorized source observation");
17258
+ }
17259
+ const { inventory_digest, ...value } = fact.value;
17260
+ return { fact, inventory_digest, observation: observationSchema.parse(value) };
17261
+ });
17262
+ const inventory = validateIndexerExampleInventory({ value: {
17263
+ protocol: "context.indexer.example-inventory/v1",
17264
+ source_scope_digest: input.workset.source_scope_digest,
17265
+ observations: observations.map((item) => item.observation).sort((a, b) => compareIndexerCanonicalText(a.observation_ref, b.observation_ref)),
17266
+ inventory_digest: observations[0].inventory_digest
17267
+ }, expected_source_scope_digest: input.workset.source_scope_digest });
17268
+ const spans = new Map(input.dependency_view.positive_nodes.flatMap((node) => node.kind === "source-span" ? [[node.evidence_ref, node]] : []));
17269
+ return observations.map(({ fact, observation, inventory_digest }) => {
17270
+ 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)) {
17271
+ throw new TypeError("Example selection identity does not match its current task");
17272
+ }
17273
+ const sourceRefs = observation.evidence_refs.map((ref) => {
17274
+ const span = spans.get(ref);
17275
+ 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) {
17276
+ throw new TypeError("Example selection source is outside the current dependency view or has changed");
17277
+ }
17278
+ return span.node_ref;
17279
+ }).sort(compareIndexerCanonicalText);
17280
+ const node = {
17281
+ kind: "selected-fact",
17282
+ fact_ref: fact.fact_ref,
17283
+ fact_digest: indexerProtocolDigest(fact),
17284
+ source_span_node_refs: sourceRefs,
17285
+ targets: []
17286
+ };
17287
+ return { ...node, node_ref: indexerDependencyNodeRef({ polarity: "positive", node }) };
17288
+ });
17289
+ }
17290
+
16711
17291
  // src/indexerRunProtocolCommon.ts
16712
17292
  var indexerRunFinalAuthoritySchema = exports_external.object({
16713
17293
  layer_ref: indexerProviderLayerRefSchema,
@@ -16841,6 +17421,10 @@ function buildIndexerPrimaryRegistryProjection(input) {
16841
17421
  owned_scope: "ref" in binding.owned_scope ? binding.owned_scope : { targets: canonicalTargets2(binding.owned_scope.targets) }
16842
17422
  })).sort((left, right) => compareIndexerCanonicalText(indexerProtocolDigest(left), indexerProtocolDigest(right)));
16843
17423
  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}`));
17424
+ const readRequirementIds = new Set(entry.read_scope.refs.flatMap((ref) => {
17425
+ const match = /^requirement:([^#]+)#/u.exec(ref);
17426
+ return match ? [match[1]] : [];
17427
+ }));
16844
17428
  const payload = {
16845
17429
  protocol: "context.indexer.primary-registry-projection/v1",
16846
17430
  indexer_id: entry.id,
@@ -16848,6 +17432,7 @@ function buildIndexerPrimaryRegistryProjection(input) {
16848
17432
  requirement_bindings: requirementBindings,
16849
17433
  read_scope: {
16850
17434
  refs: [...entry.read_scope.refs].sort(compareIndexerCanonicalText),
17435
+ requirements: input.registry.requirements.filter((requirement) => readRequirementIds.has(requirement.id)).sort((a, b) => compareIndexerCanonicalText(a.id, b.id)),
16851
17436
  ...entry.read_scope.extra_targets === undefined ? {} : { extra_targets: canonicalTargets2(entry.read_scope.extra_targets) }
16852
17437
  },
16853
17438
  profile: {
@@ -17156,7 +17741,7 @@ var indexerArtifactDependencySetSchema = exports_external.object({
17156
17741
  artifacts: exports_external.array(artifactDependencySchema),
17157
17742
  dependency_set_digest: indexerDigestSchema
17158
17743
  }).strict();
17159
- function canonicalUnique5(values) {
17744
+ function canonicalUnique6(values) {
17160
17745
  return [...new Set(values)].sort(compareIndexerCanonicalText);
17161
17746
  }
17162
17747
  function versionedPositive(node) {
@@ -17179,8 +17764,8 @@ function artifactDependency(value) {
17179
17764
  }
17180
17765
  function artifactSections(artifact) {
17181
17766
  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));
17767
+ const factRefs = canonicalUnique6(Object.values(artifact.variables).flatMap((variable) => variable.fact_refs));
17768
+ const evidenceRefs = canonicalUnique6(Object.values(artifact.variables).flatMap((variable) => variable.evidence_refs));
17184
17769
  return artifact.section_projections.map((section) => ({
17185
17770
  section_key: section.section_key,
17186
17771
  fact_refs: factRefs,
@@ -17189,8 +17774,8 @@ function artifactSections(artifact) {
17189
17774
  }
17190
17775
  return artifact.sections.map((section) => ({
17191
17776
  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 : []))
17777
+ fact_refs: canonicalUnique6(section.blocks.flatMap((block) => block.layer === "deterministic-block" ? block.fact_refs : [])),
17778
+ evidence_refs: canonicalUnique6(section.blocks.flatMap((block) => block.layer === "semantic-prose" ? block.evidence_refs : []))
17194
17779
  }));
17195
17780
  }
17196
17781
  function dependencySetPayload(value) {
@@ -17202,7 +17787,7 @@ function indexerArtifactDependencySetDigest(value) {
17202
17787
  }
17203
17788
  function assertBoundInputs(input) {
17204
17789
  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) {
17790
+ 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
17791
  throw new TypeError("Artifact dependency inputs do not bind the same current author run");
17207
17792
  }
17208
17793
  const logical = dependencyView.positive_nodes.find((node) => node.kind === "logical-unit");
@@ -17231,6 +17816,7 @@ function buildIndexerArtifactDependencySet(input) {
17231
17816
  });
17232
17817
  const sourceNodes = dependencyView.positive_nodes.filter((node) => node.kind === "source-span");
17233
17818
  const sourceByEvidence = new Map(sourceNodes.map((node) => [node.evidence_ref, node]));
17819
+ const sourceByNode = new Map(sourceNodes.map((node) => [node.node_ref, node]));
17234
17820
  const evidenceByRef = new Map(input.result.evidence_bindings.map((evidence) => {
17235
17821
  let node = sourceByEvidence.get(evidence.evidence_ref);
17236
17822
  const belongsToPrimary = evidence.source_ref === input.workset.source_ref && evidence.module_ref === input.workset.module_ref;
@@ -17253,23 +17839,18 @@ function buildIndexerArtifactDependencySet(input) {
17253
17839
  node_ref: indexerDependencyNodeRef({ polarity: "positive", node: supplemental })
17254
17840
  });
17255
17841
  }
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`);
17842
+ 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) {
17843
+ throw new TypeError(`Source ${evidence.evidence_ref} is unavailable or its file content changed; refresh the current task's source material`);
17268
17844
  }
17269
- return [evidence.evidence_ref, versionedPositive(node)];
17845
+ const current = { ...node, locator: evidence.locator };
17846
+ return [evidence.evidence_ref, versionedPositive({
17847
+ ...current,
17848
+ node_ref: indexerDependencyNodeRef({ polarity: "positive", node: current })
17849
+ })];
17270
17850
  }));
17271
17851
  const factNodes = [
17272
17852
  ...dependencyView.positive_nodes.filter((node) => node.kind === "selected-fact"),
17853
+ ...exampleFactDependencies({ workset: input.workset, dependency_view: dependencyView, result: input.result }),
17273
17854
  ...input.composition_input === undefined ? [] : compositionFactDependencies({
17274
17855
  composition_input: input.composition_input,
17275
17856
  workset: input.workset,
@@ -17280,27 +17861,35 @@ function buildIndexerArtifactDependencySet(input) {
17280
17861
  const factNodeByRef = new Map(factNodes.map((node) => [node.fact_ref, node]));
17281
17862
  const factByRef = new Map(input.result.facts.map((fact) => {
17282
17863
  const node = factNodeByRef.get(fact.fact_ref);
17283
- const sourceSpanNodeRefs = canonicalUnique5(fact.evidence_refs.map((ref) => {
17864
+ const sourceSpanNodeRefs = canonicalUnique6(fact.evidence_refs.map((ref) => {
17284
17865
  const evidence = evidenceByRef.get(ref);
17285
17866
  if (evidence === undefined) {
17286
17867
  throw new TypeError(`Fact ${fact.fact_ref} references evidence outside the dependency view`);
17287
17868
  }
17288
17869
  return evidence.node_ref;
17289
17870
  }));
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`);
17871
+ if (node === undefined) {
17872
+ throw new TypeError(`Fact ${fact.fact_ref} is not available in the current task; use a supplied Fact or source_items reference`);
17292
17873
  }
17293
- return [fact.fact_ref, versionedPositive(node)];
17874
+ const expectedEvidence = canonicalUnique6(node.source_span_node_refs.map((ref) => sourceByNode.get(ref).evidence_ref));
17875
+ if (canonicalIndexerJson(expectedEvidence) !== canonicalIndexerJson(canonicalUnique6(fact.evidence_refs))) {
17876
+ throw new TypeError(`Fact ${fact.fact_ref} refers to a different source than the current task`);
17877
+ }
17878
+ return [fact.fact_ref, versionedPositive({
17879
+ ...node,
17880
+ fact_digest: indexerProtocolDigest(fact),
17881
+ source_span_node_refs: sourceSpanNodeRefs
17882
+ })];
17294
17883
  }));
17295
17884
  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);
17885
+ const resources = dependencyView.positive_nodes.filter((node) => node.kind === "template-policy-fragment" || node.kind === "contract-metric" || node.kind === "approved-knowledge").map(versionedPositive);
17297
17886
  const negatives = dependencyView.negative_nodes.map(versionedNegative);
17298
17887
  const usedPositive = new Map([[logical.node_ref, logical]]);
17299
17888
  const usedNegative = new Map;
17300
17889
  const artifacts = input.result.artifacts.map((artifact) => {
17301
17890
  const sections = artifactSections(artifact).map((section) => {
17302
17891
  const facts = section.fact_refs.map((ref) => factByRef.get(ref));
17303
- const evidenceRefs = canonicalUnique5([
17892
+ const evidenceRefs = canonicalUnique6([
17304
17893
  ...section.evidence_refs,
17305
17894
  ...section.fact_refs.flatMap((ref) => input.result.facts.find((fact) => fact.fact_ref === ref).evidence_refs)
17306
17895
  ]);
@@ -17326,20 +17915,20 @@ function buildIndexerArtifactDependencySet(input) {
17326
17915
  }
17327
17916
  return sectionDependency({
17328
17917
  section_key: section.section_key,
17329
- positive_dependency_refs: canonicalUnique5([
17918
+ positive_dependency_refs: canonicalUnique6([
17330
17919
  logical.dependency_ref,
17331
17920
  ...facts.map((item) => item.dependency_ref),
17332
17921
  ...evidence.map((item) => item.dependency_ref),
17333
17922
  ...sectionResources.map((item) => item.dependency_ref)
17334
17923
  ]),
17335
- negative_dependency_refs: canonicalUnique5(sectionNegatives.map((item) => item.dependency_ref))
17924
+ negative_dependency_refs: canonicalUnique6(sectionNegatives.map((item) => item.dependency_ref))
17336
17925
  });
17337
17926
  }).sort((left, right) => compareIndexerCanonicalText(left.section_key, right.section_key));
17338
17927
  return artifactDependency({
17339
17928
  artifact_id: artifact.artifact_id,
17340
17929
  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)),
17930
+ positive_dependency_refs: canonicalUnique6(sections.flatMap((section) => section.positive_dependency_refs)),
17931
+ negative_dependency_refs: canonicalUnique6(sections.flatMap((section) => section.negative_dependency_refs)),
17343
17932
  sections
17344
17933
  });
17345
17934
  }).sort((left, right) => compareIndexerCanonicalText(left.artifact_id, right.artifact_id));
@@ -17468,7 +18057,8 @@ function validateIndexerTargetResolutionView(value) {
17468
18057
  }
17469
18058
  var indexerRepairIntentPayloadSchema = exports_external.object({
17470
18059
  target_ref: exports_external.string().min(1),
17471
- instruction: exports_external.string().trim().min(1)
18060
+ instruction: exports_external.string().trim().min(1),
18061
+ current_markdown: exports_external.string().optional()
17472
18062
  }).strict();
17473
18063
  var indexerRepairIntentSchema = indexerRepairIntentPayloadSchema.extend({
17474
18064
  intent_digest: indexerDigestSchema
@@ -17739,6 +18329,15 @@ var partitionGroupSchema = exports_external.object({
17739
18329
  subject_intent: exports_external.enum(["primary", "enrich-or-independent"]),
17740
18330
  logical_unit_ref: indexerCanonicalRefSchema,
17741
18331
  label: exports_external.string().min(1),
18332
+ scope_change: exports_external.object({ removed_member_ids: exports_external.array(indexerCanonicalRefSchema).min(1) }).strict().optional(),
18333
+ reader_task: exports_external.string().min(1).optional(),
18334
+ outline: exports_external.array(exports_external.string().min(1)).optional(),
18335
+ artifact_intent: exports_external.string().min(1).optional(),
18336
+ template_id: exports_external.string().min(1).optional(),
18337
+ articles: exports_external.array(indexerArticlePlanSchema).min(1).optional(),
18338
+ priority: exports_external.number().int().nonnegative().optional(),
18339
+ delivery_boundary: exports_external.boolean().optional(),
18340
+ ready_for_author: exports_external.boolean().optional(),
17742
18341
  reader_question_refs: exports_external.array(indexerCanonicalRefSchema),
17743
18342
  question_target_bindings: exports_external.array(questionTargetBindingSchema),
17744
18343
  member_ids: exports_external.array(indexerCanonicalRefSchema).min(1)
@@ -17897,6 +18496,8 @@ function validateGroups(plan, allowedQuestions, allowedTargets) {
17897
18496
  if (targetRefs.some((ref) => !allowedTargets.has(ref))) {
17898
18497
  throw new TypeError(`partition group ${group.group_key} creates an unknown question target`);
17899
18498
  }
18499
+ if (group.articles !== undefined)
18500
+ validateIndexerArticlePlan(group.articles, group.question_target_bindings.filter((binding) => binding.role === "primary-carrier").map((binding) => binding.target_ref));
17900
18501
  groups.set(group.group_key, group);
17901
18502
  }
17902
18503
  return groups;
@@ -17982,11 +18583,13 @@ function validateIndexerPartitionPlan(input) {
17982
18583
  });
17983
18584
  if (plan.status === "complete") {
17984
18585
  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")) {
18586
+ 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
18587
  throw new TypeError("empty complete PartitionPlan requires no reader questions, no targets, and no owned members");
17987
18588
  }
17988
18589
  }
17989
- validateQuestionTargetClosure(plan, input.required_question_target_refs ?? input.workset.allowed_question_target_refs);
18590
+ if (plan.groups.length > 0 || plan.member_dispositions.length === 0) {
18591
+ validateQuestionTargetClosure(plan, input.required_question_target_refs ?? input.workset.allowed_question_target_refs);
18592
+ }
17990
18593
  } else {
17991
18594
  const closed = new Set(plan.member_dispositions.map((item) => item.member_id));
17992
18595
  const expectedUnassigned = canonicalInventory.map((member) => member.member_id).filter((id) => !closed.has(id)).sort();
@@ -18078,7 +18681,7 @@ function indexerCatalogFallbackImplementationDigest(cliReleaseDigest) {
18078
18681
  cli_release_digest: indexerDigestSchema.parse(cliReleaseDigest)
18079
18682
  });
18080
18683
  }
18081
- function canonicalUnique6(values, field) {
18684
+ function canonicalUnique7(values, field) {
18082
18685
  const sorted = [...values].sort(compareIndexerCanonicalText);
18083
18686
  if (new Set(sorted).size !== sorted.length) {
18084
18687
  throw new TypeError(`${field} must not contain duplicate identities`);
@@ -18116,7 +18719,7 @@ function assertLocalDeclarations(input) {
18116
18719
  if (!Number.isSafeInteger(declaration.priority) || declaration.priority < 0) {
18117
18720
  throw new TypeError("local partition strategy priority must be a non-negative integer");
18118
18721
  }
18119
- const profiles = canonicalUnique6(declaration.profiles, "local strategy profiles");
18722
+ const profiles = canonicalUnique7(declaration.profiles, "local strategy profiles");
18120
18723
  if (profiles.some((profile) => !input.selectedProfiles.has(profile))) {
18121
18724
  throw new TypeError("local partition strategy references an unselected profile");
18122
18725
  }
@@ -18136,7 +18739,7 @@ function providerImplementationDigest(input) {
18136
18739
  }
18137
18740
  function resolveIndexerPartitionStrategies(input) {
18138
18741
  const indexerId = indexerIdSchema.parse(input.indexer_id);
18139
- const selectedProfiles = canonicalUnique6(input.selected_profile_ids, "selected partition profiles");
18742
+ const selectedProfiles = canonicalUnique7(input.selected_profile_ids, "selected partition profiles");
18140
18743
  const selectedProfileSet = new Set(selectedProfiles);
18141
18744
  const manifest = indexerProviderManifestSchema.parse(input.provider.manifest);
18142
18745
  if (manifest.id !== input.provider.id || manifest.version !== input.provider.version) {
@@ -18276,7 +18879,7 @@ function resolveIndexerPartitionStrategies(input) {
18276
18879
  }
18277
18880
  function validateIndexerPartitionStrategyResolution(valueInput) {
18278
18881
  const value = indexerPartitionStrategyResolutionSchema.parse(valueInput);
18279
- if (canonicalIndexerJson(value.selected_profile_ids) !== canonicalIndexerJson(canonicalUnique6(value.selected_profile_ids, "resolved selected_profile_ids"))) {
18882
+ if (canonicalIndexerJson(value.selected_profile_ids) !== canonicalIndexerJson(canonicalUnique7(value.selected_profile_ids, "resolved selected_profile_ids"))) {
18280
18883
  throw new TypeError("resolved selected_profile_ids are not canonical");
18281
18884
  }
18282
18885
  const expected = [...value.strategies].sort((left, right) => compareIndexerCanonicalText(strategySortKey(left), strategySortKey(right)));
@@ -18483,26 +19086,26 @@ function validateAttemptDigest(attempt) {
18483
19086
  }
18484
19087
  }
18485
19088
  function validateIndexerPartitionConvergenceRecord(value) {
18486
- const record = indexerPartitionConvergenceRecordSchema.parse(value);
18487
- record.attempts.forEach((attempt, index) => {
19089
+ const record3 = indexerPartitionConvergenceRecordSchema.parse(value);
19090
+ record3.attempts.forEach((attempt, index) => {
18488
19091
  validateAttemptDigest(attempt);
18489
19092
  if (attempt.strategy_order !== index) {
18490
19093
  throw new TypeError("partition convergence attempts must use contiguous strategy order");
18491
19094
  }
18492
- const expectedPrevious = index === 0 ? null : record.attempts[index - 1].attempt_digest;
19095
+ const expectedPrevious = index === 0 ? null : record3.attempts[index - 1].attempt_digest;
18493
19096
  if (attempt.previous_attempt_digest !== expectedPrevious) {
18494
19097
  throw new TypeError("partition convergence attempt lineage is invalid");
18495
19098
  }
18496
19099
  });
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";
19100
+ const last = record3.attempts.at(-1);
19101
+ 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
19102
  if (!validDecision)
18500
19103
  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) {
19104
+ const payload = Object.fromEntries(Object.entries(record3).filter(([key]) => key !== "convergence_digest"));
19105
+ if (indexerProtocolDigest(payload) !== record3.convergence_digest) {
18503
19106
  throw new TypeError("partition convergence digest is invalid");
18504
19107
  }
18505
- return record;
19108
+ return record3;
18506
19109
  }
18507
19110
  function convergeIndexerPartitionPlan(input) {
18508
19111
  const strategies = canonicalStrategies(input.authorized_strategies);
@@ -18696,7 +19299,6 @@ function validateIndexerMainRunResult(input) {
18696
19299
  throw new TypeError("main run Result does not match its request/stage/input view");
18697
19300
  }
18698
19301
  let operationResult;
18699
- let authoringAudit = null;
18700
19302
  let artifactDependencySet = null;
18701
19303
  const runEnvelope = buildIndexerRunEnvelope({
18702
19304
  workset: request.workset,
@@ -18730,6 +19332,7 @@ function validateIndexerMainRunResult(input) {
18730
19332
  expected_provider: request.final_authority,
18731
19333
  expected_input_digest: request.execution_request_digest,
18732
19334
  expected_subject_key: input.validation.expected_subject_key,
19335
+ ...input.validation.page_plan?.articles === undefined ? {} : { planned_articles: input.validation.page_plan.articles },
18733
19336
  artifact_policy_eligibility: input.validation.artifact_policy_eligibility,
18734
19337
  allowed_source_roles: input.validation.allowed_source_roles,
18735
19338
  ...input.validation.authorized_evidence_targets === undefined ? {} : {
@@ -18744,7 +19347,6 @@ function validateIndexerMainRunResult(input) {
18744
19347
  if (operationResult.source_role !== request.run_environment.source_role) {
18745
19348
  throw new TypeError("author Result source role does not match the run environment");
18746
19349
  }
18747
- authoringAudit = buildIndexerGeneratedAuthoringAudit(operationResult);
18748
19350
  artifactDependencySet = buildIndexerArtifactDependencySet({
18749
19351
  result: operationResult,
18750
19352
  workset: request.workset,
@@ -18762,7 +19364,6 @@ function validateIndexerMainRunResult(input) {
18762
19364
  request,
18763
19365
  result,
18764
19366
  operation_result: operationResult,
18765
- authoring_audit: authoringAudit,
18766
19367
  artifact_dependency_set: artifactDependencySet,
18767
19368
  run_envelope: runEnvelope
18768
19369
  };
@@ -19232,11 +19833,7 @@ function validateIndexerInspectorResult(input) {
19232
19833
  if (expectedVariants === undefined) {
19233
19834
  throw new TypeError("inspector projection targets an inactive profile");
19234
19835
  }
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
- }
19836
+ assertIndexerInspectorProfileVariants(item.payload, expectedVariants);
19240
19837
  for (const sourceFactRef of item.payload.source_fact_refs) {
19241
19838
  if (!inputFactRefs.has(sourceFactRef)) {
19242
19839
  throw new TypeError("inspector projection references a fact outside its input View");
@@ -19258,6 +19855,15 @@ function validateIndexerInspectorResult(input) {
19258
19855
  }
19259
19856
  return { result, evidence, fact_payloads: result.fact_payloads };
19260
19857
  }
19858
+ function assertIndexerInspectorProfileVariants(projection, expected) {
19859
+ for (const [axis, expectedValue] of Object.entries(expected)) {
19860
+ const observed = projection.profile_variants[axis];
19861
+ if (observed === undefined && projection.status !== "available")
19862
+ continue;
19863
+ if (observed !== expectedValue)
19864
+ throw new TypeError("inspector projection variant drifted from the active Registry profile");
19865
+ }
19866
+ }
19261
19867
  // src/indexerAuthorizedWorksetView.ts
19262
19868
  function isIndexerJson(value, ancestors = new WeakSet) {
19263
19869
  if (value === null || typeof value === "string" || typeof value === "boolean") {
@@ -19338,7 +19944,7 @@ var indexerAuthorizedWorksetViewSchema = exports_external.object({
19338
19944
  addDuplicateIssues(value.projection_input_digests, context, "projection_input_digests");
19339
19945
  addDuplicateIssues(value.items.map((item) => item.ref), context, "items.ref");
19340
19946
  });
19341
- function canonicalUnique7(values, field) {
19947
+ function canonicalUnique8(values, field) {
19342
19948
  const sorted = [...values].sort(compareIndexerCanonicalText);
19343
19949
  if (new Set(sorted).size !== sorted.length) {
19344
19950
  throw new TypeError(`${field} must contain unique values`);
@@ -19358,7 +19964,7 @@ function canonicalItem(value) {
19358
19964
  function canonicalSource(value) {
19359
19965
  const payload = authorizedWorksetViewSourcePayloadSchema.parse({
19360
19966
  ...value,
19361
- input_digests: canonicalUnique7(value.input_digests, "source.input_digests"),
19967
+ input_digests: canonicalUnique8(value.input_digests, "source.input_digests"),
19362
19968
  items: canonicalItems(value.items)
19363
19969
  });
19364
19970
  return indexerAuthorizedWorksetViewSourceSchema.parse({
@@ -19674,7 +20280,7 @@ function buildIndexerAuthorizedWorksetView(input) {
19674
20280
  }
19675
20281
  function validateIndexerAuthorizedWorksetView(value) {
19676
20282
  const view = indexerAuthorizedWorksetViewSchema.parse(value);
19677
- const projectionInputDigests = canonicalUnique7(view.projection_input_digests, "projection_input_digests");
20283
+ const projectionInputDigests = canonicalUnique8(view.projection_input_digests, "projection_input_digests");
19678
20284
  if (projectionInputDigests.some((digest, index) => digest !== view.projection_input_digests[index])) {
19679
20285
  throw new TypeError("projection_input_digests must use canonical ordering");
19680
20286
  }
@@ -23031,7 +23637,7 @@ function compareCoverageDomains(oldRequirement, newRequirement, changes) {
23031
23637
  }
23032
23638
  }
23033
23639
  function exclusionCells(requirement) {
23034
- return new Set((requirement.exclusions ?? []).flatMap((exclusion) => [...targetCellSet2(exclusion.scope.targets)].map((cell) => `${exclusion.id}\x00${cell}`)));
23640
+ return new Set((requirement.exclusions ?? []).flatMap((exclusion) => [...targetCellSet2(exclusion.scope.targets)].map((cell) => `${exclusion.id}\x00${cell}\x00${JSON.stringify([...exclusion.paths ?? []].sort())}`)));
23035
23641
  }
23036
23642
  function questionViewMap(views) {
23037
23643
  return new Map(views.map((view) => [`${view.ref}\x00${view.contractDigest}`, view]));
@@ -23195,6 +23801,14 @@ function compareIndexRequirementContraction(oldRequirement, newRequirement, opti
23195
23801
  throw new TypeError("Requirement comparator cannot replace a requirement identity");
23196
23802
  }
23197
23803
  const changes = [];
23804
+ if (oldRequirement.purpose !== newRequirement.purpose) {
23805
+ addChange(changes, {
23806
+ area: "reader-goals",
23807
+ path: "purpose",
23808
+ relation: "incomparable",
23809
+ detail: "reader purpose changed; its semantic relationship requires the stated user decision"
23810
+ });
23811
+ }
23198
23812
  compareSetArea({
23199
23813
  oldValues: targetCellSet2(oldRequirement.target_scope.targets),
23200
23814
  newValues: targetCellSet2(newRequirement.target_scope.targets),
@@ -23568,6 +24182,7 @@ function normalizeRequirement(requirement) {
23568
24182
  })).sort((left, right) => compareIndexerCanonicalText(left.source_ref, right.source_ref));
23569
24183
  return {
23570
24184
  id: requirement.id,
24185
+ ...requirement.purpose === undefined ? {} : { purpose: requirement.purpose },
23571
24186
  reader_goals: sortedUnique4(requirement.reader_goals, "reader_goals"),
23572
24187
  coverage_domains: Object.fromEntries(Object.entries(requirement.coverage_domains).sort(([left], [right]) => compareIndexerCanonicalText(left, right))),
23573
24188
  ...requirement.questions === undefined ? {} : {
@@ -26735,7 +27350,7 @@ var DIRECT_FACT_KIND_MAPPING = {
26735
27350
  "downstream-callsite": "downstream-callsite",
26736
27351
  "state-transition": "state-transition"
26737
27352
  };
26738
- function record(value) {
27353
+ function record3(value) {
26739
27354
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
26740
27355
  }
26741
27356
  function parserFactMemberKind(fact) {
@@ -26744,7 +27359,7 @@ function parserFactMemberKind(fact) {
26744
27359
  return direct;
26745
27360
  if (fact.denominator !== "symbol")
26746
27361
  return null;
26747
- const symbolKind = record(fact.payload)?.kind;
27362
+ const symbolKind = record3(fact.payload)?.kind;
26748
27363
  return symbolKind === "component" ? "component" : "entry";
26749
27364
  }
26750
27365
  function buildIndexerPartitionInventoryFromParserFactView(value) {
@@ -26843,7 +27458,7 @@ function nodePolarity(node) {
26843
27458
  function nodeVersionRef(node) {
26844
27459
  return indexerDependencyVersionRef({ polarity: nodePolarity(node), node });
26845
27460
  }
26846
- function canonicalUnique8(values) {
27461
+ function canonicalUnique9(values) {
26847
27462
  return [...new Set(values)].sort(compareIndexerCanonicalText);
26848
27463
  }
26849
27464
  function validateImpactInputs(input) {
@@ -26894,7 +27509,7 @@ function refsForCurrentNode(input) {
26894
27509
  section_key: section.section_key
26895
27510
  })));
26896
27511
  return {
26897
- artifactIds: canonicalUnique8(sections.map((section) => section.artifact_id)),
27512
+ artifactIds: canonicalUnique9(sections.map((section) => section.artifact_id)),
26898
27513
  sections
26899
27514
  };
26900
27515
  }
@@ -26902,7 +27517,7 @@ function buildDependencyChanges(input) {
26902
27517
  const previousNodes = new Map([...input.previousView.positive_nodes, ...input.previousView.negative_nodes].map((node) => [node.node_ref, node]));
26903
27518
  const currentNodes = new Map([...input.currentView.positive_nodes, ...input.currentView.negative_nodes].map((node) => [node.node_ref, node]));
26904
27519
  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) => {
27520
+ return canonicalUnique9([...previousNodes.keys(), ...currentNodes.keys()]).flatMap((nodeRef) => {
26906
27521
  const previous = previousNodes.get(nodeRef);
26907
27522
  const current = currentNodes.get(nodeRef);
26908
27523
  const previousRef = previous === undefined ? null : nodeVersionRef(previous);
@@ -26927,7 +27542,7 @@ function buildDependencyChanges(input) {
26927
27542
  change: previous === undefined ? "added" : current === undefined ? "removed" : "changed",
26928
27543
  previous_dependency_ref: previousRef,
26929
27544
  current_dependency_ref: currentRef,
26930
- affected_artifact_ids: canonicalUnique8([
27545
+ affected_artifact_ids: canonicalUnique9([
26931
27546
  ...fromPrevious.artifactIds,
26932
27547
  ...fromCurrent.artifactIds
26933
27548
  ]),
@@ -26974,14 +27589,14 @@ function buildIndexerIncrementalImpactReport(input) {
26974
27589
  }
26975
27590
  const artifacts = validated.previousSet.artifacts.map((artifact) => {
26976
27591
  const sections = artifact.sections.map((section) => {
26977
- const changed2 = canonicalUnique8(changedBySection.get(`${artifact.artifact_id}\x00${section.section_key}`) ?? []);
27592
+ const changed2 = canonicalUnique9(changedBySection.get(`${artifact.artifact_id}\x00${section.section_key}`) ?? []);
26978
27593
  return {
26979
27594
  section_key: section.section_key,
26980
27595
  state: changed2.length === 0 ? "current" : "stale",
26981
27596
  changed_node_refs: changed2
26982
27597
  };
26983
27598
  });
26984
- const changed = canonicalUnique8(sections.flatMap((section) => section.changed_node_refs));
27599
+ const changed = canonicalUnique9(sections.flatMap((section) => section.changed_node_refs));
26985
27600
  return {
26986
27601
  artifact_id: artifact.artifact_id,
26987
27602
  artifact_kind: artifact.artifact_kind,
@@ -27352,11 +27967,11 @@ var indexerMainAcceptedRecordSchema = exports_external.object({
27352
27967
  acceptance_digest: indexerDigestSchema
27353
27968
  }).strict();
27354
27969
  function validateIndexerMainAcceptedRecord(value) {
27355
- const record2 = indexerMainAcceptedRecordSchema.parse(value);
27356
- if (record2.stage === "author" !== (record2.artifact_dependency_set_digest !== null)) {
27970
+ const record4 = indexerMainAcceptedRecordSchema.parse(value);
27971
+ if (record4.stage === "author" !== (record4.artifact_dependency_set_digest !== null)) {
27357
27972
  throw new TypeError("accepted author records require an Artifact dependency set and partition records forbid one");
27358
27973
  }
27359
- return record2;
27974
+ return record4;
27360
27975
  }
27361
27976
  function buildIndexerMainAcceptedRecord(input) {
27362
27977
  const payload2 = {
@@ -27441,41 +28056,41 @@ var indexerMainWorksetStatusSchema = exports_external.object({
27441
28056
  function observeIndexerMainWorksetState(input) {
27442
28057
  const currentSet = validateIndexerMainWorksetSet(input.workset_set);
27443
28058
  const records = input.records.map((value) => {
27444
- const record2 = indexerMainStateRecordSchema.parse(value);
27445
- if (record2.state === "accepted") {
27446
- const { state: _state, ...accepted2 } = record2;
28059
+ const record4 = indexerMainStateRecordSchema.parse(value);
28060
+ if (record4.state === "accepted") {
28061
+ const { state: _state, ...accepted2 } = record4;
27447
28062
  validateIndexerMainAcceptedRecord(accepted2);
27448
28063
  }
27449
- return record2;
28064
+ return record4;
27450
28065
  });
27451
- if (new Set(records.map((record2) => record2.workset_digest)).size !== records.length) {
28066
+ if (new Set(records.map((record4) => record4.workset_digest)).size !== records.length) {
27452
28067
  throw new TypeError("main workset state contains duplicate workset records");
27453
28068
  }
27454
- const byDigest = new Map(records.map((record2) => [record2.workset_digest, record2]));
28069
+ const byDigest = new Map(records.map((record4) => [record4.workset_digest, record4]));
27455
28070
  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);
28071
+ for (const record4 of records) {
28072
+ const item = currentItems.get(record4.workset_digest);
27458
28073
  if (item === undefined) {
27459
28074
  throw new TypeError("main workset state contains a record outside the current set");
27460
28075
  }
27461
- if (record2.state === "accepted") {
28076
+ if (record4.state === "accepted") {
27462
28077
  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
28078
+ protocol: record4.protocol,
28079
+ workset_digest: record4.workset_digest,
28080
+ stage: record4.stage,
28081
+ execution_request_digest: record4.execution_request_digest,
28082
+ result_digest: record4.result_digest,
28083
+ receipt_digest: record4.receipt_digest,
28084
+ run_envelope_digest: record4.run_envelope_digest,
28085
+ artifact_dependency_set_digest: record4.artifact_dependency_set_digest
27471
28086
  };
27472
- if (record2.stage !== item.stage || indexerProtocolDigest(payload3) !== record2.acceptance_digest) {
28087
+ if (record4.stage !== item.stage || indexerProtocolDigest(payload3) !== record4.acceptance_digest) {
27473
28088
  throw new TypeError("accepted main result record is stale or has an invalid digest");
27474
28089
  }
27475
28090
  }
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])) {
28091
+ if (record4.state === "failed") {
28092
+ const dependencies = [...record4.dependency_digests].sort(compareIndexerCanonicalText);
28093
+ if (new Set(dependencies).size !== dependencies.length || dependencies.some((digest, index) => digest !== record4.dependency_digests[index])) {
27479
28094
  throw new TypeError("failed main result dependencies must be unique and canonical");
27480
28095
  }
27481
28096
  }
@@ -27488,22 +28103,22 @@ function observeIndexerMainWorksetState(input) {
27488
28103
  }
27489
28104
  }));
27490
28105
  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
28106
+ pending: joined.filter(({ record: record4 }) => record4.state === "pending" || record4.state === "running").length,
28107
+ accepted: joined.filter(({ record: record4 }) => record4.state === "accepted").length,
28108
+ failed: joined.filter(({ record: record4 }) => record4.state === "failed").length,
28109
+ stale: joined.filter(({ record: record4 }) => record4.state === "stale").length
27495
28110
  };
27496
- const nextRefs = joined.filter(({ record: record2 }) => record2.state !== "accepted" && record2.state !== "running").map(({ item, record: record2 }) => ({
28111
+ const nextRefs = joined.filter(({ record: record4 }) => record4.state !== "accepted" && record4.state !== "running").map(({ item, record: record4 }) => ({
27497
28112
  ...item,
27498
- state: record2.state
28113
+ state: record4.state
27499
28114
  }));
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
28115
+ const accepted = joined.filter((item) => item.record.state === "accepted").map(({ record: record4 }) => ({
28116
+ workset_digest: record4.workset_digest,
28117
+ execution_request_digest: record4.execution_request_digest,
28118
+ result_digest: record4.result_digest,
28119
+ receipt_digest: record4.receipt_digest,
28120
+ run_envelope_digest: record4.run_envelope_digest,
28121
+ artifact_dependency_set_digest: record4.artifact_dependency_set_digest
27507
28122
  })).sort((left, right) => compareIndexerCanonicalText(left.workset_digest, right.workset_digest));
27508
28123
  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
28124
  const payload2 = {
@@ -27648,7 +28263,111 @@ function validateIndexerAgentStepInput(value) {
27648
28263
  }
27649
28264
  return input;
27650
28265
  }
28266
+ // src/knowledgeMap.ts
28267
+ var knowledgeMapEntrySchema = exports_external.object({
28268
+ key: exports_external.string().min(1),
28269
+ parent: exports_external.string().min(1).nullable(),
28270
+ title: exports_external.string().min(1),
28271
+ order: exports_external.number().finite().default(0),
28272
+ target: exports_external.object({
28273
+ artifact_ref: exports_external.string().min(1),
28274
+ section_key: exports_external.string().min(1).optional()
28275
+ }).strict().optional()
28276
+ }).strict();
28277
+ var knowledgeMapUpdateSchema = exports_external.object({
28278
+ expected_revision: exports_external.string().nullable(),
28279
+ upsert: exports_external.array(knowledgeMapEntrySchema).default([]),
28280
+ remove: exports_external.array(exports_external.string().min(1)).default([])
28281
+ }).strict();
28282
+ var knowledgeMapSchema = exports_external.object({
28283
+ protocol: exports_external.literal("context.knowledge-map/v1"),
28284
+ revision: exports_external.string().min(1),
28285
+ entries: exports_external.array(knowledgeMapEntrySchema)
28286
+ }).strict();
28287
+ function validateEntries(entries) {
28288
+ const indexed = new Map(entries.map((entry) => [entry.key, entry]));
28289
+ if (indexed.size !== entries.length)
28290
+ throw new TypeError("knowledge-map entries must have unique keys");
28291
+ for (const entry of entries) {
28292
+ const visited = new Set;
28293
+ let current = entry;
28294
+ while (current !== undefined) {
28295
+ if (visited.has(current.key))
28296
+ throw new TypeError("knowledge map contains a parent cycle");
28297
+ visited.add(current.key);
28298
+ if (current.parent === null)
28299
+ break;
28300
+ const parent = indexed.get(current.parent);
28301
+ if (parent === undefined)
28302
+ throw new TypeError(`knowledge-map entry ${current.key} has an unknown parent`);
28303
+ current = parent;
28304
+ }
28305
+ }
28306
+ }
28307
+ function validateKnowledgeMap(value) {
28308
+ const result = knowledgeMapSchema.parse(value);
28309
+ validateEntries(result.entries);
28310
+ const { revision, ...payload2 } = result;
28311
+ if (indexerProtocolDigest(payload2) !== revision)
28312
+ throw new TypeError("knowledge map revision does not match its content");
28313
+ return result;
28314
+ }
28315
+ function updateKnowledgeMap(current, value) {
28316
+ const update = knowledgeMapUpdateSchema.parse(value);
28317
+ if ((current?.revision ?? null) !== update.expected_revision)
28318
+ throw new TypeError("knowledge map changed; reread the current structure before applying this edit");
28319
+ const keys = update.upsert.map((entry) => entry.key);
28320
+ if (new Set(keys).size !== keys.length || new Set(update.remove).size !== update.remove.length || keys.some((key) => update.remove.includes(key))) {
28321
+ throw new TypeError("knowledge map update contains conflicting entry identities");
28322
+ }
28323
+ const entries = new Map(current?.entries.map((entry) => [entry.key, entry]) ?? []);
28324
+ for (const key of update.remove)
28325
+ entries.delete(key);
28326
+ for (const entry of update.upsert)
28327
+ entries.set(entry.key, entry);
28328
+ const payload2 = {
28329
+ protocol: "context.knowledge-map/v1",
28330
+ entries: [...entries.values()].sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0)
28331
+ };
28332
+ validateEntries(payload2.entries);
28333
+ return { ...payload2, revision: indexerProtocolDigest(payload2) };
28334
+ }
28335
+ function projectKnowledgeMap(structure, targets) {
28336
+ const children = new Map;
28337
+ for (const entry of structure.entries)
28338
+ children.set(entry.parent, [...children.get(entry.parent) ?? [], entry]);
28339
+ const warnings = [];
28340
+ function project(parent) {
28341
+ return (children.get(parent) ?? []).sort((a, b) => a.order - b.order || a.key.localeCompare(b.key)).flatMap((entry) => {
28342
+ const descendants = project(entry.key);
28343
+ const identity2 = entry.target === undefined ? undefined : knowledgeMapTargetKey(entry.target);
28344
+ const href = identity2 === undefined ? undefined : targets.get(identity2);
28345
+ if (identity2 !== undefined && href === undefined)
28346
+ warnings.push({ entry: entry.key, code: "knowledge-map-target-unavailable", target: identity2 });
28347
+ if (href === undefined && descendants.length === 0)
28348
+ return [];
28349
+ return [{ key: entry.key, title: entry.title, ...href === undefined ? {} : { href }, children: descendants }];
28350
+ });
28351
+ }
28352
+ return { entries: project(null), warnings };
28353
+ }
28354
+ function knowledgeMapTargetKey(target) {
28355
+ return target.section_key === undefined ? target.artifact_ref : `${target.artifact_ref}#${encodeURIComponent(target.section_key)}`;
28356
+ }
28357
+
27651
28358
  // src/indexerSemanticInput.ts
28359
+ var catalogProviderSelectionSchema = exports_external.object({
28360
+ id: indexerIdSchema,
28361
+ role: exports_external.enum(["primary", "extension"]).default("primary"),
28362
+ catalog_skill: indexerIdSchema,
28363
+ config: exports_external.record(indexerJsonSchema).optional()
28364
+ }).strict();
28365
+ var providerSelectionEntrySchema = indexerRegistryEntryInputSchema.extend({
28366
+ providers: exports_external.array(exports_external.union([
28367
+ catalogProviderSelectionSchema,
28368
+ indexerRegistryEntryInputSchema.shape.providers.element
28369
+ ])).min(1)
28370
+ });
27652
28371
  var providerObservationSchema = exports_external.object({
27653
28372
  skill: exports_external.string().min(1),
27654
28373
  version: exports_external.string().min(1).nullable(),
@@ -27662,7 +28381,7 @@ var providerObservationSchema = exports_external.object({
27662
28381
  var indexerProviderSelectionSemanticInputSchema = exports_external.object({
27663
28382
  stage: exports_external.literal("provider-selection"),
27664
28383
  host_visible_skills: exports_external.array(providerObservationSchema).default([]),
27665
- indexers: exports_external.array(indexerRegistryEntrySchema).min(1)
28384
+ indexers: exports_external.array(providerSelectionEntrySchema).min(1)
27666
28385
  }).strict();
27667
28386
  var indexerProviderResolutionSemanticInputSchema = exports_external.object({
27668
28387
  stage: exports_external.literal("provider-resolution"),
@@ -27689,6 +28408,12 @@ var partitionGroupSchema2 = exports_external.object({
27689
28408
  key: exports_external.string().min(1),
27690
28409
  title: exports_external.string().min(1),
27691
28410
  reader_task: exports_external.string().min(1),
28411
+ artifact_intent: exports_external.string().min(1).optional(),
28412
+ template_id: exports_external.string().min(1).optional(),
28413
+ articles: exports_external.array(indexerArticlePlanSchema).min(1).optional(),
28414
+ priority: exports_external.number().int().nonnegative().optional(),
28415
+ delivery_boundary: exports_external.boolean().optional(),
28416
+ ready_for_author: exports_external.boolean().optional(),
27692
28417
  subject: subjectChoiceSchema,
27693
28418
  subject_intent: exports_external.enum(["primary", "enrich-or-independent"]),
27694
28419
  members: exports_external.array(exports_external.string().min(1)).min(1),
@@ -27741,18 +28466,38 @@ var indexerPartitionSemanticInputSchema = exports_external.union([
27741
28466
  function validateIndexerPartitionSemanticInput(value) {
27742
28467
  return indexerPartitionSemanticInputSchema.parse(value);
27743
28468
  }
28469
+ var authorVisualSchema = exports_external.object({
28470
+ resource: exports_external.string().min(1),
28471
+ also_read: exports_external.array(exports_external.string().min(1)).optional(),
28472
+ context: exports_external.array(exports_external.string()).default([]),
28473
+ requirements: exports_external.string().default(""),
28474
+ disposition: exports_external.enum(["converted", "retained"]),
28475
+ format: exports_external.enum(["mermaid", "table", "original"]),
28476
+ markdown: exports_external.string().optional(),
28477
+ reason: exports_external.string().optional()
28478
+ }).strict();
27744
28479
  var authorSectionSchema = exports_external.object({
27745
28480
  key: exports_external.string().min(1),
27746
28481
  heading: exports_external.string().min(1),
28482
+ visuals: exports_external.array(authorVisualSchema).optional(),
27747
28483
  markdown: exports_external.string().min(1),
27748
- source_items: exports_external.array(exports_external.string().min(1)).min(1),
28484
+ source_items: exports_external.array(exports_external.string().min(1)).default([]),
27749
28485
  facts: exports_external.array(exports_external.string().min(1)).default([]),
27750
28486
  answers: exports_external.array(exports_external.string().min(1)).default([])
27751
28487
  }).strict();
28488
+ var authorTemplateVariablesSchema = exports_external.record(exports_external.union([
28489
+ exports_external.string(),
28490
+ exports_external.object({
28491
+ value: exports_external.string(),
28492
+ source_items: exports_external.array(exports_external.string().min(1)).default([]),
28493
+ facts: exports_external.array(exports_external.string().min(1)).default([])
28494
+ }).strict()
28495
+ ]));
27752
28496
  var authorMemberDispositionSchema = exports_external.object({
27753
28497
  item: exports_external.string().min(1),
27754
28498
  state: exports_external.enum(["covered", "catalog-only", "unsupported"]),
27755
28499
  section: exports_external.string().min(1).optional(),
28500
+ article: indexerArticleKeySchema.optional(),
27756
28501
  reason_code: exports_external.string().min(1).optional()
27757
28502
  }).strict();
27758
28503
  var authorMaterialGapSchema = exports_external.object({
@@ -27764,11 +28509,24 @@ var authorDiagnosticSchema = exports_external.object({
27764
28509
  message: exports_external.string().min(1),
27765
28510
  target: exports_external.string().min(1).optional()
27766
28511
  }).strict();
27767
- var indexerAuthorSemanticInputSchema = exports_external.object({
28512
+ var authorInputBaseSchema = exports_external.object({
27768
28513
  stage: exports_external.literal("author"),
27769
28514
  group_key: exports_external.string().min(1),
27770
28515
  outcome: exports_external.enum(["publish", "catalog-only", "request-material", "unsupported"]),
28516
+ articles: exports_external.array(exports_external.object({
28517
+ key: indexerArticleKeySchema,
28518
+ title: exports_external.string().min(1),
28519
+ summary: exports_external.string().min(1),
28520
+ artifact_intent: exports_external.string().min(1).optional(),
28521
+ template_variables: authorTemplateVariablesSchema.optional(),
28522
+ sections: exports_external.array(authorSectionSchema).min(1)
28523
+ }).strict()).min(1).optional(),
27771
28524
  artifact_intent: exports_external.string().min(1).optional(),
28525
+ template_variables: authorTemplateVariablesSchema.optional(),
28526
+ example_candidates: exports_external.array(exports_external.object({
28527
+ scenario_key: indexerIdSchema,
28528
+ source_item: exports_external.string().min(1)
28529
+ }).strict()).optional(),
27772
28530
  policy: exports_external.string().min(1).optional(),
27773
28531
  target_resolutions: exports_external.array(exports_external.object({
27774
28532
  target: exports_external.string().min(1),
@@ -27778,32 +28536,36 @@ var indexerAuthorSemanticInputSchema = exports_external.object({
27778
28536
  title: exports_external.string().min(1).optional(),
27779
28537
  summary: exports_external.string().min(1).optional(),
27780
28538
  sections: exports_external.array(authorSectionSchema).default([]),
27781
- member_dispositions: exports_external.array(authorMemberDispositionSchema),
28539
+ member_dispositions: exports_external.array(exports_external.union([
28540
+ authorMemberDispositionSchema,
28541
+ authorMemberDispositionSchema.omit({ item: true }).extend({ items: exports_external.array(exports_external.string().min(1)).min(1) }).strict()
28542
+ ])).transform((entries) => entries.flatMap((entry) => {
28543
+ if ("item" in entry)
28544
+ return [entry];
28545
+ const { items, ...disposition } = entry;
28546
+ return items.map((item) => ({ item, ...disposition }));
28547
+ })),
27782
28548
  material_gaps: exports_external.array(authorMaterialGapSchema).default([]),
27783
28549
  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
- });
28550
+ }).strict();
28551
+ var indexerAuthorSemanticInputSchema = exports_external.union([
28552
+ authorInputBaseSchema.extend({
28553
+ outcome: exports_external.literal("publish"),
28554
+ title: exports_external.string().min(1),
28555
+ summary: exports_external.string().min(1),
28556
+ sections: exports_external.array(authorSectionSchema).min(1)
28557
+ }),
28558
+ authorInputBaseSchema.extend({
28559
+ outcome: exports_external.literal("publish"),
28560
+ articles: authorInputBaseSchema.shape.articles.unwrap(),
28561
+ title: exports_external.string().optional(),
28562
+ summary: exports_external.string().optional(),
28563
+ sections: exports_external.array(authorSectionSchema).max(0).default([])
28564
+ }),
28565
+ authorInputBaseSchema.extend({ outcome: exports_external.literal("catalog-only") }),
28566
+ authorInputBaseSchema.extend({ outcome: exports_external.literal("request-material") }),
28567
+ authorInputBaseSchema.extend({ outcome: exports_external.literal("unsupported") })
28568
+ ]);
27807
28569
  var indexerPartitionBatchSemanticInputSchema = exports_external.object({
27808
28570
  stage: exports_external.literal("partition"),
27809
28571
  results: exports_external.array(exports_external.object({
@@ -27846,10 +28608,11 @@ var indexerMainBatchSubmissionEnvelopeSchema = exports_external.object({
27846
28608
  var postAuthorSectionSchema = exports_external.object({
27847
28609
  key: exports_external.string().min(1),
27848
28610
  heading: exports_external.string().min(1),
28611
+ visuals: exports_external.array(authorVisualSchema).optional(),
27849
28612
  markdown: exports_external.string().min(1),
27850
28613
  source_refs: exports_external.array(exports_external.string().min(1)).min(1)
27851
28614
  }).strict();
27852
- var indexerPostAuthorSemanticInputSchema = exports_external.object({
28615
+ var postAuthorInputBaseSchema = exports_external.object({
27853
28616
  stage: exports_external.literal("post-author"),
27854
28617
  outcome: exports_external.enum(["complete", "failed"]),
27855
28618
  proposals: exports_external.array(exports_external.object({
@@ -27860,15 +28623,14 @@ var indexerPostAuthorSemanticInputSchema = exports_external.object({
27860
28623
  sections: exports_external.array(postAuthorSectionSchema).min(1)
27861
28624
  }).strict()).default([]),
27862
28625
  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
- });
28626
+ }).strict();
28627
+ var indexerPostAuthorSemanticInputSchema = exports_external.discriminatedUnion("outcome", [
28628
+ postAuthorInputBaseSchema.extend({ outcome: exports_external.literal("complete") }),
28629
+ postAuthorInputBaseSchema.extend({
28630
+ outcome: exports_external.literal("failed"),
28631
+ diagnostics: exports_external.array(authorDiagnosticSchema).min(1)
28632
+ })
28633
+ ]);
27872
28634
  var indexerPostAuthorBatchSemanticInputSchema = exports_external.object({
27873
28635
  stage: exports_external.literal("post-author"),
27874
28636
  results: exports_external.array(exports_external.object({
@@ -27885,20 +28647,21 @@ var indexerPostAuthorBatchSemanticInputSchema = exports_external.object({
27885
28647
  });
27886
28648
  }
27887
28649
  });
27888
- var indexerStructureReviewInputSchema = exports_external.object({
28650
+ var structureReviewBaseSchema = exports_external.object({
27889
28651
  stage: exports_external.literal("structure-review"),
27890
- decision: exports_external.enum(["approved", "request-adjustment"]),
28652
+ knowledge_map: knowledgeMapUpdateSchema.optional(),
28653
+ decision: exports_external.enum(["approved", "exclude-obsolete", "request-adjustment"]),
27891
28654
  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({
28655
+ }).strict();
28656
+ var indexerStructureReviewInputSchema = exports_external.discriminatedUnion("decision", [
28657
+ structureReviewBaseSchema.extend({ decision: exports_external.literal("approved") }),
28658
+ structureReviewBaseSchema.extend({ decision: exports_external.literal("exclude-obsolete") }),
28659
+ structureReviewBaseSchema.extend({
28660
+ decision: exports_external.literal("request-adjustment"),
28661
+ feedback: exports_external.string().min(1)
28662
+ })
28663
+ ]);
28664
+ var layoutConfirmationBaseSchema = exports_external.object({
27902
28665
  stage: exports_external.literal("layout-confirmation"),
27903
28666
  decision: exports_external.enum(["approved", "rejected"]),
27904
28667
  feedback: exports_external.string().min(1).optional(),
@@ -27906,23 +28669,57 @@ var indexerLayoutConfirmationInputSchema = exports_external.object({
27906
28669
  artifact_ref: exports_external.string().min(1),
27907
28670
  output_path: exports_external.string().min(1)
27908
28671
  }).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
- });
28672
+ }).strict();
28673
+ var indexerLayoutConfirmationInputSchema = exports_external.discriminatedUnion("decision", [
28674
+ layoutConfirmationBaseSchema.extend({ decision: exports_external.literal("approved") }),
28675
+ layoutConfirmationBaseSchema.omit({ paths: true }).extend({
28676
+ decision: exports_external.literal("rejected"),
28677
+ feedback: exports_external.string().min(1)
28678
+ })
28679
+ ]);
28680
+ var approvedRevisionSemanticInputSchema = exports_external.union([
28681
+ exports_external.object({ stage: exports_external.literal("approved-revision"), markdown: exports_external.string().min(1) }).strict(),
28682
+ exports_external.object({
28683
+ stage: exports_external.literal("approved-revision"),
28684
+ sections: exports_external.array(exports_external.object({
28685
+ section_id: exports_external.string().min(1),
28686
+ content: exports_external.array(exports_external.union([
28687
+ exports_external.object({ markdown: exports_external.string() }).strict(),
28688
+ exports_external.object({ program: exports_external.string().min(1) }).strict()
28689
+ ])).min(1)
28690
+ }).strict()).min(1)
28691
+ }).strict()
28692
+ ]);
28693
+ var sourceUpdateSemanticInputSchema = exports_external.object({
28694
+ stage: exports_external.literal("source-update"),
28695
+ decisions: exports_external.array(exports_external.object({
28696
+ path: exports_external.string().min(1),
28697
+ instruction: exports_external.string().trim().min(1).optional(),
28698
+ supporting_sources: exports_external.array(exports_external.string().min(1)).min(1).optional()
28699
+ }).strict()),
28700
+ scope_summary: exports_external.string().trim().min(1),
28701
+ new_topics: exports_external.array(exports_external.object({
28702
+ path: exports_external.string().trim().min(1),
28703
+ title: exports_external.string().trim().min(1),
28704
+ source_refs: exports_external.array(exports_external.string().min(1)).min(1),
28705
+ instruction: exports_external.string().trim().min(1)
28706
+ }).strict())
28707
+ }).strict();
28708
+ var indexerCurrentActionInputDefinitions = {
28709
+ sourceUpdate: sourceUpdateSemanticInputSchema,
28710
+ approvedRevision: approvedRevisionSemanticInputSchema,
28711
+ providerSelection: indexerProviderSelectionSemanticInputSchema,
28712
+ providerResolution: indexerProviderResolutionSemanticInputSchema,
28713
+ providerProgramAuthorization: indexerProviderProgramAuthorizationSemanticInputSchema,
28714
+ partitionBatch: indexerPartitionBatchSemanticInputSchema,
28715
+ authorBatch: indexerAuthorBatchSemanticInputSchema,
28716
+ postAuthor: indexerPostAuthorBatchSemanticInputSchema,
28717
+ structureReview: indexerStructureReviewInputSchema,
28718
+ layoutConfirmation: indexerLayoutConfirmationInputSchema
28719
+ };
27925
28720
  var indexerCurrentActionInputSchema = exports_external.union([
28721
+ sourceUpdateSemanticInputSchema,
28722
+ approvedRevisionSemanticInputSchema,
27926
28723
  indexerProviderSelectionSemanticInputSchema,
27927
28724
  indexerProviderResolutionSemanticInputSchema,
27928
28725
  indexerProviderProgramAuthorizationSemanticInputSchema,
@@ -27941,128 +28738,6 @@ function parseIndexerCurrentActionSubmission(value) {
27941
28738
  }
27942
28739
  return validateIndexerCurrentActionInput(value);
27943
28740
  }
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
28741
  // src/indexerExampleIdentityAudit.ts
28067
28742
  var collisionSchema = exports_external.object({
28068
28743
  example_ref: indexerCanonicalRefSchema,
@@ -28777,26 +29452,26 @@ function fallbackStrategy(input) {
28777
29452
  return attempt;
28778
29453
  }
28779
29454
  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) {
29455
+ const record4 = indexerCatalogFallbackRecordSchema.parse(value);
29456
+ const payload2 = Object.fromEntries(Object.entries(record4).filter(([key]) => key !== "fallback_digest"));
29457
+ if (indexerProtocolDigest(payload2) !== record4.fallback_digest) {
28783
29458
  throw new TypeError("catalog fallback digest is invalid");
28784
29459
  }
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) => {
29460
+ const planPayload2 = Object.fromEntries(Object.entries(record4.partition_plan).filter(([key]) => key !== "canonical_hash"));
29461
+ const group = record4.partition_plan.groups[0];
29462
+ const catalogMembers = [...record4.catalog_block.member_ids].sort(compareIndexerCanonicalText);
29463
+ const ownedMembers2 = record4.partition_plan.member_dispositions.map((disposition) => {
28789
29464
  if (disposition.inventory_disposition !== "owned" || disposition.group_key !== "catalog-root") {
28790
29465
  throw new TypeError("catalog fallback members must all belong to catalog-root");
28791
29466
  }
28792
29467
  return disposition.member_id;
28793
29468
  });
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) {
29469
+ 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({
29470
+ member_ids: record4.catalog_block.member_ids
29471
+ }) || 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
29472
  throw new TypeError("catalog fallback single-parent projection is inconsistent");
28798
29473
  }
28799
- return record2;
29474
+ return record4;
28800
29475
  }
28801
29476
  function buildIndexerCatalogFallback(input) {
28802
29477
  const convergence = validateIndexerPartitionConvergenceRecord(input.convergence);
@@ -29149,7 +29824,7 @@ var fanOutAuditPayloadSchema = exports_external.object({
29149
29824
  var indexerProjectedArtifactFanOutAuditSchema = fanOutAuditPayloadSchema.extend({
29150
29825
  audit_digest: indexerDigestSchema
29151
29826
  }).strict();
29152
- function auditPayload2(audit) {
29827
+ function auditPayload(audit) {
29153
29828
  const { audit_digest: _digest, ...payload3 } = audit;
29154
29829
  return payload3;
29155
29830
  }
@@ -29351,7 +30026,7 @@ function auditIndexerProjectedArtifactFanOut(input) {
29351
30026
  }
29352
30027
  function validateIndexerProjectedArtifactFanOutAudit(value) {
29353
30028
  const audit = indexerProjectedArtifactFanOutAuditSchema.parse(value);
29354
- if (indexerProtocolDigest(auditPayload2(audit)) !== audit.audit_digest) {
30029
+ if (indexerProtocolDigest(auditPayload(audit)) !== audit.audit_digest) {
29355
30030
  throw new TypeError("projected Artifact fan-out audit digest is invalid");
29356
30031
  }
29357
30032
  const expectedState = stateForCount(audit.summary.unassigned_projected_artifact_count);
@@ -29708,7 +30383,8 @@ var layoutProposalPayloadSchema = exports_external.object({
29708
30383
  node_ref: indexerCanonicalRefSchema,
29709
30384
  subject_key: indexerSubjectKeySchema
29710
30385
  }).strict(),
29711
- artifacts: exports_external.array(layoutArtifactSchema)
30386
+ artifacts: exports_external.array(layoutArtifactSchema),
30387
+ delivery_artifact_ids: exports_external.array(exports_external.string().min(1)).min(1).optional()
29712
30388
  }).strict();
29713
30389
  var indexerLayoutProposalSchema = layoutProposalPayloadSchema.extend({
29714
30390
  proposal_digest: indexerDigestSchema
@@ -29746,7 +30422,7 @@ function indexerLayoutSectionRef(currentArtifactRef, sectionIdentityRef) {
29746
30422
  section_identity_ref: sectionIdentityRef
29747
30423
  })}`;
29748
30424
  }
29749
- function viewRef(currentArtifactRef, collection) {
30425
+ function indexerLayoutViewRef(currentArtifactRef, collection) {
29750
30426
  return `view:artifact:${indexerProtocolDigest({
29751
30427
  protocol: "context.indexer.internal-view-identity/v1",
29752
30428
  artifact_ref: currentArtifactRef,
@@ -29770,11 +30446,12 @@ function outputPath(input) {
29770
30446
  const suffix = input.primary ? "" : input.duplicate_kind ? `-${readerPathSlug(input.artifact.artifact_kind)}-${readerPathSlug(input.artifact.artifact_id)}` : `-${readerPathSlug(input.artifact.artifact_kind)}`;
29771
30447
  return `knowledge/${input.collection}/${namespace}/${subject}${suffix}.md`;
29772
30448
  }
29773
- function structuredSections(artifact, facts) {
30449
+ function structuredSections(artifact, facts, render_cache) {
29774
30450
  return artifact.sections.map((section) => {
29775
30451
  const contentBlocks = materializeIndexerStructuredContent({
29776
30452
  blocks: section.blocks,
29777
- facts
30453
+ facts,
30454
+ render_cache
29778
30455
  });
29779
30456
  const evidenceRefs = [...new Set(contentBlocks.flatMap((block) => block.evidence_refs))].sort(compareIndexerCanonicalText);
29780
30457
  return {
@@ -29885,7 +30562,7 @@ function resolveIndexerLayout(input) {
29885
30562
  if (bundleEntry === undefined || bundleEntry.artifact_kind !== artifact.artifact_kind) {
29886
30563
  throw new TypeError(`Artifact ${artifact.artifact_id} is absent from its closed Bundle`);
29887
30564
  }
29888
- const sections = artifact.representation === "sections" ? structuredSections(artifact, result.facts) : (() => {
30565
+ const sections = artifact.representation === "sections" ? structuredSections(artifact, result.facts, input.render_cache) : (() => {
29889
30566
  const rendered = renderedById.get(artifact.artifact_id);
29890
30567
  if (rendered === undefined) {
29891
30568
  throw new TypeError(`template Artifact ${artifact.artifact_id} must be rendered before layout`);
@@ -29921,7 +30598,7 @@ function resolveIndexerLayout(input) {
29921
30598
  node_ref: nodeRef,
29922
30599
  artifact_id: artifact.artifact_id,
29923
30600
  artifact_kind: artifact.artifact_kind,
29924
- internal_view_ref: viewRef(currentArtifactRef, collection),
30601
+ internal_view_ref: indexerLayoutViewRef(currentArtifactRef, collection),
29925
30602
  collection,
29926
30603
  output_path: outputPath({
29927
30604
  collection,
@@ -29964,6 +30641,13 @@ function resolveIndexerLayout(input) {
29964
30641
  if (new Set(sectionIdentities).size !== sectionIdentities.length) {
29965
30642
  throw new TypeError("layout resolver produced colliding logical Section identities");
29966
30643
  }
30644
+ if (input.delivery_artifact_ids !== undefined) {
30645
+ const selected = new Set(input.delivery_artifact_ids);
30646
+ const available = new Set(artifacts.map((artifact) => artifact.artifact_id));
30647
+ if (selected.size !== input.delivery_artifact_ids.length || selected.size === 0 || [...selected].some((id) => !available.has(id))) {
30648
+ throw new TypeError("delivery layout requires unique, available Artifact identities");
30649
+ }
30650
+ }
29967
30651
  const payload3 = layoutProposalPayloadSchema.parse({
29968
30652
  protocol: "context.indexer.layout-proposal/v1",
29969
30653
  indexer_id: result.indexer_id,
@@ -29979,7 +30663,10 @@ function resolveIndexerLayout(input) {
29979
30663
  node_ref: nodeRef,
29980
30664
  subject_key: result.logical_unit.subject_key
29981
30665
  },
29982
- artifacts
30666
+ artifacts: input.delivery_artifact_ids === undefined ? artifacts : artifacts.filter((artifact) => input.delivery_artifact_ids.includes(artifact.artifact_id)),
30667
+ ...input.delivery_artifact_ids === undefined ? {} : {
30668
+ delivery_artifact_ids: [...input.delivery_artifact_ids].sort(compareIndexerCanonicalText)
30669
+ }
29983
30670
  });
29984
30671
  return indexerLayoutProposalSchema.parse({
29985
30672
  ...payload3,
@@ -29990,12 +30677,14 @@ function validateIndexerLayoutProposal(input) {
29990
30677
  const proposal = indexerLayoutProposalSchema.parse(input.proposal);
29991
30678
  const expected = resolveIndexerLayout({
29992
30679
  artifact_result: input.artifact_result,
30680
+ render_cache: input.render_cache,
29993
30681
  post_author_envelope: input.post_author_envelope,
29994
30682
  profile: proposal.profile,
29995
30683
  profile_contract: input.profile_contract,
29996
30684
  operator_contract: input.operator_contract,
29997
30685
  subject_key_schema_set: input.subject_key_schema_set,
29998
30686
  shared_artifact_fingerprint: proposal.shared_artifact_fingerprint,
30687
+ delivery_artifact_ids: proposal.delivery_artifact_ids,
29999
30688
  ...input.rendered_artifacts === undefined ? {} : { rendered_artifacts: input.rendered_artifacts }
30000
30689
  });
30001
30690
  if (canonicalIndexerJson(expected) !== canonicalIndexerJson(proposal)) {
@@ -30032,7 +30721,7 @@ function validateProposalDigest(value) {
30032
30721
  for (const artifact of proposal.artifacts) {
30033
30722
  if (artifact.purpose === "semantic-split") {
30034
30723
  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) {
30724
+ 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
30725
  throw new TypeError("semantic-split layout Artifact has invalid parent lineage");
30037
30726
  }
30038
30727
  } else if (artifact.split_of_artifact_ref !== null || artifact.split_boundary !== null) {
@@ -30804,21 +31493,7 @@ function normalizedReaderBody(markdown) {
30804
31493
  lines.splice(0, end + 2);
30805
31494
  }
30806
31495
  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;
31496
+ `).trim();
30822
31497
  }
30823
31498
  function fileMetrics(markdown) {
30824
31499
  const readerBody = normalizedReaderBody(markdown);
@@ -30831,7 +31506,7 @@ function fileMetrics(markdown) {
30831
31506
  }),
30832
31507
  byteCount: Buffer2.byteLength(markdown, "utf8"),
30833
31508
  readerBodyLineCount: lines.length,
30834
- empty: !lines.some(isReaderContentLine)
31509
+ empty: readerBody.length === 0
30835
31510
  };
30836
31511
  }
30837
31512
  function physicalRef(outputPath2, markdownDigest) {
@@ -30972,7 +31647,7 @@ function logicalUnitRegistrations(input) {
30972
31647
  throw new TypeError(`layout Node ${proposal.node.node_ref} lacks an Artifact Bundle`);
30973
31648
  }
30974
31649
  const entries = bundleEntryById(bundle);
30975
- if (entries.size !== proposal.artifacts.length || entries.size !== bundle.artifacts.length) {
31650
+ if (proposal.delivery_artifact_ids === undefined && entries.size !== proposal.artifacts.length || entries.size !== bundle.artifacts.length) {
30976
31651
  throw new TypeError(`Artifact Bundle ${bundle.bundle_digest} does not close its layout Artifact set`);
30977
31652
  }
30978
31653
  return proposal.artifacts.map((artifact) => {
@@ -31333,7 +32008,8 @@ function structuredArtifactSections(input) {
31333
32008
  return input.artifact.sections.map((section) => {
31334
32009
  const blocks = materializeIndexerStructuredContent({
31335
32010
  blocks: section.blocks,
31336
- facts: input.result.facts
32011
+ facts: input.result.facts,
32012
+ render_cache: input.render_cache
31337
32013
  });
31338
32014
  const evidenceRefs = [...new Set(blocks.flatMap((block) => block.evidence_refs))].sort(compareIndexerCanonicalText);
31339
32015
  assertSectionIntegrity({
@@ -31401,7 +32077,7 @@ function candidateFiles(input) {
31401
32077
  artifact.artifact_id,
31402
32078
  artifact
31403
32079
  ]));
31404
- return input.accepted.effectiveArtifacts.map((artifact) => {
32080
+ return input.accepted.effectiveArtifacts.filter((artifact) => input.proposal.delivery_artifact_ids === undefined || input.proposal.delivery_artifact_ids.includes(artifact.artifact_id)).map((artifact) => {
31405
32081
  const layout = layoutById.get(artifact.artifact_id);
31406
32082
  if (layout === undefined) {
31407
32083
  throw new TypeError(`Candidate compile Result Artifact ${artifact.artifact_id} has no layout`);
@@ -31409,7 +32085,8 @@ function candidateFiles(input) {
31409
32085
  const sections = artifact.representation === "sections" ? structuredArtifactSections({
31410
32086
  result: input.accepted.artifactResult,
31411
32087
  proposal: input.proposal,
31412
- artifact
32088
+ artifact,
32089
+ render_cache: input.render_cache
31413
32090
  }) : (() => {
31414
32091
  const rendered = renderedById.get(artifact.artifact_id);
31415
32092
  if (rendered === undefined) {
@@ -31421,6 +32098,19 @@ function candidateFiles(input) {
31421
32098
  rendered
31422
32099
  });
31423
32100
  })();
32101
+ for (const section of sections) {
32102
+ if (input.markdown_projection === undefined)
32103
+ continue;
32104
+ section.markdown = input.markdown_projection({
32105
+ markdown: section.markdown,
32106
+ output_path: layout.output_path,
32107
+ artifact_ref: layout.artifact_ref
32108
+ });
32109
+ section.markdown_digest = indexerProtocolDigest({
32110
+ protocol: "context.indexer.physical-section-markdown/v1",
32111
+ markdown: section.markdown
32112
+ });
32113
+ }
31424
32114
  const markdown = sections.map((section) => section.markdown).join(`
31425
32115
 
31426
32116
  `);
@@ -31536,14 +32226,15 @@ function buildIndexerCandidateCompile(input) {
31536
32226
  profile_contract: input.profile_contract,
31537
32227
  operator_contract: input.operator_contract,
31538
32228
  subject_key_schema_set: input.subject_key_schema_set,
31539
- rendered_artifacts: item.renderedArtifacts
32229
+ rendered_artifacts: item.renderedArtifacts,
32230
+ render_cache: input.render_cache
31540
32231
  });
31541
32232
  const binding = resultBinding({ accepted: item, proposal });
31542
32233
  return {
31543
32234
  accepted: item,
31544
32235
  proposal,
31545
32236
  binding,
31546
- files: candidateFiles({ accepted: item, proposal, binding })
32237
+ files: candidateFiles({ accepted: item, proposal, binding, markdown_projection: input.markdown_projection, render_cache: input.render_cache })
31547
32238
  };
31548
32239
  }).sort((left, right) => compareIndexerCanonicalText(left.binding.artifact_result_digest, right.binding.artifact_result_digest));
31549
32240
  const files = entries.flatMap((entry) => entry.files).sort((left, right) => compareIndexerCanonicalText(left.output_path, right.output_path));
@@ -31657,7 +32348,12 @@ function validateIndexerProviderContractReferences(input) {
31657
32348
  ...variant.artifact_kinds.required,
31658
32349
  ...variant.artifact_kinds.discretionary
31659
32350
  ]));
31660
- const sourceRoles = new Set(targetProfiles.flatMap((profile) => profile.layout_mappings.flatMap((mapping) => mapping.source_roles)));
32351
+ const declaredProfileIds = selectedBaseProfileIds({
32352
+ manifest: input.manifest,
32353
+ selectedProfiles: input.manifest.provides.profiles,
32354
+ registeredProfiles: new Set(profilesById.keys())
32355
+ });
32356
+ const sourceRoles = new Set([...declaredProfileIds].flatMap((id) => profilesById.get(id).layout_mappings.flatMap((mapping) => mapping.source_roles)));
31661
32357
  for (const sourceRole of input.manifest.provides.source_roles ?? []) {
31662
32358
  if (!sourceRoles.has(sourceRole)) {
31663
32359
  throw new TypeError(`Provider references unregistered layout source role ${sourceRole}`);
@@ -31977,8 +32673,8 @@ function recoverIndexerMainRunLedger(input) {
31977
32673
  ]));
31978
32674
  const previousByItem = new Map(previous?.entries.map((entry) => [entry.item_ref, entry]));
31979
32675
  const acceptedByIdentity = new Map((input.accepted_records ?? []).map((candidate) => {
31980
- const record2 = validateIndexerMainAcceptedRecord(candidate);
31981
- return [indexerMainRunIdentityDigest(record2), record2];
32676
+ const record4 = validateIndexerMainAcceptedRecord(candidate);
32677
+ return [indexerMainRunIdentityDigest(record4), record4];
31982
32678
  }));
31983
32679
  if (acceptedByIdentity.size !== (input.accepted_records ?? []).length) {
31984
32680
  throw new TypeError("accepted main run cache contains duplicate identities");
@@ -32059,16 +32755,16 @@ function startIndexerMainRuns(input) {
32059
32755
  }
32060
32756
  function acceptIndexerMainRun(input) {
32061
32757
  const ledger = validateIndexerMainRunLedger(input.ledger);
32062
- const record2 = validateIndexerMainAcceptedRecord(input.accepted_record);
32758
+ const record4 = validateIndexerMainAcceptedRecord(input.accepted_record);
32063
32759
  return replaceEntry({
32064
32760
  ledger,
32065
- workset_digest: record2.workset_digest,
32761
+ workset_digest: record4.workset_digest,
32066
32762
  replace: (entry) => {
32067
32763
  if (entry.state !== "running") {
32068
32764
  throw new TypeError("main result requires a running ledger entry");
32069
32765
  }
32070
- assertAcceptedRecord({ record: record2, base: entry });
32071
- return { ...entry, state: "accepted", accepted_record: record2 };
32766
+ assertAcceptedRecord({ record: record4, base: entry });
32767
+ return { ...entry, state: "accepted", accepted_record: record4 };
32072
32768
  }
32073
32769
  });
32074
32770
  }
@@ -32167,6 +32863,21 @@ function observeIndexerMainRunLedger(value) {
32167
32863
  records
32168
32864
  });
32169
32865
  }
32866
+ function invalidateIndexerMainRunWorksets(value, worksets) {
32867
+ const ledger = validateIndexerMainRunLedger(value);
32868
+ if ([...worksets].some((digest) => !ledger.entries.some((entry) => entry.workset_digest === digest))) {
32869
+ throw new TypeError("adjusted workset is not in the current ledger");
32870
+ }
32871
+ return buildLedger({
32872
+ workset_set: ledger.workset_set,
32873
+ entries: ledger.entries.map((entry, index) => !worksets.has(entry.workset_digest) ? entry : {
32874
+ ...entryBase({ item: ledger.workset_set.items[index], execution_request_digest: entry.execution_request_digest }),
32875
+ state: "stale",
32876
+ previous_workset_digest: entry.workset_digest,
32877
+ previous_execution_request_digest: entry.execution_request_digest
32878
+ })
32879
+ });
32880
+ }
32170
32881
  // src/indexerPostAuthorRunLedger.ts
32171
32882
  var composerRefSchema = exports_external.string().regex(/^provider:[^#]+#layer:[^#]+#composer:[A-Za-z0-9._-]+$/u);
32172
32883
  var ledgerEntryBase = {
@@ -32567,9 +33278,10 @@ function sameEnvelope(candidate, expected) {
32567
33278
  return parsed.success && indexerProtocolDigest(parsed.data) === indexerProtocolDigest(expected);
32568
33279
  }
32569
33280
  function observeIndexerPostAuthorState(input) {
32570
- const ledger = recoverIndexerPostAuthorRunLedger({
33281
+ const previous = validateIndexerPostAuthorRunLedger(input.ledger);
33282
+ const ledger = previous.workset_set_digest === input.plan.workset_set.workset_set_digest ? previous : recoverIndexerPostAuthorRunLedger({
32571
33283
  plan: input.plan,
32572
- previous_ledger: input.ledger,
33284
+ previous_ledger: previous,
32573
33285
  validator_contract_digest: input.validator_contract_digest
32574
33286
  });
32575
33287
  const effectiveSet = validateIndexerEffectiveComposerSet(input.effective_composer_set);
@@ -32626,7 +33338,7 @@ function observeIndexerPostAuthorState(input) {
32626
33338
  };
32627
33339
  }
32628
33340
  const counts = {
32629
- pending: ledger.entries.filter((entry) => entry.state === "pending").length,
33341
+ pending: ledger.entries.filter((entry) => entry.state === "pending" || entry.state === "running").length,
32630
33342
  accepted: ledger.entries.filter((entry) => entry.state === "accepted").length,
32631
33343
  failed: ledger.entries.filter((entry) => entry.state === "failed").length,
32632
33344
  stale: ledger.entries.filter((entry) => entry.state === "stale").length
@@ -32856,13 +33568,126 @@ var customPhase = (id, run, io = {}) => ({
32856
33568
  writes: io.writes ?? [],
32857
33569
  run
32858
33570
  });
33571
+ // src/managedSources.ts
33572
+ import { readdir, lstat, realpath as realpath3, readFile as readFile3 } from "node:fs/promises";
33573
+ import { join, relative as relative3, isAbsolute as isAbsolute4 } from "node:path";
33574
+
33575
+ // src/sessionMetadata.ts
33576
+ var sessionChangeSchema = exports_external.object({
33577
+ repository: exports_external.string().trim().min(1).optional(),
33578
+ commit: exports_external.string().regex(/^(?:[a-fA-F0-9]{40}|[a-fA-F0-9]{64})$/u).optional(),
33579
+ mr: exports_external.string().url().refine((value) => /^https?:\/\//u.test(value), "MR/PR must be an HTTP(S) URL").optional()
33580
+ }).strict().refine((value) => value.commit !== undefined || value.mr !== undefined, "A session change needs a commit or MR/PR reference");
33581
+ var sessionChangesSchema = exports_external.array(sessionChangeSchema);
33582
+ function sourceHeader(markdown) {
33583
+ const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u.exec(markdown);
33584
+ if (!match)
33585
+ return;
33586
+ const document = $parseDocument(match[1], { uniqueKeys: true });
33587
+ if (document.errors.length)
33588
+ throw new TypeError(`Invalid sessions frontmatter: ${document.errors[0].message}`);
33589
+ const value = document.toJS();
33590
+ if (value !== null && (typeof value !== "object" || Array.isArray(value))) {
33591
+ throw new TypeError("Sessions frontmatter must be a mapping");
33592
+ }
33593
+ return { value: value ?? {}, body: markdown.slice(match[0].length) };
33594
+ }
33595
+ function readSessionChanges(markdown) {
33596
+ const value = sourceHeader(markdown)?.value.changes;
33597
+ return value === undefined ? undefined : sessionChangesSchema.parse(value);
33598
+ }
33599
+ function writeSessionChanges(markdown, changes) {
33600
+ if (changes === undefined) {
33601
+ readSessionChanges(markdown);
33602
+ return markdown;
33603
+ }
33604
+ const parsed = sessionChangesSchema.parse(changes);
33605
+ const header = sourceHeader(markdown);
33606
+ const metadata = { ...header?.value ?? {} };
33607
+ if (parsed.length)
33608
+ metadata.changes = parsed;
33609
+ else
33610
+ delete metadata.changes;
33611
+ const body = header?.body ?? markdown;
33612
+ if (!Object.keys(metadata).length)
33613
+ return body;
33614
+ return `---
33615
+ ${$stringify(metadata)}---
33616
+ ${body}`;
33617
+ }
33618
+
33619
+ // src/managedSources.ts
33620
+ function assertManagedDocumentName(name) {
33621
+ if (!/^\d{8}\/[^/\\\x00-\x1f\s:#?]+\.md$/u.test(name) || name.includes("/..")) {
33622
+ throw new TypeError("Managed document name must be YYYYMMDD/semantic-name.md inside sources/note or sources/sessions");
33623
+ }
33624
+ const date = name.slice(0, 8);
33625
+ const parsed = new Date(`${date.slice(0, 4)}-${date.slice(4, 6)}-${date.slice(6, 8)}T00:00:00Z`);
33626
+ if (!Number.isFinite(parsed.getTime()) || parsed.toISOString().slice(0, 10).replaceAll("-", "") !== date) {
33627
+ throw new TypeError("Managed document date must be a valid YYYYMMDD date");
33628
+ }
33629
+ }
33630
+ async function assertManagedDocumentPath(rootDir, type, name) {
33631
+ assertManagedDocumentName(name);
33632
+ const root = await realpath3(rootDir);
33633
+ const parts = ["sources", type, ...name.split("/")];
33634
+ let path = root;
33635
+ for (const part of parts) {
33636
+ path = join(path, part);
33637
+ try {
33638
+ if ((await lstat(path)).isSymbolicLink())
33639
+ throw new TypeError("Managed document paths must not traverse symlinks");
33640
+ } catch (error) {
33641
+ if (!(error && typeof error === "object" && ("code" in error) && error.code === "ENOENT"))
33642
+ throw error;
33643
+ }
33644
+ }
33645
+ const rel = relative3(root, path);
33646
+ if (isAbsolute4(rel) || rel.startsWith("../"))
33647
+ throw new TypeError("Managed document path leaves its workspace");
33648
+ return path;
33649
+ }
33650
+ async function discoverManagedDocuments(rootDir, type) {
33651
+ const base = join(rootDir, "sources", type);
33652
+ await assertManagedDocumentPath(rootDir, type, "20000101/discovery.md");
33653
+ let dates;
33654
+ try {
33655
+ dates = await readdir(base, { withFileTypes: true });
33656
+ } catch (error) {
33657
+ if (error && typeof error === "object" && "code" in error && error.code === "ENOENT")
33658
+ return [];
33659
+ throw error;
33660
+ }
33661
+ const entries = [];
33662
+ for (const date of dates.sort((a, b) => a.name.localeCompare(b.name))) {
33663
+ if (!date.isDirectory() || !/^\d{8}$/u.test(date.name))
33664
+ continue;
33665
+ for (const file of (await readdir(join(base, date.name), { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
33666
+ if (!file.isFile() || !file.name.endsWith(".md"))
33667
+ continue;
33668
+ const name = `${date.name}/${file.name}`;
33669
+ await assertManagedDocumentPath(rootDir, type, name);
33670
+ const changes = type === "sessions" ? readSessionChanges(await readFile3(join(base, name), "utf8")) : undefined;
33671
+ entries.push({
33672
+ ...changes === undefined ? {} : { changes },
33673
+ id: name,
33674
+ name,
33675
+ namespace: date.name,
33676
+ module: file.name,
33677
+ materializedAt: `sources/${type}/${name}`
33678
+ });
33679
+ }
33680
+ }
33681
+ return entries;
33682
+ }
33683
+
32859
33684
  // src/sources.ts
32860
- import { readFile as readFile3 } from "node:fs/promises";
33685
+ import { readFile as readFile4 } from "node:fs/promises";
32861
33686
  import { resolve as resolve3 } from "node:path";
32862
33687
  var DEFAULT_REPO_SOURCES_REGISTRY_PATH = "sources/repo/index.yaml";
32863
33688
  var DEFAULT_FILE_SOURCES_REGISTRY_PATH = "sources/file/index.yaml";
32864
33689
  var DEFAULT_LARK_SOURCES_REGISTRY_PATH = "sources/lark/index.yaml";
32865
- var SOURCE_TYPES = ["repo", "file", "lark"];
33690
+ var SOURCE_TYPES = ["repo", "file", "lark", "note", "sessions"];
32866
33691
  var SOURCE_NAME_PATTERN = /^[a-z0-9][a-z0-9._-]*$/u;
32867
33692
  var REPO_DATE_NAMESPACE_PATTERN = /^\d{8}$/u;
32868
33693
  function assertSourceType(value, field) {
@@ -33165,7 +33990,7 @@ var parseLarkSourcesRegistry = (input, registryPath) => {
33165
33990
  };
33166
33991
  var readYamlIfPresent = async (absolutePath, emptyValue) => {
33167
33992
  try {
33168
- const content = await readFile3(absolutePath, "utf8");
33993
+ const content = await readFile4(absolutePath, "utf8");
33169
33994
  return content.trim().length === 0 ? emptyValue : $parse(content);
33170
33995
  } catch (error) {
33171
33996
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
@@ -33217,7 +34042,9 @@ var loadSourcesRegistry = async (options = {}) => {
33217
34042
  },
33218
34043
  repos: repoRegistry.repos,
33219
34044
  files,
33220
- larks
34045
+ larks,
34046
+ notes: await discoverManagedDocuments(rootDir, "note"),
34047
+ sessions: await discoverManagedDocuments(rootDir, "sessions")
33221
34048
  };
33222
34049
  assertGlobalSourceUniqueness(registry);
33223
34050
  return registry;
@@ -33261,6 +34088,221 @@ var allSources = (type) => {
33261
34088
  type
33262
34089
  }];
33263
34090
  };
34091
+ // src/processedScopes.ts
34092
+ var reference = exports_external.string().min(1).refine((value) => value.trim() === value, {
34093
+ message: "scope references must not have surrounding whitespace"
34094
+ });
34095
+ var processedScopeSchema = exports_external.object({
34096
+ requirement_ref: reference,
34097
+ source_ref: reference,
34098
+ processed_version: reference,
34099
+ module_refs: exports_external.array(reference).min(1).optional()
34100
+ }).strict().superRefine((scope, context) => {
34101
+ if (scope.module_refs && new Set(scope.module_refs).size !== scope.module_refs.length) {
34102
+ context.addIssue({
34103
+ code: exports_external.ZodIssueCode.custom,
34104
+ path: ["module_refs"],
34105
+ message: "module_refs must not contain duplicates"
34106
+ });
34107
+ }
34108
+ });
34109
+ function processedScopeKey(scope) {
34110
+ return JSON.stringify([
34111
+ scope.requirement_ref,
34112
+ scope.source_ref,
34113
+ [...scope.module_refs ?? []].sort()
34114
+ ]);
34115
+ }
34116
+ var processedScopesSchema = exports_external.array(processedScopeSchema).superRefine((scopes, context) => {
34117
+ const seen = new Set;
34118
+ scopes.forEach((scope, index) => {
34119
+ const key = processedScopeKey(scope);
34120
+ if (seen.has(key)) {
34121
+ context.addIssue({
34122
+ code: exports_external.ZodIssueCode.custom,
34123
+ path: [index],
34124
+ message: "processed_scopes must contain only one latest version per exact scope"
34125
+ });
34126
+ }
34127
+ seen.add(key);
34128
+ });
34129
+ });
34130
+ function readProcessedScopes(structure) {
34131
+ return processedScopesSchema.parse(structure?.processed_scopes === undefined ? [] : structure.processed_scopes);
34132
+ }
34133
+ function containsScope(outer, inner) {
34134
+ 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)));
34135
+ }
34136
+ function mergeProcessedScopes(previous, completed) {
34137
+ const updates = processedScopesSchema.parse(completed);
34138
+ const retained = processedScopesSchema.parse(previous).filter((scope) => !updates.some((update) => containsScope(update, scope)));
34139
+ return [...retained, ...updates].sort((a, b) => processedScopeKey(a).localeCompare(processedScopeKey(b)));
34140
+ }
34141
+ function processedVersionForScope(scopes, scope) {
34142
+ const parsed = processedScopesSchema.parse(scopes);
34143
+ const exact = parsed.find((entry) => processedScopeKey(entry) === processedScopeKey(scope));
34144
+ if (exact)
34145
+ return exact.processed_version;
34146
+ const versions = new Set(parsed.filter((entry) => containsScope(entry, scope)).map((entry) => entry.processed_version));
34147
+ return versions.size === 1 ? [...versions][0] : undefined;
34148
+ }
34149
+ // src/indexerApprovedKnowledge.ts
34150
+ var indexerApprovedKnowledgeSchema = exports_external.object({
34151
+ protocol: exports_external.literal("context.indexer.approved-knowledge/v1"),
34152
+ artifact_ref: indexerCanonicalRefSchema,
34153
+ subject_key: indexerSubjectKeySchema,
34154
+ primary_indexer_id: exports_external.string().min(1).optional(),
34155
+ path: portableIndexerPathSchema,
34156
+ approved_content_digest: indexerDigestSchema,
34157
+ source_versions: exports_external.array(exports_external.object({
34158
+ source_ref: indexerCanonicalRefSchema,
34159
+ module_ref: indexerCanonicalRefSchema.nullable(),
34160
+ version: exports_external.string().min(1)
34161
+ }).strict()).min(1),
34162
+ sections: exports_external.array(exports_external.object({
34163
+ section_ref: indexerCanonicalRefSchema,
34164
+ section_key: exports_external.string().min(1).optional(),
34165
+ markdown: exports_external.string().min(1),
34166
+ fact_refs: exports_external.array(indexerCanonicalRefSchema),
34167
+ evidence_refs: exports_external.array(indexerCanonicalRefSchema).min(1)
34168
+ }).strict()).min(1),
34169
+ facts: exports_external.array(indexerArtifactFactSchema),
34170
+ evidence_bindings: exports_external.array(indexerEvidenceBindingSchema),
34171
+ dependencies: exports_external.array(indexerKnowledgeDependencySchema),
34172
+ dependency_versions: exports_external.array(indexerKnowledgeDependencyVersionSchema).optional(),
34173
+ snapshot_digest: indexerDigestSchema
34174
+ }).strict();
34175
+ var sourceKey = (source2) => JSON.stringify([source2.source_ref, source2.module_ref]);
34176
+ function validateIndexerApprovedKnowledge(value) {
34177
+ const snapshot2 = indexerApprovedKnowledgeSchema.parse(value);
34178
+ const { snapshot_digest, ...payload3 } = snapshot2;
34179
+ if (indexerProtocolDigest(payload3) !== snapshot_digest)
34180
+ throw new TypeError("Approved knowledge snapshot integrity changed");
34181
+ const facts = new Map(snapshot2.facts.map((fact) => [fact.fact_ref, fact]));
34182
+ const evidence = new Map(snapshot2.evidence_bindings.map((binding) => [binding.evidence_ref, binding]));
34183
+ const sources = new Set(snapshot2.source_versions.map(sourceKey));
34184
+ const versions = snapshot2.dependency_versions ?? [];
34185
+ 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))) {
34186
+ throw new TypeError("Approved knowledge has duplicate or undeclared dependency versions");
34187
+ }
34188
+ 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) {
34189
+ throw new TypeError("Approved knowledge snapshot repeats an identity");
34190
+ }
34191
+ for (const binding of evidence.values()) {
34192
+ if (!sources.has(sourceKey(binding)))
34193
+ throw new TypeError("Approved knowledge evidence has no source version");
34194
+ const { binding_digest, ...content } = binding;
34195
+ if (indexerProtocolDigest(content) !== binding_digest)
34196
+ throw new TypeError("Approved knowledge evidence binding changed");
34197
+ }
34198
+ for (const fact of facts.values()) {
34199
+ if (fact.evidence_refs.some((ref) => !evidence.has(ref)))
34200
+ throw new TypeError("Approved knowledge fact has unknown source evidence");
34201
+ }
34202
+ for (const section of snapshot2.sections) {
34203
+ if (section.evidence_refs.some((ref) => !evidence.has(ref)))
34204
+ throw new TypeError("Approved knowledge section has unknown source evidence");
34205
+ for (const ref of section.fact_refs) {
34206
+ const fact = facts.get(ref);
34207
+ if (!fact || fact.evidence_refs.some((evidenceRef) => !section.evidence_refs.includes(evidenceRef))) {
34208
+ throw new TypeError("Approved knowledge section fact is outside its evidence binding");
34209
+ }
34210
+ }
34211
+ }
34212
+ return snapshot2;
34213
+ }
34214
+ function buildIndexerApprovedKnowledge(payload3) {
34215
+ return validateIndexerApprovedKnowledge({ ...payload3, snapshot_digest: indexerProtocolDigest(payload3) });
34216
+ }
34217
+ function projectIndexerApprovedKnowledge(input) {
34218
+ const available = new Map(input.snapshots.map((snapshot2) => [snapshot2.artifact_ref, snapshot2]));
34219
+ if (available.size !== input.snapshots.length)
34220
+ throw new TypeError("Approved knowledge projection repeats an article");
34221
+ const scope = new Map(input.authorized_sources.map((source2) => [sourceKey(source2), source2.version]));
34222
+ if (scope.size !== input.authorized_sources.length || new Set(input.dependencies.map((dependency) => dependency.artifact_ref)).size !== input.dependencies.length) {
34223
+ throw new TypeError("Approved knowledge projection repeats a source or dependency identity");
34224
+ }
34225
+ const pending = [];
34226
+ const versions = [];
34227
+ const facts = [];
34228
+ const readingSections = [];
34229
+ const evidence = new Map;
34230
+ for (const value of input.dependencies) {
34231
+ const dependency = indexerKnowledgeDependencySchema.parse(value);
34232
+ const defer = (reason) => pending.push({ artifact_ref: dependency.artifact_ref, required: dependency.required, reason });
34233
+ const raw = available.get(dependency.artifact_ref);
34234
+ if (!raw) {
34235
+ defer("not-approved");
34236
+ continue;
34237
+ }
34238
+ const snapshot2 = validateIndexerApprovedKnowledge(raw);
34239
+ if (input.approved_versions.get(snapshot2.artifact_ref) !== snapshot2.approved_content_digest) {
34240
+ defer("approval-changed");
34241
+ continue;
34242
+ }
34243
+ const sections = dependency.section_refs.length ? snapshot2.sections.filter((section) => dependency.section_refs.includes(section.section_ref)) : snapshot2.sections;
34244
+ if (sections.length !== (dependency.section_refs.length || snapshot2.sections.length)) {
34245
+ defer("section-unavailable");
34246
+ continue;
34247
+ }
34248
+ const factRefs = new Set(sections.flatMap((section) => section.fact_refs));
34249
+ const evidenceRefs = new Set(sections.flatMap((section) => section.evidence_refs));
34250
+ const bindings = snapshot2.evidence_bindings.filter((binding) => evidenceRefs.has(binding.evidence_ref));
34251
+ const selectedSourceKeys = new Set(bindings.map(sourceKey));
34252
+ const sourceVersions = snapshot2.source_versions.filter((source2) => selectedSourceKeys.has(sourceKey(source2)));
34253
+ if (sourceVersions.some((source2) => !scope.has(sourceKey(source2)))) {
34254
+ throw new TypeError(`Approved knowledge is outside the current read scope: ${snapshot2.artifact_ref}`);
34255
+ }
34256
+ if (sourceVersions.some((source2) => scope.get(sourceKey(source2)) !== source2.version)) {
34257
+ defer("source-version-changed");
34258
+ continue;
34259
+ }
34260
+ if (bindings.some((binding) => !input.evidence_kinds.has(binding.kind)))
34261
+ throw new TypeError("Provider cannot consume the approved knowledge evidence kind");
34262
+ for (const binding of bindings) {
34263
+ const previous = evidence.get(binding.evidence_ref);
34264
+ if (previous && previous.binding_digest !== binding.binding_digest)
34265
+ throw new TypeError("Approved knowledge sources have conflicting evidence identities");
34266
+ evidence.set(binding.evidence_ref, binding);
34267
+ }
34268
+ const projectionDigest = indexerProtocolDigest({ snapshot: snapshot2.snapshot_digest, sections: sections.map((section) => section.section_ref).sort() });
34269
+ versions.push({ artifact_ref: snapshot2.artifact_ref, approved_content_digest: snapshot2.approved_content_digest, projection_digest: projectionDigest });
34270
+ for (const section of sections)
34271
+ readingSections.push({
34272
+ artifact_ref: snapshot2.artifact_ref,
34273
+ section_ref: section.section_ref,
34274
+ approved_content_digest: snapshot2.approved_content_digest,
34275
+ evidence_role: "approved-interpretation",
34276
+ markdown: section.markdown,
34277
+ evidence_refs: section.evidence_refs
34278
+ });
34279
+ for (const fact of snapshot2.facts.filter((fact2) => factRefs.has(fact2.fact_ref))) {
34280
+ const value2 = {
34281
+ approved_artifact_ref: snapshot2.artifact_ref,
34282
+ approved_content_digest: snapshot2.approved_content_digest,
34283
+ original_fact_ref: fact.fact_ref,
34284
+ original_subject: fact.subject_key,
34285
+ source_versions: sourceVersions,
34286
+ value: fact.value
34287
+ };
34288
+ facts.push({
34289
+ fact_ref: `fact:approved-${indexerProtocolDigest(value2).slice(7)}`,
34290
+ fact_kind: "approved-knowledge-fact",
34291
+ subject_key: input.subject_key,
34292
+ value: value2,
34293
+ evidence_refs: fact.evidence_refs
34294
+ });
34295
+ }
34296
+ }
34297
+ return {
34298
+ status: pending.some((item) => item.required) ? "waiting" : "ready",
34299
+ pending,
34300
+ versions,
34301
+ facts,
34302
+ reading_sections: readingSections,
34303
+ evidence_bindings: [...evidence.values()]
34304
+ };
34305
+ }
33264
34306
 
33265
34307
  // src/index.ts
33266
34308
  function assertUniquePhaseIds(phases) {
@@ -33467,12 +34509,14 @@ var kbPackage = (definition) => {
33467
34509
  const base = createPackageDefinitionBase("kb", definition);
33468
34510
  const distribution = normalizePackageDistribution(definition.distribution);
33469
34511
  const assets = normalizePackageAssets(definition.assets);
34512
+ const site = normalizePackageSite(definition.site);
33470
34513
  return {
33471
34514
  kind: "package.kb",
33472
34515
  ...base,
33473
34516
  navigation: normalizePackageNavigation(definition.navigation),
33474
34517
  ...distribution === undefined ? {} : { distribution },
33475
- assets
34518
+ assets,
34519
+ ...site === undefined ? {} : { site }
33476
34520
  };
33477
34521
  };
33478
34522
  var llmsPackage = (definition) => ({
@@ -33480,9 +34524,11 @@ var llmsPackage = (definition) => ({
33480
34524
  ...createPackageDefinitionBase("llms", definition)
33481
34525
  });
33482
34526
  export {
34527
+ writeSessionChanges,
33483
34528
  validatedIndexerCustomizationDraftSchema,
33484
34529
  validateValidatedIndexerCustomizationDraft,
33485
34530
  validateResolvedProviderBundle,
34531
+ validateKnowledgeMap,
33486
34532
  validateIndexerToolSnapshot,
33487
34533
  validateIndexerTargetResolutionView,
33488
34534
  validateIndexerSubjectKeyForSchema,
@@ -33533,6 +34579,7 @@ export {
33533
34579
  validateIndexerPostAuthorRunLedger,
33534
34580
  validateIndexerPostAuthorFragmentResult,
33535
34581
  validateIndexerPostAuthorFragmentRequest,
34582
+ validateIndexerPlannedArticles,
33536
34583
  validateIndexerPhysicalArtifactAudit,
33537
34584
  validateIndexerPartitionStrategyResolution,
33538
34585
  validateIndexerPartitionStrategyAttempt,
@@ -33565,11 +34612,11 @@ export {
33565
34612
  validateIndexerLayoutProposal,
33566
34613
  validateIndexerLayoutChangeReport,
33567
34614
  validateIndexerLayerCompositionInput,
34615
+ validateIndexerKnowledgeDependencyGraph,
33568
34616
  validateIndexerInventoryDispositionSet,
33569
34617
  validateIndexerInspectorResult,
33570
34618
  validateIndexerInspectorRequest,
33571
34619
  validateIndexerIncrementalImpactReport,
33572
- validateIndexerGeneratedAuthoringAudit,
33573
34620
  validateIndexerFixedDependencySet,
33574
34621
  validateIndexerExampleLinkageAudit,
33575
34622
  validateIndexerExampleInventory,
@@ -33608,7 +34655,9 @@ export {
33608
34655
  validateIndexerArtifactDependencySet,
33609
34656
  validateIndexerArtifactBundlePolicy,
33610
34657
  validateIndexerArtifactBundle,
34658
+ validateIndexerArticlePlan,
33611
34659
  validateIndexerApprovedLayoutProjection,
34660
+ validateIndexerApprovedKnowledge,
33612
34661
  validateIndexerAgentStepInput,
33613
34662
  validateIndexerActivationResult,
33614
34663
  validateIndexerActivationRequest,
@@ -33619,10 +34668,14 @@ export {
33619
34668
  validateArtifactResults,
33620
34669
  validateAndRecordIndexerMainRun,
33621
34670
  validateAndMaterializeIndexerLayerFragment,
34671
+ updateKnowledgeMap,
33622
34672
  startIndexerPostAuthorRun,
33623
34673
  startIndexerMainRuns,
33624
34674
  startIndexerMainRun,
34675
+ sourceUpdateSemanticInputSchema,
33625
34676
  source,
34677
+ sessionChangesSchema,
34678
+ sessionChangeSchema,
33626
34679
  sameIndexerParserExecutionPlan,
33627
34680
  sameIndexerApprovedLayout,
33628
34681
  retryIndexerMainPartitionRun,
@@ -33649,20 +34702,31 @@ export {
33649
34702
  recoverIndexerPostAuthorRunLedger,
33650
34703
  recoverIndexerMainRunLedger,
33651
34704
  reconcileIndexerResults,
34705
+ readSessionChanges,
34706
+ readProcessedScopes,
33652
34707
  questionPairs,
34708
+ projectKnowledgeMap,
33653
34709
  projectIndexerSourceIdentityInventory,
34710
+ projectIndexerPublicContractTable,
33654
34711
  projectIndexerPartitionSubjects,
33655
34712
  projectIndexerFactValue,
34713
+ projectIndexerApprovedKnowledge,
34714
+ processedVersionForScope,
34715
+ processedScopesSchema,
34716
+ processedScopeSchema,
34717
+ processedScopeKey,
33656
34718
  planIndexerPostAuthorComposition,
33657
34719
  parseIndexerRegistry,
33658
34720
  parseIndexerProviderManifest,
33659
34721
  parseIndexerCurrentActionSubmission,
34722
+ packageSiteSchema,
33660
34723
  ownerCells,
33661
34724
  observeIndexerPostAuthorState,
33662
34725
  observeIndexerMainWorksetState,
33663
34726
  observeIndexerMainRunLedger,
33664
34727
  normalizeIndexerRequirementSet,
33665
34728
  normalizeIndexerExampleRelativePath,
34729
+ mergeProcessedScopes,
33666
34730
  mergeIndexerEvidenceAdapterResults,
33667
34731
  mergeIndexerEvidenceAdapterExecutions,
33668
34732
  mdxJsonDocs,
@@ -33677,10 +34741,15 @@ export {
33677
34741
  loadIndexerRegistry,
33678
34742
  loadIndexerProviderManifest,
33679
34743
  llmsPackage,
34744
+ knowledgeMapUpdateSchema,
34745
+ knowledgeMapTargetKey,
34746
+ knowledgeMapSchema,
34747
+ knowledgeMapEntrySchema,
33680
34748
  kbPackage,
33681
34749
  isPortableIndexerPath,
33682
34750
  isIndexerProviderProtocol,
33683
34751
  isIndexerLayerFragmentKind,
34752
+ invalidateIndexerMainRunWorksets,
33684
34753
  initializeIndexerPostAuthorRunLedger,
33685
34754
  initializeIndexerMainRunLedger,
33686
34755
  inflationSensitiveHardMaximum,
@@ -33881,6 +34950,7 @@ export {
33881
34950
  indexerMainRunIdentityDigest,
33882
34951
  indexerMainAcceptedRecordSchema,
33883
34952
  indexerLogicalUnitDependencyNodeSchema,
34953
+ indexerLayoutViewRef,
33884
34954
  indexerLayoutTransitionSchema,
33885
34955
  indexerLayoutSectionRef,
33886
34956
  indexerLayoutSectionIdentityRef,
@@ -33896,6 +34966,9 @@ export {
33896
34966
  indexerLayerFragmentDigest,
33897
34967
  indexerLayerCompositionInputSchema,
33898
34968
  indexerLayerCompositionInputDigest,
34969
+ indexerKnowledgeDependencyVersionSchema,
34970
+ indexerKnowledgeDependencySchema,
34971
+ indexerKnowledgeDependencyFingerprint,
33899
34972
  indexerKnowledgeCollectionSchema2 as indexerKnowledgeCollectionSchema,
33900
34973
  indexerInventoryMembersDigest,
33901
34974
  indexerInventoryMemberSchema,
@@ -33910,7 +34983,6 @@ export {
33910
34983
  indexerIncrementalImpactReportDigest,
33911
34984
  indexerImplementationFingerprint,
33912
34985
  indexerHostExecutionCapabilitiesSchema,
33913
- indexerGeneratedAuthoringAuditSchema,
33914
34986
  indexerFixedDependencySetSchema,
33915
34987
  indexerExecutionSchema,
33916
34988
  indexerExampleRepresentationSchema,
@@ -33948,6 +35020,7 @@ export {
33948
35020
  indexerCustomizationLadderStepSchema,
33949
35021
  indexerCustomizationDraftSchema,
33950
35022
  indexerCurrentActionInputSchema,
35023
+ indexerCurrentActionInputDefinitions,
33951
35024
  indexerCoverageCompletionReportSchema,
33952
35025
  indexerControlledProgramResultSchema,
33953
35026
  indexerControlledProgramRequestSchema,
@@ -33998,13 +35071,18 @@ export {
33998
35071
  indexerArtifactDependencySetDigest,
33999
35072
  indexerArtifactContentBlockSchema,
34000
35073
  indexerArtifactBundleSchema,
35074
+ indexerArticleSectionKey,
35075
+ indexerArticlePlanSchema,
35076
+ indexerArticleKeySchema,
34001
35077
  indexerApprovedLayoutProjectionSchema,
35078
+ indexerApprovedKnowledgeSchema,
34002
35079
  indexerAgentStepInputSchema,
34003
35080
  indexerAgentStepInputDigest,
34004
35081
  indexerActivationResultSchema,
34005
35082
  indexerActivationRequestSchema,
34006
35083
  indexRequirementSetSchema,
34007
35084
  indexRequirementSchema,
35085
+ impactedIndexerKnowledgeArticles,
34008
35086
  failIndexerPostAuthorRun,
34009
35087
  failIndexerMainRun,
34010
35088
  expectedProviderResolutionFromAction,
@@ -34012,6 +35090,7 @@ export {
34012
35090
  evaluateIndexerCandidateMaterialization,
34013
35091
  enforceIndexerSubjectKeySchemaTransition,
34014
35092
  dispositionMap,
35093
+ discoverManagedDocuments,
34015
35094
  deriveIndexerProgramExecutionPolicy,
34016
35095
  defineProject,
34017
35096
  customPhase,
@@ -34019,7 +35098,6 @@ export {
34019
35098
  coverageDomainCompletionSchema,
34020
35099
  coverageCompletionReportPayloadSchema,
34021
35100
  convergeIndexerPartitionPlan,
34022
- containsIndexerControlledAuthoringPlaceholder,
34023
35101
  confirmIndexerRequirementWorkset,
34024
35102
  confirmIndexerRequirementChange,
34025
35103
  confirmIndexerRequirementAmendment,
@@ -34109,7 +35187,6 @@ export {
34109
35187
  buildIndexerInspectorWorksetViewSource,
34110
35188
  buildIndexerInspectorRequest,
34111
35189
  buildIndexerIncrementalImpactReport,
34112
- buildIndexerGeneratedAuthoringAudit,
34113
35190
  buildIndexerFixedDependencySet,
34114
35191
  buildIndexerExampleLinkageAudit,
34115
35192
  buildIndexerExampleInventory,
@@ -34136,6 +35213,7 @@ export {
34136
35213
  buildIndexerArtifactDependencySet,
34137
35214
  buildIndexerArtifactBundle,
34138
35215
  buildIndexerApprovedLayoutProjection,
35216
+ buildIndexerApprovedKnowledge,
34139
35217
  buildIndexerAgentStepInput,
34140
35218
  buildIndexerActivationRequest,
34141
35219
  authorizeIndexerSubjectReidentification,
@@ -34147,16 +35225,19 @@ export {
34147
35225
  assertTopLevelNamespace,
34148
35226
  assertOkfRoot,
34149
35227
  assertNoReferenceOnlyReaderTargets,
35228
+ assertManagedDocumentPath,
35229
+ assertManagedDocumentName,
34150
35230
  assertMainlineCollection,
34151
35231
  assertKnowledgeCollection,
34152
35232
  assertIndexerPhysicalArtifactAuditPassed,
34153
35233
  assertIndexerParserDependenciesLocked,
34154
- assertIndexerGeneratedAuthoringAuditClear,
35234
+ assertIndexerInspectorProfileVariants,
34155
35235
  assertIndexerExampleIdentityAuditPassed,
34156
35236
  assertIndexerExampleCandidateDecisionClosure,
34157
35237
  assertIndexerCanonicalOrder,
34158
35238
  assertDocumentMainlineCollection,
34159
35239
  assertDocumentEvidenceSectionMetadata,
35240
+ approvedRevisionSemanticInputSchema,
34160
35241
  analyzeIndexerSubjectKeySchemaTransition,
34161
35242
  allSources,
34162
35243
  acceptIndexerPostAuthorRun,
@@ -34165,6 +35246,7 @@ export {
34165
35246
  OKF_ROOTS,
34166
35247
  MAINLINE_COLLECTIONS,
34167
35248
  KNOWLEDGE_COLLECTIONS,
35249
+ IndexerKnowledgeDependencyCycleError,
34168
35250
  INDEXER_SUBJECT_NORMALIZATIONS,
34169
35251
  INDEXER_SUBJECT_DERIVATION_OPERATORS,
34170
35252
  INDEXER_STRUCTURED_DECLARATION_KINDS,