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