@c4a/context-cli 0.7.1 → 0.7.5

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