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