@c4a/context-cli 0.7.0 → 0.7.4

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 (219) hide show
  1. package/README.md +18 -39
  2. package/README.zh-CN.md +13 -27
  3. package/cli.js +59230 -80555
  4. package/indexers/bundles/context-code-indexer/SKILL.md +30 -3
  5. package/indexers/bundles/context-code-indexer/context-indexer.yaml +3 -8
  6. package/indexers/bundles/context-code-indexer/references/indexer.md +110 -7
  7. package/indexers/bundles/context-code-indexer/references/metrics.md +143 -37
  8. package/indexers/bundles/context-code-indexer/templates/adapter-integration.md +2 -2
  9. package/indexers/bundles/context-code-indexer/templates/component-library.md +8 -0
  10. package/indexers/bundles/context-code-indexer/templates/gateway-facade.md +16 -0
  11. package/indexers/bundles/context-markdown-indexer/SKILL.md +13 -3
  12. package/indexers/bundles/context-markdown-indexer/context-indexer.yaml +20 -7
  13. package/indexers/bundles/context-markdown-indexer/references/indexer.md +33 -4
  14. package/indexers/bundles/context-markdown-indexer/references/semantic-planning.md +30 -14
  15. package/indexers/bundles/context-markdown-indexer/references/structure-and-artifacts.md +6 -0
  16. package/indexers/bundles/context-markdown-indexer/tests/fixtures/anonymous.json +1 -1
  17. package/indexers/bundles/context-markdown-indexer/tests/fixtures/profiles.json +13 -13
  18. package/indexers/bundles/context-markdown-indexer/tests/fixtures/routing.json +122 -0
  19. package/indexers/contracts/operator-contract.json +2 -2
  20. package/indexers/contracts/profile-contract.json +3819 -454
  21. package/indexers/release-manifest.json +22 -22
  22. package/package.json +13 -3
  23. package/plugins/VERSION +1 -1
  24. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  25. package/plugins/claude/commands/context.md +44 -85
  26. package/plugins/codex/.codex-plugin/plugin.json +2 -2
  27. package/plugins/codex/skills/context/SKILL.md +44 -85
  28. package/plugins/cursor/.cursor-plugin/plugin.json +1 -1
  29. package/plugins/cursor/commands/c4a-context.md +44 -85
  30. package/plugins/skills/context/SKILL.md +44 -85
  31. package/plugins/skills/context-code-indexer/SKILL.md +30 -3
  32. package/plugins/skills/context-code-indexer/context-indexer.yaml +3 -8
  33. package/plugins/skills/context-code-indexer/references/indexer.md +110 -7
  34. package/plugins/skills/context-code-indexer/references/metrics.md +143 -37
  35. package/plugins/skills/context-code-indexer/templates/adapter-integration.md +2 -2
  36. package/plugins/skills/context-code-indexer/templates/component-library.md +8 -0
  37. package/plugins/skills/context-code-indexer/templates/gateway-facade.md +16 -0
  38. package/plugins/skills/context-markdown-indexer/SKILL.md +13 -3
  39. package/plugins/skills/context-markdown-indexer/context-indexer.yaml +20 -7
  40. package/plugins/skills/context-markdown-indexer/references/indexer.md +33 -4
  41. package/plugins/skills/context-markdown-indexer/references/semantic-planning.md +30 -14
  42. package/plugins/skills/context-markdown-indexer/references/structure-and-artifacts.md +6 -0
  43. package/plugins/skills/context-markdown-indexer/tests/fixtures/anonymous.json +1 -1
  44. package/plugins/skills/context-markdown-indexer/tests/fixtures/profiles.json +13 -13
  45. package/plugins/skills/context-markdown-indexer/tests/fixtures/routing.json +122 -0
  46. package/providers/context/actions/advance-current-indexer-lifecycle.yaml +6 -0
  47. package/providers/context/actions/configure-indexer-providers.yaml +1 -1
  48. package/providers/context/actions/materialize-indexer-workset-view.yaml +7 -0
  49. package/providers/context/actions/run-indexer-lifecycle.yaml +7 -0
  50. package/providers/context/actions/run-indexer-post-author-composer.yaml +1 -1
  51. package/providers/context/codes.yaml +9 -49
  52. package/providers/context/graphs/indexer.yaml +75 -592
  53. package/providers/context/graphs/workspace.yaml +25 -500
  54. package/providers/context/manifest.json +110 -1199
  55. package/providers/context/provider.yaml +2 -2
  56. package/providers/context/resources/diagnostics/projection-stale.md +0 -1
  57. package/providers/context/resources/dialogue/human-gates.md +3 -3
  58. package/providers/context/resources/manuals/reference/package-templates.md +2 -3
  59. package/providers/context/resources/manuals/reference/project-api.md +52 -985
  60. package/providers/context/resources/procedures/close-and-build.md +8 -23
  61. package/providers/context/resources/procedures/knowledge-review.md +13 -4
  62. package/providers/context/resources/procedures/source-capture-detailed.md +6 -8
  63. package/providers/context/resources/views/authorized-indexer-workset-view.yaml +15 -0
  64. package/providers/context/resources/views/package-current.yaml +1 -1
  65. package/providers/context/resources/views/resolved-indexer-instructions.yaml +1 -1
  66. package/providers/context/resources/views/review-current.yaml +1 -1
  67. package/providers/context/resources/views/source-boundary.yaml +1 -1
  68. package/providers/context/resources/views/source-current.yaml +1 -1
  69. package/providers/context/resources/views/verification-current.yaml +1 -1
  70. package/providers/context/resources/views/workspace-current.yaml +1 -1
  71. package/providers/context/schemas/indexer-agent-step-input.schema.json +2 -2
  72. package/providers/context/schemas/indexer-agent-step-result.schema.json +298 -32
  73. package/providers/context/schemas/indexer-authorized-workset-view.schema.json +65 -0
  74. package/providers/context/schemas/indexer-contract-overlay-validation-input.schema.json +0 -42
  75. package/providers/context/schemas/indexer-contract-overlay-validation-result.schema.json +27 -122
  76. package/providers/context/schemas/indexer-lifecycle-continuation.schema.json +15 -0
  77. package/providers/context/schemas/indexer-main-lifecycle-input.schema.json +13 -20
  78. package/providers/context/schemas/indexer-main-lifecycle-output.schema.json +17 -2
  79. package/providers/context/schemas/indexer-materialized-resource.schema.json +8 -1
  80. package/providers/context/schemas/indexer-overlay-question-proposal-input.schema.json +55 -6
  81. package/providers/context/schemas/indexer-overlay-question-rebind-input.schema.json +4 -4
  82. package/providers/context/schemas/indexer-workset-view-materialization-request.schema.json +32 -0
  83. package/providers/context/skills/configure-indexer-providers/SKILL.md +40 -27
  84. package/providers/context/skills/run-indexer-agent-step/SKILL.md +34 -8
  85. package/providers/context/skills/run-indexer-lifecycle/SKILL.md +37 -0
  86. package/providers/context/skills/run-indexer-post-author-composer/SKILL.md +38 -9
  87. package/docs/document-optimization.md +0 -82
  88. package/docs/document-optimization.zh-CN.md +0 -70
  89. package/indexers/capability-manifest.json +0 -40
  90. package/indexers/contracts/hard-rule-conformance.json +0 -2644
  91. package/providers/context/actions/accept-main-index-run.yaml +0 -7
  92. package/providers/context/actions/accept-material-answer-run.yaml +0 -7
  93. package/providers/context/actions/accept-post-author-composer-run.yaml +0 -7
  94. package/providers/context/actions/actualize-material-answer-bindings.yaml +0 -8
  95. package/providers/context/actions/align-next.yaml +0 -6
  96. package/providers/context/actions/apply-code-index-guidance.yaml +0 -5
  97. package/providers/context/actions/apply-document-optimization-guidance.yaml +0 -5
  98. package/providers/context/actions/apply-structure-confirmation.yaml +0 -5
  99. package/providers/context/actions/audit-material-gap-state.yaml +0 -8
  100. package/providers/context/actions/audit-projected-artifact-fan-out.yaml +0 -8
  101. package/providers/context/actions/authorize-indexer-contract-overlay.yaml +0 -7
  102. package/providers/context/actions/build-main-index-author-worksets.yaml +0 -7
  103. package/providers/context/actions/build-main-index-catalog-fallback.yaml +0 -7
  104. package/providers/context/actions/build-main-index-partition-worksets.yaml +0 -7
  105. package/providers/context/actions/build-material-question-workset.yaml +0 -7
  106. package/providers/context/actions/build-post-author-composer-worksets.yaml +0 -7
  107. package/providers/context/actions/build-question-target-inventory.yaml +0 -7
  108. package/providers/context/actions/build-subject-catalog.yaml +0 -7
  109. package/providers/context/actions/build-target-resolution-views.yaml +0 -7
  110. package/providers/context/actions/checkpoint-material-answer-review.yaml +0 -8
  111. package/providers/context/actions/checkpoint-material-gaps.yaml +0 -8
  112. package/providers/context/actions/close-indexer-approved-knowledge.yaml +0 -8
  113. package/providers/context/actions/compile-next.yaml +0 -5
  114. package/providers/context/actions/compose-indexer-post-author-fragments.yaml +0 -7
  115. package/providers/context/actions/configure-code-extraction.yaml +0 -5
  116. package/providers/context/actions/configure-prose-lifecycle.yaml +0 -5
  117. package/providers/context/actions/converge-main-index-partition-run.yaml +0 -7
  118. package/providers/context/actions/evaluate-material-gaps.yaml +0 -8
  119. package/providers/context/actions/extract-next.yaml +0 -5
  120. package/providers/context/actions/fail-main-index-run.yaml +0 -7
  121. package/providers/context/actions/fail-material-answer-run.yaml +0 -7
  122. package/providers/context/actions/fail-post-author-composer-run.yaml +0 -7
  123. package/providers/context/actions/inspect-code-extraction.yaml +0 -5
  124. package/providers/context/actions/inspect-document-classification.yaml +0 -5
  125. package/providers/context/actions/inspect-index-candidate-review-readiness.yaml +0 -8
  126. package/providers/context/actions/inspect-index-profile-failure.yaml +0 -7
  127. package/providers/context/actions/inspect-material-answer-review.yaml +0 -8
  128. package/providers/context/actions/inspect-structure.yaml +0 -5
  129. package/providers/context/actions/migrate-codeindex.yaml +0 -5
  130. package/providers/context/actions/observe-main-index-run-ledger.yaml +0 -7
  131. package/providers/context/actions/observe-material-answer-runs.yaml +0 -7
  132. package/providers/context/actions/observe-post-author-composer-worksets.yaml +0 -7
  133. package/providers/context/actions/optimize-documents.yaml +0 -6
  134. package/providers/context/actions/override-index-profile-audit.yaml +0 -7
  135. package/providers/context/actions/prepare-main-index-run-ledger.yaml +0 -7
  136. package/providers/context/actions/prepare-material-answer-runs.yaml +0 -7
  137. package/providers/context/actions/preview-extraction-batch.yaml +0 -5
  138. package/providers/context/actions/reconcile-indexer-results.yaml +0 -7
  139. package/providers/context/actions/reconcile-review-identities.yaml +0 -5
  140. package/providers/context/actions/record-index-profile-revision.yaml +0 -7
  141. package/providers/context/actions/report-index-profile-failure.yaml +0 -7
  142. package/providers/context/actions/resolve-effective-composers.yaml +0 -7
  143. package/providers/context/actions/review-material-answer-candidate.yaml +0 -8
  144. package/providers/context/actions/revise-code-index-audit.yaml +0 -5
  145. package/providers/context/actions/revise-document.yaml +0 -5
  146. package/providers/context/actions/revise-index-output.yaml +0 -7
  147. package/providers/context/actions/run-material-answer-indexers.yaml +0 -7
  148. package/providers/context/actions/start-main-index-run.yaml +0 -7
  149. package/providers/context/actions/start-material-answer-run.yaml +0 -7
  150. package/providers/context/actions/start-post-author-composer-run.yaml +0 -7
  151. package/providers/context/actions/submit-code-index-audit.yaml +0 -6
  152. package/providers/context/resources/dialogue/code-extraction.md +0 -87
  153. package/providers/context/resources/dialogue/document-classification.md +0 -33
  154. package/providers/context/resources/dialogue/structure-confirmation.md +0 -44
  155. package/providers/context/resources/dialogue/workflow-mode-after-capture.md +0 -25
  156. package/providers/context/resources/manuals/reference/code-extractors.md +0 -152
  157. package/providers/context/resources/procedures/code-extraction.md +0 -188
  158. package/providers/context/resources/procedures/code-index-audit.md +0 -113
  159. package/providers/context/resources/procedures/document-classification.md +0 -22
  160. package/providers/context/resources/procedures/document-optimization.md +0 -110
  161. package/providers/context/resources/procedures/document-revision.md +0 -36
  162. package/providers/context/resources/procedures/prose-align.md +0 -68
  163. package/providers/context/resources/procedures/prose-compile.md +0 -23
  164. package/providers/context/resources/semantic/align/candidate-resolution.md +0 -106
  165. package/providers/context/resources/semantic/align/density-profile.md +0 -41
  166. package/providers/context/resources/semantic/align/gates.md +0 -276
  167. package/providers/context/resources/semantic/align/structure-planning.md +0 -337
  168. package/providers/context/resources/semantic/code-index/classification.md +0 -270
  169. package/providers/context/resources/semantic/code-index/templates/adapter.md +0 -118
  170. package/providers/context/resources/semantic/code-index/templates/api-service.md +0 -116
  171. package/providers/context/resources/semantic/code-index/templates/background-runtime.md +0 -109
  172. package/providers/context/resources/semantic/code-index/templates/cli-tool.md +0 -129
  173. package/providers/context/resources/semantic/code-index/templates/contract-source.md +0 -73
  174. package/providers/context/resources/semantic/code-index/templates/contracts-and-chains.md +0 -81
  175. package/providers/context/resources/semantic/code-index/templates/cross-module-chain.md +0 -78
  176. package/providers/context/resources/semantic/code-index/templates/derived-source.md +0 -116
  177. package/providers/context/resources/semantic/code-index/templates/domain-service.md +0 -109
  178. package/providers/context/resources/semantic/code-index/templates/event-flow.md +0 -62
  179. package/providers/context/resources/semantic/code-index/templates/monorepo-container.md +0 -124
  180. package/providers/context/resources/semantic/code-index/templates/persistence-boundary.md +0 -56
  181. package/providers/context/resources/semantic/code-index/templates/plugin-extension.md +0 -52
  182. package/providers/context/resources/semantic/code-index/templates/protocol-boundary.md +0 -88
  183. package/providers/context/resources/semantic/code-index/templates/sdk-library.md +0 -132
  184. package/providers/context/resources/semantic/code-index/templates/web-application.md +0 -145
  185. package/providers/context/resources/semantic/compile/index.md +0 -31
  186. package/providers/context/resources/views/code-index-audit.yaml +0 -6
  187. package/providers/context/resources/views/document-optimization-current.yaml +0 -6
  188. package/providers/context/resources/views/extraction-preview.yaml +0 -6
  189. package/providers/context/resources/views/structure-current.yaml +0 -6
  190. package/providers/context/schemas/code-index-audit-decision.schema.json +0 -94
  191. package/providers/context/schemas/document-optimization-decisions.schema.json +0 -57
  192. package/providers/context/schemas/indexer-candidate-review-readiness-input.schema.json +0 -46
  193. package/providers/context/schemas/indexer-candidate-review-readiness-output.schema.json +0 -104
  194. package/providers/context/schemas/indexer-contract-overlay-authorization-input.schema.json +0 -32
  195. package/providers/context/schemas/indexer-contract-overlay-authorization-result.schema.json +0 -121
  196. package/providers/context/schemas/indexer-material-answer-lifecycle-input.schema.json +0 -90
  197. package/providers/context/schemas/indexer-material-answer-lifecycle-output.schema.json +0 -80
  198. package/providers/context/schemas/indexer-material-answer-review-inspection-input.schema.json +0 -32
  199. package/providers/context/schemas/indexer-material-answer-review-inspection-output.schema.json +0 -32
  200. package/providers/context/schemas/indexer-material-answer-review-resolution-input.schema.json +0 -19
  201. package/providers/context/schemas/indexer-material-answer-review-resolution-output.schema.json +0 -87
  202. package/providers/context/schemas/indexer-material-gap-lifecycle-input.schema.json +0 -86
  203. package/providers/context/schemas/indexer-material-gap-lifecycle-output.schema.json +0 -19
  204. package/providers/context/schemas/indexer-post-author-fragment-result.schema.json +0 -18
  205. package/providers/context/schemas/indexer-post-author-lifecycle-input.schema.json +0 -94
  206. package/providers/context/schemas/indexer-post-author-lifecycle-output.schema.json +0 -72
  207. package/providers/context/schemas/indexer-profile-failure-inspection-input.schema.json +0 -13
  208. package/providers/context/schemas/indexer-profile-failure-inspection-result.schema.json +0 -19
  209. package/providers/context/schemas/indexer-profile-failure-report-input.schema.json +0 -22
  210. package/providers/context/schemas/indexer-profile-failure-report-result.schema.json +0 -49
  211. package/providers/context/schemas/indexer-profile-override-decision.schema.json +0 -20
  212. package/providers/context/schemas/indexer-profile-override-result.schema.json +0 -49
  213. package/providers/context/schemas/indexer-profile-revision-agent-input.schema.json +0 -18
  214. package/providers/context/schemas/indexer-profile-revision-record-input.schema.json +0 -31
  215. package/providers/context/schemas/indexer-profile-revision-record-result.schema.json +0 -45
  216. package/providers/context/schemas/indexer-result-reconciliation-input.schema.json +0 -59
  217. package/providers/context/schemas/indexer-result-reconciliation-output.schema.json +0 -43
  218. package/providers/context/schemas/prose-structure-batch.schema.json +0 -35
  219. package/providers/context/skills/revise-index-output/SKILL.md +0 -12
@@ -4,1031 +4,98 @@ kind: procedure
4
4
  mediaType: text/markdown
5
5
  ---
6
6
 
7
- # Project API
7
+ # Context Project API
8
8
 
9
- Import from `@c4a/context` in `src/index.ts`.
9
+ The project has two durable declarations with separate responsibilities:
10
+
11
+ - `src/index.ts`: source references, document capture, custom non-knowledge
12
+ orchestration, and package outputs.
13
+ - `src/indexers.yaml`: knowledge requirements, Provider selection, target/read
14
+ scopes, profiles, and Provider customization.
15
+
16
+ Do not describe the same knowledge transformation in both files.
10
17
 
11
18
  ## `defineProject`
12
19
 
13
20
  ```ts
14
- import { defineProject } from "@c4a/context";
15
-
16
- export default defineProject({
21
+ defineProject({
17
22
  sources: [],
18
23
  phases: [],
19
24
  packages: [],
20
25
  });
21
26
  ```
22
27
 
23
- The project file is executable TypeScript, but the preferred style is a small
24
- declaration list. Put heavy logic in imported transform files.
28
+ The definition is declarative. Loading it must not mutate knowledge or runtime
29
+ state.
25
30
 
26
31
  ## Sources
27
32
 
28
- A source is a stable knowledge boundary, not only a display label. Repo, file,
29
- and Lark sources use a date batch plus a concrete module name; multiple code or
30
- document modules may share the date. The flattened selector `YYYYMMDD/module`
31
- is the source identity used by phases, snapshot paths, and source refs.
32
- Codegraph NodeRef/ViewRef and knowledge paths use the stable module name without
33
- the date:
34
-
35
- ```text
36
- knowledge/<collection>/<slug>.md
37
- knowledge/<collection>/<containment>/<slug>.md # only for an intentional hierarchy
38
- knowledge/codeindex/<module>/symbol/<slug>.md
39
- repo:<date>/<module>#symbol:...
40
- file:<date>/<module>/<document>#span:...
41
- lark:<date>/<module>/<document>#span:...
42
- capture:file:<date>/<module>
43
- align:lark:<date>/<module>:architecture
44
- dist/<source-name>-kb/...
45
- ```
46
-
47
- Choose the module boundary before extraction. In a monorepo, register each
48
- confirmed package/subdirectory under the same date batch. A repo root that
49
- resolves to multiple modules is for inspection; it is not an extraction unit.
50
- Approved codeindex paths use the stable module name; the date remains only in
51
- source selectors, phase ids, and evidence refs:
52
-
53
- ```text
54
- knowledge/codeindex/module-a/...
55
- knowledge/codeindex/module-b/...
56
- ```
57
-
58
- For prose Views, provide a stable filename `slug` and omit `path`; the CLI
59
- derives the path. Omit `containment` when the page is an independent collection
60
- entry, producing `knowledge/<collection>/<slug>.md`. Set `containment` only
61
- when the approved structure intentionally places the page under a parent path;
62
- it is not a required source/module wrapper.
63
-
64
- The registry stores this as one date entry containing several `modules` entries,
65
- and materializes each module at `sources/repo/<date>/<module>`.
66
- Repo module names are project-wide codeindex identities and therefore cannot be
67
- reused under another date batch. Refresh an existing module through its original
68
- date/module selector.
69
- When a repo module and the Context workspace share the same Git root, the CLI
70
- normalizes even an absolute `--local` input into a path relative to the
71
- workspace and stores the package directory as `subpath`. Materialized repo
72
- links always use relative symlink targets. This keeps the registry and links
73
- valid when the whole checkout moves. Cross-repository absolute checkout roots
74
- remain absolute because no shared movable root can be assumed.
75
- The date entry must be a valid calendar date in `YYYYMMDD` form. Use
76
- `context source ensure <date>` or `context source inspect <date>` for the whole
77
- batch, and `<date>/<module>` when targeting one module.
78
-
79
- ```yaml
80
- sources:
81
- - name: "20260712"
82
- modules:
83
- - name: module-a
84
- local: ../monorepo
85
- subpath: packages/module-a
86
- git:
87
- remote: https://git.example.com/product/monorepo.git
88
- ref: <full-commit-sha>
89
- - name: module-b
90
- local: ../monorepo
91
- subpath: packages/module-b
92
- git:
93
- remote: https://git.example.com/product/monorepo.git
94
- ref: <full-commit-sha>
95
- ```
96
-
97
- File and Lark registries use the same outer shape. Their modules hold local
98
- document boundaries or remote document identities:
99
-
100
- ```yaml
101
- sources:
102
- - name: "20260712"
103
- modules:
104
- - name: local-manual
105
- local: ../manual
106
- - name: api-guide
107
- local: ../api-guide
108
- ```
109
-
110
- ### Batch source registration
111
-
112
- Use one command when a user confirms several source modules together:
113
-
114
- ```bash
115
- context source add batch [YYYYMMDD] --input <sources.yaml|json|-> --format json
116
- ```
117
-
118
- The payload is a non-empty `sources` array. Every item requires `type`. Repo
119
- also requires `module` and accepts `local`/`remote`/`ref`. File requires `local`
120
- and accepts `include`; Lark accepts exactly one of `url`, `docToken`, or
121
- `wikiToken` plus optional `title`. File/Lark `module` is optional and is derived
122
- with the same lowercase path-safe rule as the single-source commands. Resolved
123
- module identities must be unique across the batch.
124
-
125
- Source mutations share a project write lock, and every registry file is
126
- replaced atomically. Never run separate `source add` processes in parallel. A
127
- batch executes items in order; if a runtime item fails, its error lists the
128
- completed items and the same payload may be rerun idempotently.
129
-
130
- ```yaml
131
- sources:
132
- - name: "20260712"
133
- modules:
134
- - name: user-manual
135
- url: https://example.larksuite.com/wiki/example-a
136
- - name: migration-guide
137
- url: https://example.larksuite.com/wiki/example-b
138
- ```
139
-
140
- ### `source(name)`
141
-
142
- Reference one registered source by name. The reference is type-neutral in
143
- project code; each phase resolves it through the registry and checks whether it
144
- is a repo, file, or lark source:
145
-
146
- ```ts
147
- import { source } from "@c4a/context";
148
-
149
- const productDocs = source("product-docs");
150
- ```
151
-
152
- ### `source(namespace, module)`
153
-
154
- Reference one registered repo module. Use the date batch and module name
155
- returned by `context source add repo`:
156
-
157
- ```ts
158
- const moduleA = source("20260712", "module-a");
159
- const moduleB = source("20260712", "module-b");
160
- ```
161
-
162
- These references resolve to `20260712/module-a` and `20260712/module-b`;
163
- extraction and verification remain independent.
164
-
165
- ### `source(namespace, module, { type })`
166
-
167
- Reference one file or Lark module under a date batch:
168
-
169
33
  ```ts
170
- const localManual = source("20260712", "local-manual", { type: "file" });
171
- const userManual = source("20260712", "user-manual", { type: "lark" });
34
+ const repo = source("20260901", "component-lib");
35
+ const docs = source("product-docs", { type: "file" });
36
+ const handbook = source("handbook", { type: "lark" });
37
+ const everyRepo = allSources("repo");
172
38
  ```
173
39
 
174
- These references produce module-scoped phase ids and manifest entries without
175
- treating the date as one document identity. Captured document files remain
176
- siblings under `sources/file|lark/<date>/` and share the date-level
177
- `manifest.json`; the logical `date/module` identity does not create another
178
- directory level.
179
-
180
- For a confirmed multi-document request, declare one capture phase per module.
181
- While any module is uncaptured, `context status --format json` selects either
182
- the `route.capture.configuration-required` Route with
183
- `workflow.current.configuration`, or the `route.capture.pending-target` Route
184
- with the next declared command in `workflow.current.commands`.
185
-
186
- Each command item declares its effect and availability. The current route's
187
- `gate` identifies the decision and authority boundary. Write commands are bound
188
- to the workflow revision; after one succeeds, rerun status instead of reusing
189
- the old command. An external command also declares
190
- `execution.target: agent-host`; execute it as a top-level Agent-host action so
191
- network and credential-store access are not lost inside a restricted child
192
- sandbox.
193
-
194
- ### `allSources("repo")`
40
+ References resolve against `sources/repo/index.yaml`,
41
+ `sources/file/index.yaml`, and `sources/lark/index.yaml`. Register or refresh
42
+ sources through `context source ...`; do not invent snapshot directories.
195
43
 
196
- Reference all repo sources as one collection:
197
-
198
- ```ts
199
- import { allSources } from "@c4a/context";
200
-
201
- const repoSources = allSources("repo");
202
- ```
203
-
204
- Use `allSources("repo")` only when the project should list every registered
205
- repo module. Prefer a specific `source("date", "module")` for extraction phases.
206
-
207
- ## Phases
208
-
209
- Phases declare reads and writes. The runtime can inspect them, dry-run them, and
210
- record per-phase logs.
211
-
212
- The API exposes the current declared workflow only. Declare file/lark sources,
213
- capture phases, prose structure gates, source-bound compile phases, code
214
- extraction phases, review gates, close/build, and packages explicitly. The CLI
215
- then routes work through `context status`, `context run <phase-id>`, `context
216
- review html/apply`, `context close`, `context verify`, and `context build`.
217
-
218
- For Agent and automation output, use `context verify --format json --compact`.
219
- It returns deterministic groups, counts, affected-scope totals, and a few
220
- representative samples instead of repeating every issue. Read the complete,
221
- auditable issue set only when needed with `context verify --view diagnostics
222
- --page-size 25 --format json`; follow its executable pagination command without
223
- inventing overlapping file ranges.
224
-
225
- ### Status declaration coverage
226
-
227
- `context status --format json --view full` includes a `declarationGraph` and
228
- `configurationGaps` for document workflows. Each row reports capture, align,
229
- compile, and Review coverage for a canonical source plus collection. Gaps are
230
- non-blocking before structure confirmation. Once a structure is confirmed,
231
- compile routing is exact: phase selection uses canonical source plus collection,
232
- and candidate progress remains bound to the current `structure_digest`. A
233
- compile phase from another collection is never used as fallback.
234
-
235
- Captured align targets that do not yet have an active confirmed structure are
236
- reported in `pendingStructureTargets`. They remain unfinished even when the
237
- currently active structures have been closed, verified, and built. Missing
238
- compile or Review declarations route to `needs-prose-configuration`; once the
239
- declarations are complete, status returns the exact align investigation command
240
- for the next target. A built package does not freeze the workspace or require a
241
- new workspace for later sources.
242
-
243
- `context status --format json` defaults to the compact workflow route, target,
244
- progress, counts, and aggregated diagnostics. Use `--view full` only when
245
- source, phase, package, and lifecycle inventories are needed for debugging.
246
-
247
- ### Current-conversation managed execution
248
-
249
- `context status --managed --format json` exposes
250
- `executionMode: { mode: "managed", scope: "current-conversation" }` and resolves
251
- eligible human gates into immediate commands. The flag is deliberately absent
252
- from `defineProject`: callers start each workflow evaluation loop with managed
253
- status, then execute the returned revision-bound command unchanged. Returned
254
- commands carry a compact current-conversation marker instead of repeating every
255
- authority. A later process or conversation gets ordinary human-gated behavior
256
- by default.
257
-
258
- Managed Review is atomic and scope-validated:
259
-
260
- ```bash
261
- context review approve-all <collection> --managed --format json
262
- context review approve-all --all --managed --format json
263
- ```
264
-
265
- The default JSON result reports counts and change totals without listing every
266
- candidate id or materialized path. Add `--verbose` only when debugging requires
267
- the complete candidate and page details.
268
-
269
- Managed structure confirmation and Review use only the revision-bound commands
270
- returned by `workflow.current`. Source boundaries and unread source bodies,
271
- external operations, payload validation, deterministic close, and verification
272
- errors are never bypassed.
273
-
274
- For consecutive mechanical routes, the Agent may run:
275
-
276
- ```bash
277
- context run --managed --until blocked-or-complete --format json
278
- ```
279
-
280
- This is a bounded host loop over the same revisioned routes. It stops before
281
- read-only interpretation, project configuration, unresolved authority,
282
- diagnostics, or a non-unique command plan; it does not add another workflow
283
- entry or make semantic decisions.
284
-
285
- ### `captureFile`
286
-
287
- Capture a registered file source into a committed normalized document snapshot.
288
- Default file capture treats `.md` files as document bodies. For MDX
289
- documentation sites that use `_meta.json` route metadata, declare the processor
290
- in `src/index.ts`:
291
-
292
- ```ts
293
- captureFile({ source: docs, processor: mdxJsonDocs() });
294
- ```
295
-
296
- With that processor, `.md` and `.mdx` are document bodies. Included
297
- `_meta.json` files are captured as route metadata assets, surfaced in
298
- `read-plan` / `source-index`, and mechanically projected into
299
- `__context_route_metadata.md` so route facts can be cited as evidence. The route
300
- projection records the canonical extensionless route form instead of treating a
301
- local `.html` URL as the source of truth.
302
-
303
- MDX component text is extracted separately: string props such as `title`,
304
- `label`, `description`, `href`, `to`, and component children are projected into
305
- `__context_mdx_component_text.md` as generated evidence. The original `.mdx`
306
- file remains in the snapshot unchanged. If a documentation page renders body
307
- text only at runtime from application code or remote data, configure that
308
- documentation site as an explicit source boundary instead of hand-writing route
309
- or body facts.
44
+ ## Capture phases
310
45
 
311
46
  ```ts
312
47
  captureFile({ source: docs });
313
- ```
314
-
315
- Phase id:
316
-
317
- ```text
318
- capture:file:<source-name>
319
- ```
320
-
321
- Register the source first with
322
- `context source add file [YYYYMMDD] --module <module> --local <path>`.
323
- The first registration requires `--local`; the registry may later keep `local`
324
- only as a refresh hint while committed snapshots remain verifiable. Multiple
325
- file modules may share one date. When `--module` is omitted, the CLI derives it
326
- from the local file or directory name.
327
-
328
- ### `captureLark`
329
-
330
- Capture a registered Lark / Feishu document source into a committed normalized
331
- Markdown snapshot:
332
-
333
- ```ts
48
+ captureFile({ source: docs, processor: mdxJsonDocs() });
334
49
  captureLark({ source: handbook });
335
50
  ```
336
51
 
337
- Embedded resources are materialized with deterministic defaults. Video remains
338
- reference-only unless a project opts into bundling, and byte limits prevent an
339
- unexpected document from expanding the workspace without bound:
340
-
341
- ```ts
342
- captureLark({
343
- source: handbook,
344
- resources: {
345
- videos: "bundle",
346
- maxBytesPerResource: 20 * 1024 * 1024,
347
- maxTotalBytes: 200 * 1024 * 1024,
348
- },
349
- });
350
- ```
351
-
352
- Phase id:
353
-
354
- ```text
355
- capture:lark:<source-name>
356
- ```
357
-
358
- Register each source with
359
- `context source add lark [YYYYMMDD] --module <module>` and exactly one identity
360
- flag: `--url`, `--doc-token`, or `--wiki-token`. Multiple documents may share
361
- one date batch; when `--module` is omitted, the CLI derives an opaque,
362
- credential-safe module id. Capture reads the
363
- remote document through the CLI runner as structured Docx XML. Context keeps a
364
- redacted XML audit asset, projects supported blocks deterministically into
365
- readable Markdown, and materializes required inline resources such as images,
366
- attachments, Sheets, Bases, whiteboards, diagrams, and synced blocks. Navigation
367
- resources and default video capture remain explicit references. The projection
368
- does not infer or summarize document meaning. Its fidelity and resource reports close discovered blocks
369
- against converted and intentionally skipped blocks and reports evidence
370
- completeness separately from Markdown projection quality. Unknown non-empty XML
371
- blocks receive a generic, auditable, non-interactive projection and do not block
372
- downstream work. A remote whiteboard or diagram explicitly confirmed as deleted
373
- is preserved as an unavailable-resource notice with
374
- `document.resource.source-missing` and a warning. An embedded resource whose
375
- export is explicitly rejected as `authorization/permission_denied` is retained
376
- the same way with `document.resource.permission-denied`. Missing scopes,
377
- unresolved external-resource identity, retryable failures, and unclassified
378
- authorization errors remain evidence errors and prevent downstream Review.
379
- Snapshot files live under `sources/lark/<date>/` as sibling document files
380
- tracked by one compact date-level `manifest.json`. Each module keeps one raw
381
- `source.xml`, one consolidated `capture-report.json`, and its actual downloaded
382
- or structured resources under `assets/<module>/materialized/`; it does not emit
383
- one descriptor file per embedded resource. Access credentials and transient
384
- signed media URLs are not written into the workspace.
385
-
386
- Approved resource bytes are projected to content-addressed
387
- `knowledge/assets/<kind>/` paths. KB build copies selected resources to
388
- `others/assets/<kind>/` inside the package and rewrites page links. See
389
- [Lark Resource Materialization](../guides/lark-resources.md) for the complete
390
- resource table and storage lifecycle.
391
-
392
- Use a typed document reference in project declarations:
393
-
394
- ```ts
395
- const handbook = source("20260712", "user-manual", { type: "lark" });
396
- const localDocs = source("20260712", "local-manual", { type: "file" });
397
- ```
398
-
399
- ### `alignProse`
52
+ Capture only creates a deterministic readable snapshot. Classification,
53
+ partitioning, authoring, Candidate creation, and Review belong to the selected
54
+ Markdown Indexer.
400
55
 
401
- Open the prose structure gate for document evidence:
56
+ ## `customPhase`
402
57
 
403
58
  ```ts
404
- alignProse({
405
- source: docs,
406
- collection: "architecture",
59
+ customPhase("project:refresh-catalog", async (ctx) => {
60
+ await ctx.ensureSources();
407
61
  });
408
62
  ```
409
63
 
410
- `collection` is an internal knowledge classification, not a package directory.
411
- Package build maps `codeindex`/`business`/`product` to `wikis/`,
412
- `architecture`/`sop`/`faq`/`decision`/`incident` to `guides/`,
413
- `standards`/`test` to `rules/`, and `feats` to `feats/`. The complete output
414
- contract is documented in [Package Outputs](../guides/package-outputs.md).
415
-
416
- When `source("name")` is type-neutral, the SDK may declare
417
- `align:source:<source-name>:architecture`; the CLI resolves it to
418
- `align:file:<source-name>:architecture` or `align:lark:<source-name>:architecture` after
419
- reading the registry.
420
-
421
- Align is a gated workflow. It produces and validates a structure draft, not
422
- final approved body:
423
-
424
- ```bash
425
- context run align:file:<source-name>:architecture --view read-plan --format json
426
- context run align:file:<source-name>:architecture --view source-index --compact --format json
427
- context run align:file:<source-name>:architecture --view span-detail --span <source-ref> --format json
428
- context run align:file:<source-name>:architecture --view span-text --span <source-ref> --format json
429
- context run align:file:<source-name>:architecture --view existing-knowledge --query <title-or-stable-ref> --format json
430
- context run align:file:<source-name>:architecture --view schema --format json
431
- context run align:file:<source-name>:architecture --view semantic-rules --format json
432
- context run align:file:<source-name>:architecture --validate --input <structure.yaml> --format json
433
- context run align:file:<source-name>:architecture --view diagnostics --input <structure.yaml> --format json
434
- context run align:file:<source-name>:architecture --view structure-summary --input <structure.yaml> --format json
435
- context run align:file:<source-name>:architecture --stage --input <structure.yaml> --format json
436
- ```
437
-
438
- When `workflow.current.batch` is present, several independent document slots
439
- can be prepared in one Agent pass and validated or staged through one command:
440
-
441
- ```yaml
442
- schema: context.prose.structure-batch.v1
443
- items:
444
- - phase_id: align:file:<source-a>:architecture
445
- input: .tmp/agent-payloads/<source-a>-structure.yaml
446
- - phase_id: align:file:<source-b>:architecture
447
- input: .tmp/agent-payloads/<source-b>-structure.yaml
448
- ```
449
-
450
- ```bash
451
- context run --batch-input .tmp/agent-payloads/prose-structure-batch.yaml --validate --format json
452
- context run --batch-input .tmp/agent-payloads/prose-structure-batch.yaml --stage --managed --format json
453
- ```
454
-
455
- Batch preflight validates every payload before writing. Stage writes ready
456
- slots serially; it does not merge documents or decide their semantic shape.
64
+ Use it for project orchestration that does not publish knowledge or bypass the
65
+ Indexer lifecycle. Declare stable reads/writes when the phase has them.
457
66
 
458
- Align results expose a recommended `payload_target.path` under
459
- `.tmp/agent-payloads/`. Agents should use it for transient structure inputs and
460
- may remove the file after a successful stage. The CLI continues to accept an
461
- explicit alternative path; this is an authoring convention, not validation.
462
-
463
- For the ordinary path, `read-plan` is a complete authoring packet: it includes
464
- the payload contract, a budgeted canonical source-ref map, exact source-body
465
- resources, and a direct `--stage` command. Read the bodies, author the payload,
466
- and run that stage command. Request `source-index` only when the packet reports
467
- omitted refs, and request `existing-knowledge` only when reusing or checking an
468
- approved identity. The separate schema and validate views are optional
469
- diagnostic tools, not required lifecycle steps.
470
-
471
- `--validate`, `--stage`, and `--confirm` are mutually exclusive operations. An
472
- `--input` without an operation is rejected unless the selected view explicitly
473
- consumes that input. Deterministic boundary repairs run internally before the
474
- result is returned. `self_healed` includes input/output Section counts, the
475
- number of original Sections split, and structural reason codes. Stage performs validation before writing and returns the
476
- same diagnostics on failure; in managed mode, a valid stage also confirms the
477
- structure. Successful standalone validation returns a stage command with the
478
- same file path. JSON run output keeps `next_action` first;
479
- schema and full reports stay behind explicit Views, while `--verbose` restores
480
- the full phase result and repeated contracts. Long diagnostics return a compact
481
- first page plus an exact diagnostics continuation command.
482
-
483
- Validation returns `state: ready | repair-required | invalid`. Only `ready`
484
- sets `valid: true` and may proceed to stage. `error_free: true` with
485
- `state: repair-required` means no error diagnostic remains, but a declared
486
- confirmation blocker still requires repair; it is not a successful result.
487
-
488
- `existing-knowledge` is the authoring-time lookup for approved identities. It
489
- returns stable NodeRefs, ViewRefs, titles, tags, collections, and section counts
490
- without exposing workspace storage paths. `--query` performs deterministic
491
- case-insensitive exact/prefix/substring matching; `--collection`,
492
- `--node-type`, `--page-size`, and the returned continuation command narrow or
493
- page the same View. Use it after reading source evidence and before introducing
494
- a new Node identity. Structure validation remains the final duplicate gate.
495
-
496
- Align and compile evidence results include `semantic_rules`. Its `required`
497
- array is the rule subset selected for the current judgment, with a selection
498
- reason and content digest for each rule. `handle`, `digest`, and
499
- `rules_version` are stable cache checks: reuse a loaded ruleset only while its
500
- content remains in the active context and both handle and digest still match.
501
- After context compaction, resume the paginated `semantic-rules` View for the
502
- returned required subset; a handle alone does not imply that the rule text is
503
- still available.
504
-
505
- Document evidence boundaries are deterministic rather than semantic.
506
- `source-index` and `chunks` mark Markdown AST blocks with
507
- `boundary_role: "markdown-ast-block"` and `section_candidate: true`.
508
- `span-text`/`span-detail` mark each returned page as
509
- `range_role: "transport-page"` and `section_candidate: false`; pagination line
510
- ranges are never structure boundaries. Structure validation blocks repeated
511
- fixed-width line grids that cut through AST blocks and reports sections that
512
- cross multiple heading paths, without classifying document topics.
513
-
514
- After capture, the capture phase itself exposes collection-neutral `read-plan`,
515
- `source-index`, `span-detail`, `span-text`, and other read-only evidence views.
516
- Status selects `route.document.classification-required` until every captured
517
- target has an evidence-backed, user-confirmed align declaration. Align then
518
- adds `schema` and `structure-summary` for structure work. Agents should not
519
- scan `sources/` or `.tmp` to invent evidence. They may read only the exact
520
- source-body files selected as required resources by the current Route; those
521
- files carry stable content digests and must be read in full before a receipt is
522
- reported. Read all required direct paths, then execute the Route's single
523
- `resources.after_read.command`; the CLI writes and carries the merged receipt
524
- set without requiring Agent-authored JSON. That acknowledgement response
525
- already contains the re-evaluated `workflow.current`, so no additional status
526
- command is needed.
527
-
528
- Generated Context Views use the same content-addressed rule. Materialization
529
- returns a receipt-set path and an exact post-read command. Read the complete
530
- file, then execute that command; unchanged content remains current across
531
- workflow revisions, while write and external commands still require the exact
532
- current revision.
533
-
534
- Compile `read-plan`, `blockers`, and `diagnostics` Views are workspace-read-only
535
- and may run concurrently. Compile `--validate`, compile `--stage`, structure
536
- confirmation, Review apply, and close are serial operations.
537
-
538
- Structure payloads use `schema_version: "context.structure.v1"` and canonical
539
- `file:` / `lark:` `#span` source refs. A one-file-to-one-page plan is represented
540
- as ordinary `nodes[]` and `views[]` in the structure. It does not bypass
541
- structure confirmation or compile. Continuity applies to each Section, while one View/Page may
542
- contain multiple independently retrievable continuous Sections. Deterministic
543
- boundary splitting is applied internally during validate/stage; it is not a
544
- separate Agent-authored payload or approval step.
545
-
546
- ### `compileProse`
547
-
548
- Compile confirmed prose structure into reviewable source-bound draft pages:
549
-
550
- ```ts
551
- compileProse({
552
- source: docs,
553
- collection: "architecture",
554
- });
555
- ```
556
-
557
- When `source("name")` is type-neutral, the SDK may declare
558
- `compile:source:<source-name>:architecture`; the CLI resolves it to
559
- `compile:file:<source-name>:architecture` or `compile:lark:<source-name>:architecture` after
560
- reading the registry.
561
-
562
- Phase id:
563
-
564
- ```text
565
- compile:file:<source-name>:architecture
566
- compile:lark:<source-name>:architecture
567
- ```
568
-
569
- Compile requires confirmed CLI-managed lifecycle structure. It freezes the
570
- current structure for the compile round; if the user wants to change nodes,
571
- section ownership, or relationships, return to the align/structure gate.
572
-
573
- Common commands:
574
-
575
- ```bash
576
- context run compile:file:<source-name>:architecture --view read-plan --format json
577
- context run compile:file:<source-name>:architecture --validate --format json
578
- context run compile:file:<source-name>:architecture --stage --format json
579
- context run compile:file:<source-name>:architecture --view diagnostics --format json
580
- ```
581
-
582
- Compile validates the complete confirmed source/collection slot before writing
583
- any candidate, then materializes the slot atomically. Section bodies are
584
- source-mirrored from the confirmed spans; the Agent does not create a separate
585
- compile-actions payload. Each canonical source plus collection remains an
586
- independent structure slot. When other captured align targets remain pending,
587
- status routes to those slots before opening one collection-level Review
588
- payload. `context close` is blocked while a planned View is unprepared, still
589
- draft, or rejected without a structure revision.
590
-
591
- Relationships stay in `structure.yaml` typed edges in current output; compile
592
- does not infer relationships or inject relation markers into verbatim body.
593
-
594
- ### `extractTs`
595
-
596
- Extract exported TypeScript / JavaScript / TSX / JSX symbols into draft candidates:
597
-
598
- ```ts
599
- extractTs({
600
- source: componentLib,
601
- collection: "codeindex",
602
- });
603
- ```
604
-
605
- Options:
606
-
607
- | Field | Meaning |
608
- |---|---|
609
- | `source` | `source("date", "module")` for one repo module |
610
- | `collection` | Code extraction uses `"codeindex"` |
611
- | `include` | Optional glob list inside the selected source; default is `["src/**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}"]` |
612
- | `mode` | `"exports"` (default) traces public exports from automatic or configured entries; `"scan"` uses every file matched by `include` as an entry root |
613
- | `entries` | Optional source-relative entry files for `"exports"` mode. They override `package.json` entry detection and live only in the Context project configuration |
614
- | `exportedOnly` | Defaults to `true` in `"exports"` mode and `false` in `"scan"` mode |
615
- | `indexUnits` | Stable module/index plans used for ownership, capability and per-unit scale checks. A single-source exports-only package gets a compatible public-contract default; scan, collection and custom extraction require an explicit plan before formal writes |
616
- | `transform` | Optional markdown transform function or functions |
617
-
618
- An explicit index unit records production intent rather than parser settings:
619
-
620
- ```ts
621
- extractTs({
622
- source: componentLib,
623
- collection: "codeindex",
624
- indexUnits: [{
625
- id: "component-public-api",
626
- inputSources: ["20260712/component-lib"],
627
- outputOwner: "component-lib",
628
- moduleType: "sdk-library",
629
- moduleTypes: ["sdk-library"],
630
- facets: ["public-api", "plugin-extension"],
631
- moduleTypeEvidence: ["package.json exports and src/index.ts public entry"],
632
- documents: ["README.md", "docs/public-api.md"],
633
- outputProfile: "public-api-reference",
634
- responsibility: "Document stable exported component contracts.",
635
- entries: ["src/index.ts"],
636
- pageKinds: ["module-map", "public-contract"],
637
- protocols: [],
638
- dependencies: [],
639
- exclusions: ["src/internal/**", "src/generated/**"],
640
- lifecycle: "authoritative",
641
- sourceOfTruth: "src/index.ts",
642
- capability: "complete",
643
- }],
644
- });
645
- ```
646
-
647
- `inputSources` names registered evidence sources; `outputOwner` is the one
648
- stable page owner used for accounting and navigation. `capability` is
649
- `"complete"`, `"project-adapter"`, or `"material-required"`. The last value
650
- stops the Route until the plan is narrowed or reliable source material is
651
- provided.
652
-
653
- `moduleType` is the primary compact classification. `moduleTypes` may add other
654
- applicable archetypes for a hybrid module, while `facets` records composable
655
- behaviors such as routing, protocol consumption, events, persistence, plugins,
656
- release, or cross-module chains. `moduleTypeEvidence` records the inspected
657
- paths that support the classification. Classify first, then read the matching
658
- Route-provided code-index templates, and only then finish the extraction plan.
659
- `documents` contains exact source-relative Markdown paths read for that plan;
660
- Context compares it with discovered module documents instead of treating a
661
- source-code comment as documentation coverage.
662
- `lifecycle` is `"authoritative"`, `"generated"`, `"mirrored"`, `"legacy"`,
663
- or `"vendored"`; derived sources normally use `"provenance-only"` rather
664
- than duplicating reader-facing pages. These are generic project facts, not
665
- framework names inferred by the CLI.
666
-
667
- `moduleType`, `moduleTypes`, `facets`, `outputProfile`, `lifecycle`, and
668
- `capability` are runtime-validated closed values. Supported output profiles are
669
- `module-map`, `application-map`, `protocol-index`, `service-boundary`,
670
- `runtime-map`, `public-api-reference`, `command-map`, `adapter-contract`,
671
- `module-registry`, `cross-module-flow`, and `provenance-only`.
672
-
673
- `extractTs()` projects one candidate page per selected symbol, and each source
674
- can belong to only one of its index units. Use `extractCustom()` for aggregated
675
- maps, registries, protocol indexes, cross-module flows, or multiple candidate
676
- owners over one source; custom candidates declare their owning `module`.
677
-
678
- `source` is the only package/module boundary. `include` narrows files inside
679
- that source; it does not select a second module. Standard packages can omit
680
- `entries` and use `package.json` `exports`, `main`, or `bin` detection. For a
681
- non-standard package, configure `entries` in the Context project instead of
682
- editing the source repository:
683
-
684
- ```ts
685
- extractTs({
686
- source: componentLib,
687
- collection: "codeindex",
688
- include: ["src/**/*.ts"],
689
- entries: ["src/api.ts"],
690
- });
691
- ```
692
-
693
- When the intended knowledge scope is every declaration in the selected files
694
- rather than a public export graph, use `mode: "scan"`. Scan mode does not accept
695
- `entries`; `include` supplies its file roots. Because scan mode can expand
696
- internal declarations into a symbol catalog, it requires an explicit
697
- `indexUnits` plan before formal extraction.
698
-
699
- Entry failures use the stable machine code `NO_ENTRY_DETECTED`. This includes
700
- `entries: []`, exports mode with no detected/configured entry, and scan mode
701
- with no files matched by `include`; these cases never succeed silently.
702
-
703
- TypeScript extraction reads the selected module's `tsconfig.json` or
704
- `jsconfig.json`. JSONC comments/trailing commas, local or installed `extends`,
705
- `compilerOptions.baseUrl`, and `compilerOptions.paths` are used for export
706
- tracing and internal dependency relations, so aliases such as `@/*` resolve to
707
- their source files.
708
-
709
- In monorepos, make each package/subdirectory a module boundary. Register the
710
- chosen package path with `context source add repo [YYYYMMDD] --module <module> --local <package-dir>` and
711
- reference it with `source("<date>", "<module>")`.
712
- Do not use `include` to choose a
713
- package from a larger monorepo source.
714
-
715
- Use `context source inspect <date>/<module>` to list detected module/package
716
- boundaries before choosing the source. Use `context run <phase-id> --dry-run
717
- --format json` to check the resolved modules, file counts, symbol counts, and
718
- candidate estimate before writing the ignored lifecycle candidate ledger. The dry-run
719
- preview also includes `knowledgeTree` and `knowledgePathExamples`, which show
720
- where approved Markdown will land after review apply.
721
- Its module and total summaries distinguish `discoveredFiles`, `analyzedFiles`,
722
- `skippedFiles`, `symbols`, and `relations`. Module summaries also expose the
723
- resolved `entryFiles`, exported/internal symbol counts, and a structural
724
- `candidateKinds` count. These fields describe extractor output only; the CLI
725
- does not infer which symbols are meaningful to a particular product or
726
- audience. Modules with skipped files include the deterministic traversal
727
- reason, such as files not reachable from exports-mode entries.
728
-
729
- Before formal extraction, the workflow runs one batch preview for all pending
730
- phases. Each `indexUnits[]` result reports projected Markdown pages, output
731
- profile/owner, content-byte estimates, and risks. Per unit, 0–100 pages is
732
- normal, 101–300 is a warning that may continue, and more than 300 is blocked.
733
- The limit is non-delegatable, including in managed mode. A passing preview is
734
- cached by digest under `.tmp/context-runtime/extract/previews/` and reused by
735
- formal extraction when the source scope, phase declaration, project `src/`,
736
- dependency lock, and preview protocol still match. A missing cache is
737
- recoverable by rerunning the preview. The report includes cache hits,
738
- extractor invocation count, current and projected page counts, changes,
739
- exported/internal distribution, top directories, and advisory large-page
740
- risks; only the 300-page per-unit limit is a hard scale gate.
741
- A batch-total page advisory and quality risks such as a thin custom aggregate
742
- remain report signals and do not create another Gate.
743
-
744
- Phase id shape:
745
-
746
- ```text
747
- extract:<source-name-or-repo>:codeindex
748
- ```
749
-
750
- Codegraph extraction has two execution policies:
751
-
752
- - `context run <phase-id>` is the Agent/user default. The first run sends every
753
- code symbol to Review. Later runs preserve unchanged approved symbols and send
754
- only `add`, `update`, and `remove` deltas to Review. After every phase result,
755
- the Agent re-evaluates `context status --format json`; only
756
- `workflow.current` decides whether Review is now required.
757
- - `context run <phase-id> --auto-promote` is the explicit CI/CD path. It is valid
758
- only for `phase.extract.ts` codeindex phases, applies deterministic code deltas
759
- without Review, refreshes deterministic close when approved knowledge changed,
760
- then runs project verification. Close or verification errors make the command
761
- fail; JSON output reports applied/materialized/removed counts plus a `close`
762
- state of `refreshed`, `current`, or `not-required`. Package build remains a
763
- separate pipeline step; existing package outputs are reported stale.
764
-
765
- This policy never auto-promotes architecture, business, decision, test, or
766
- other semantic knowledge. Agents must not infer a human gate from a phase-local
767
- result. Human gates and their inspection/resolution Actions are exposed only by
768
- `workflow.current`.
769
-
770
- Approved codeindex sections use the local evidence form
771
- `src-N#symbol:<file>:<symbol>:<kind>@<digest>`. The file segment makes reverse
772
- lookup exact when multiple files contain the same symbol name, kind, and digest;
773
- the complete ref remains opaque to agents. New pages keep only top-level
774
- `candidate_fingerprint` and do not emit `code_origin`.
775
-
776
- ### `extractCustom`
777
-
778
- Use a project-owned extractor when code facts cannot be represented by the
779
- TypeScript symbol extractor, for example a language-specific parser or an
780
- aggregated repository protocol:
67
+ ## Packages
781
68
 
782
69
  ```ts
783
- extractCustom({
784
- id: "extract:service:protocol",
785
- sources: [service],
786
- collection: "codeindex",
787
- indexUnits: [{
788
- id: "service-protocol",
789
- inputSources: ["20260811/service"],
790
- outputOwner: "service",
791
- moduleType: "api-service",
792
- moduleTypes: ["api-service", "adapter"],
793
- facets: ["protocol-provider", "protocol-consumer", "cross-module-chain"],
794
- moduleTypeEvidence: ["src/protocol.ts registration and src/handler.ts dispatch"],
795
- outputProfile: "protocol-index",
796
- responsibility: "Document the stable service protocol boundary.",
797
- entries: ["src/protocol.ts"],
798
- pageKinds: ["protocol-index"],
799
- protocols: ["declared service protocol"],
800
- dependencies: [],
801
- exclusions: ["generated/**"],
802
- lifecycle: "authoritative",
803
- capability: "project-adapter",
804
- }],
805
- extract: async ({ sources }) => {
806
- const serviceRoot = sources.find((item) => item.name === "20260811/service")?.absolutePath;
807
- if (serviceRoot === undefined) throw new Error("service source is not materialized");
808
- const protocolEvidence = inspectProtocol(serviceRoot);
809
- return {
810
- candidates: [{
811
- nodeRef: "service/protocol",
812
- kind: "protocol",
813
- visibility: "exported",
814
- module: "service",
815
- evidence: [protocolEvidence],
816
- sections: [{
817
- id: "contract",
818
- kind: "contract",
819
- title: "Provided contract",
820
- markdown: renderContract(serviceRoot),
821
- evidence: [protocolEvidence],
822
- }, {
823
- id: "operations",
824
- kind: "operation",
825
- title: "Operations",
826
- markdown: renderOperations(serviceRoot),
827
- evidence: inspectOperations(serviceRoot),
828
- }, {
829
- id: "handoff",
830
- kind: "handoff",
831
- title: "Implementation handoff",
832
- markdown: renderHandoff(serviceRoot),
833
- evidence: inspectHandoff(serviceRoot),
834
- }],
835
- review: {
836
- title: "Service protocol",
837
- summary: "Aggregated protocol boundary.",
838
- signals: ["source-backed"],
839
- reason: "Review the project-owned extraction.",
840
- },
841
- }],
842
- }},
70
+ kbPackage({
71
+ name: "component-kb",
72
+ template: "src/package-templates/kb",
73
+ select: { collections: ["codeindex", "architecture"] },
843
74
  });
844
- ```
845
-
846
- `sources` is the complete CLI-resolved repo scope for the phase. Resolve files
847
- from `sources[].absolutePath`; do not embed a local or remote Agent checkout
848
- path. Every candidate section and edge carries structured `evidence`; the CLI validates that evidence against
849
- the declared sources, creates canonical `source_ref` values, writes the symbol
850
- index, candidate ledger and Review snapshots atomically, and records a phase
851
- fingerprint. Evidence-scoped section `kind` values satisfy the selected output
852
- profile's semantic coverage contract. A cross-module flow also requires at
853
- least one source-backed structured edge. `context status` therefore treats this phase exactly like another
854
- pending code extraction target, and Review can verify snapshot freshness
855
- without a placeholder `extractTs` phase.
856
-
857
- Each `sections[].markdown` value is Section body content only; do not copy the
858
- template heading into it. Context renders `sections[].title` and rejects nested
859
- reader headings at the SDK boundary so empty template chapters cannot leak into
860
- knowledge. Evidence `symbol` and `kind` are canonical-ref tokens and cannot
861
- contain `:` or `@`; exact qualified signatures remain reader-facing prose.
862
-
863
- `indexUnits` is also the batch scale and ownership contract. Candidate
864
- `module` must match one declared unit id or output owner. Older callbacks that
865
- omit `indexUnits` remain compatible: Context groups candidates by `module` and
866
- marks the plan as inferred. Once explicit units exist, an unmatched or
867
- multiply-owned candidate blocks formal extraction instead of being guessed.
868
- An inferred plan can be previewed for migration diagnostics, but formal writes
869
- require the project to declare stable units and owners.
870
75
 
871
- For a large adapter, `candidates` may be an `AsyncIterable` instead of an
872
- array. Context consumes it incrementally and stops retaining full candidates
873
- for an index unit after the 301st item proves that the unit is blocked. Array
874
- callbacks remain supported and are reported as `legacy-preview`.
875
-
876
- An optional generic `inspect` adapter can return source-backed module, entry,
877
- protocol, dependency, lifecycle, and source-of-truth findings before candidate
878
- collection. It may also return capability gaps tied to declared index-unit ids;
879
- those gaps enter the one non-delegatable capability Gate. Internal framework
880
- meaning stays in the project adapter and its referenced material.
881
-
882
- The CLI also runs a lightweight structural probe before every custom preview.
883
- It recognizes TypeScript symbols, React Router routes, Go symbols, Rush
884
- workspace structure, and source-owned protocol schemas from generic manifests
885
- and paths. The preview exposes all detected probes in
886
- `inspection.structuralProbes` and records `structuralCoverage` on each index
887
- unit. Candidate evidence must cover every probe applicable to the selected
888
- output profile. Coverage is based on source-backed evidence paths, not Markdown
889
- page count, so one aggregate page can pass while an entry-only static module
890
- card cannot.
891
-
892
- For a single-source index unit, Context also scans every represented language
893
- family and Markdown/MDX file after the unit's declared exclusions. The adapter's
894
- `eligibleFileTargets` and `eligibleLoc` must cover that independent baseline.
895
- Configuration files may be evidence, but a hand-picked evidence list cannot be
896
- reused as the source or LOC denominator. Cross-module-flow units remain scored
897
- against their declared entry, protocol, operation, and handoff boundaries rather
898
- than treating several repositories as one source-code page.
899
-
900
- The same baseline discovers conventional sibling page entries, route-register
901
- calls in Go router files, and exported receiver operations when a Go handler is
902
- the declared service source of truth. Every discovered identity must appear in
903
- the target-symbol and boundary denominators. An aggregate page may summarize
904
- these identities, but an adapter cannot list one representative sibling and
905
- silently omit the rest.
906
-
907
- The extractor returns knowledge semantics (`nodeRef`, rendered Markdown,
908
- Review summary and source-backed evidence). It must not write `knowledge/`,
909
- `.tmp/context-runtime/lifecycle/candidates.jsonl`, extraction fingerprints or
910
- Review snapshots directly. Context owns those files and preserves rejected and
911
- unchanged-approved decisions across reruns.
912
-
913
- #### Optional structural extractors
914
-
915
- For the manifest-to-capability decision and unsupported-language extension
916
- boundary, read [Code Extractor Selection](./code-extractors.md) before declaring
917
- the phase.
918
-
919
- `extractCustom()` may consume optional community packages without making them
920
- Context CLI dependencies:
921
-
922
- ```ts
923
- import { indexGoRepository } from "@c4a/extract-go";
924
- import { extractCustom } from "@c4a/context";
925
-
926
- extractCustom({
927
- id: "extract:service:codeindex",
928
- sources: [service],
929
- collection: "codeindex",
930
- extract: async ({ projectRoot }) => {
931
- const facts = await indexGoRepository(resolveServiceCheckout(projectRoot));
932
- return { candidates: buildServiceCandidates(facts) };
933
- },
76
+ llmsPackage({
77
+ name: "component-context",
78
+ template: "src/package-templates/llms",
79
+ select: { collections: ["codeindex"] },
934
80
  });
935
81
  ```
936
82
 
937
- Available structural libraries include:
938
-
939
- - `@c4a/extract-go`: Go declarations, imports, calls, and common HTTP routes;
940
- - `@c4a/extract-rush`: Rush projects, tags, entries, dependencies, and owners;
941
- - `@c4a/extract-ts`: TypeScript extraction and `extractReactRouterRoutes()`.
942
-
943
- The packages return syntax and repository facts only. They do not classify
944
- product meaning, choose candidate identities, or write lifecycle state. The
945
- knowledge project owns that mapping. Context CLI does not auto-install these
946
- packages and does not expose a built-in Go or Rush phase. Detection does not
947
- execute or replace an optional parser; it makes the matching parser contract
948
- and its evidence coverage auditable before candidate writes.
83
+ Package selection reads approved `knowledge/` only. `dist/` is generated and
84
+ may be rebuilt; it is not an authoring source.
949
85
 
950
- ### `reviewValidity`
86
+ ## Indexer registry
951
87
 
952
- Declare the review step for a collection:
88
+ The Agent and CLI maintain `src/indexers.yaml` through typed proposals and
89
+ Review gates. Each selected Indexer binds requirements and scopes to one
90
+ primary Provider, with optional declared layers or composers. Provider code
91
+ must return the current Indexer result protocol; it must not write Candidate,
92
+ knowledge, or Review files directly.
953
93
 
954
- ```ts
955
- reviewValidity({ collection: "codeindex" });
956
- ```
957
-
958
- Declare one review gate for all current draft collections:
959
-
960
- ```ts
961
- reviewValidity({ scope: "all" });
962
- ```
963
-
964
- Phase id:
965
-
966
- ```text
967
- review:codeindex:validity
968
- review:all:validity
969
- ```
970
-
971
- The review HTML and apply flow are CLI-owned.
972
-
973
- This phase marks a human review gate when current candidates exist. Agents
974
- should run `context review html <collection> --open --format json` or `context
975
- review html --all --open --format json`, confirm the returned `opened` field,
976
- and wait for the user-copied payload. They should not run the phase as an
977
- automatic approval step or synthesize a payload themselves.
978
-
979
- One batch-wide path is explicit current-conversation fully managed authority.
980
- In that mode, follow the `context status --managed` route to
981
- `context review approve-all ... --managed`; the CLI validates the exact current
982
- scope before applying one default-approved decision.
983
-
984
- Ordinary mode has a separate user-confirmed escape path for environments where
985
- the Review report cannot be opened. Do not advertise it in the initial Review
986
- prompt. After the user reports that limitation, the exact conversation phrase
987
- `强制批准` authorizes only the current Route's revision-bound
988
- `context review approve-all ... --force` command. Other generic approval or
989
- continue wording does not invoke it.
990
-
991
- The gate is batch-scoped: prose waits for every planned View across all active
992
- structure slots and every declared `pendingStructureTargets` item in the round;
993
- codeindex waits for every pending extract phase in the confirmed module round.
994
- Candidate count/hash therefore describes the complete current batch rather than
995
- one page, source slot, or module. Deterministic close later merges all active
996
- slots into `knowledge/structure.yaml`, retains only their source, collection,
997
- and consumed snapshot hash as `source_inputs`, then removes the lifecycle slots.
998
-
999
- `status.structureBatch` lists unclassified, configuration-required, pending,
1000
- and active structure slots together with the execution policy for the round.
1001
-
1002
- If the user explicitly asks for an automated or quick approval/rejection path,
1003
- use the scoped quick commands instead of hand-writing a payload:
1004
-
1005
- ```bash
1006
- context review approve <candidate-id> --collection <collection>
1007
- context review reject <candidate-id> --all
1008
- ```
1009
-
1010
- These commands still compute the current review scope and apply the same
1011
- candidate-id gate as the copied payload flow. They are not a replacement for the
1012
- default human review gate.
1013
-
1014
- ### `customPhase`
1015
-
1016
- Use only when the typed factories cannot express a project-specific workflow:
1017
-
1018
- ```ts
1019
- const sample = source("20260712", "sample");
1020
-
1021
- customPhase("custom:20260712/sample:review", async (ctx) => {
1022
- await ctx.ensureSources({ source: sample });
1023
- await ctx.extract.ts(extractTs({ source: sample, collection: "codeindex" }));
1024
- await ctx.review.html(reviewValidity({ collection: "codeindex" }));
1025
- });
1026
- ```
94
+ Detailed Provider protocol and customization guidance is selected by the
95
+ current workflow Route when it is needed.
1027
96
 
1028
- Custom phases are an orchestration escape hatch. Use `extractCustom()` instead
1029
- when project code needs to publish codeindex candidates. The supported runtime
1030
- helpers are:
97
+ ## Persistent versus runtime state
1031
98
 
1032
- - `ctx.ensureSources(...)` for repo source readiness.
1033
- - `ctx.extract.ts(...)` for declared TypeScript extraction.
1034
- - `ctx.review.html(...)` for the human review HTML gate.
99
+ Commit source registries, `src/index.ts`, `src/indexers.yaml`, package templates,
100
+ and approved knowledge. Do not commit `.tmp/context-runtime/`; it contains
101
+ recoverable execution state and is cleaned after a successful close.