@c4a/context-cli 0.5.29-beta.18 → 0.5.29-beta.21

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 (26) hide show
  1. package/README.md +7 -5
  2. package/cli.js +3995 -2165
  3. package/package.json +1 -1
  4. package/plugin/README.md +4 -3
  5. package/plugin/README_CN.md +4 -3
  6. package/plugin/commands/align.md +28 -4
  7. package/plugin/commands/capture.md +5 -3
  8. package/plugin/commands/compile.md +27 -14
  9. package/plugin/commands/query.md +1 -0
  10. package/plugin/skills/skill-align-workflow/SKILL.md +32 -10
  11. package/plugin/skills/skill-align-workflow/references/gates.md +81 -41
  12. package/plugin/skills/skill-compile-close/SKILL.md +4 -1
  13. package/plugin/skills/skill-compile-draft/SKILL.md +108 -279
  14. package/plugin/skills/skill-compile-draft/references/action-domain-gates.md +34 -0
  15. package/plugin/skills/skill-compile-draft/references/notes.md +34 -0
  16. package/plugin/skills/skill-compile-draft/references/refresh-and-update.md +71 -0
  17. package/plugin/skills/skill-compile-draft/references/structural-challenges.md +76 -0
  18. package/plugin/skills/skill-compile-judge/SKILL.md +1 -1
  19. package/plugin/skills/skill-context-query/SKILL.md +141 -94
  20. package/plugin/skills/skill-drop/SKILL.md +2 -3
  21. package/plugin/skills/skill-semantic-reconcile/SKILL.md +70 -185
  22. package/plugin/skills/skill-semantic-reconcile/references/leakage-and-ownership.md +31 -0
  23. package/plugin/skills/skill-semantic-reconcile/references/mode-semantics.md +41 -0
  24. package/plugin/skills/skill-semantic-reconcile/references/scope-review-and-omit.md +60 -0
  25. package/plugin/skills/skill-semantic-reconcile/references/temporal-and-evidence.md +66 -0
  26. package/plugin/skills/skill-semantic-reconcile/references/user-confirmation.md +71 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@c4a/context-cli",
3
- "version": "0.5.29-beta.18",
3
+ "version": "0.5.29-beta.21",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "context": "./cli.js"
package/plugin/README.md CHANGED
@@ -111,12 +111,13 @@ Measured behavior of Agent + model combinations across instruction following, pa
111
111
  | Agent | Model | Instruction following | Parameter hallucination | Extraction quality |
112
112
  |---|---|---:|---|---:|
113
113
  | Claude | Opus 4.6 / 4.7 | 95 | Almost none | 95 |
114
- | Codex | GPT 5.5 | 95 | Almost none | 91 |
115
- | Cursor | Opus 4.6 / 4.7 | 92 | Almost none | 86 |
114
+ | Claude | Haiku 4.5 | 92 | Occasional | 91 |
115
+ | Codex | GPT 5.5 | 95 | Almost none | 88 |
116
+ | Cursor | Opus 4.6 / 4.7 | 92 | Almost none | 85 |
116
117
  | Claude | DeepSeek V4 | 80 | Frequent | 55 |
117
118
  | Claude | DeepSeek V4 Flash | 65 | Frequent | 50 |
118
119
 
119
- **Recommendation**: prefer Claude Opus or GPT for now. DeepSeek V4 still lags in instruction following and extraction quality and needs further CLI optimization; full DeepSeek V4 adaptation is planned for v0.5.40, targeting an overall score above 90.
120
+ **Recommendation**: prefer Opus or Haiku, GPT for now. DeepSeek V4 still lags in instruction following and extraction quality and needs further CLI optimization; full DeepSeek V4 adaptation is planned for v0.5.40, targeting an overall score above 90.
120
121
 
121
122
  ## About this repository
122
123
 
@@ -109,12 +109,13 @@ bun add -g @c4a/context-cli
109
109
  | Agent | 模型 | 指令遵循度 | 参数幻觉 | 提取质量 |
110
110
  |---|---|---:|---|---:|
111
111
  | Claude | Opus 4.6 / 4.7 | 95 | 几乎无 | 95 |
112
- | Codex | GPT 5.5 | 95 | 几乎无 | 91 |
113
- | Cursor | Opus 4.6 / 4.7 | 92 | 几乎无 | 86 |
112
+ | Claude | Haiku 4.5 | 92 | 偶尔有 | 91 |
113
+ | Codex | GPT 5.5 | 95 | 几乎无 | 88 |
114
+ | Cursor | Opus 4.6 / 4.7 | 92 | 几乎无 | 85 |
114
115
  | Claude | DeepSeek V4 | 80 | 经常 | 55 |
115
116
  | Claude | DeepSeek V4 Flash | 65 | 经常 | 50 |
116
117
 
117
- **建议**:目前优先使用 Claude Opus 或 GPT;DeepSeek V4 在指令遵循与提取质量上仍有差距,需配合 CLI 进一步优化,预计 v0.5.40 完成 DeepSeek V4 适配并达到 90+ 综合得分。
118
+ **建议**:目前优先使用 Opus 或 Haiku、GPT;DeepSeek V4 在指令遵循与提取质量上仍有差距,需配合 CLI 进一步优化,预计 v0.5.40 完成 DeepSeek V4 适配并达到 90+ 综合得分。
118
119
 
119
120
  ## 关于本仓库
120
121
 
@@ -11,7 +11,7 @@ Run the beta.8 align workflow. `/context:align` is the user entrypoint; internal
11
11
  Keep the prompt shape stable: read fixed schema/protocol first, then existing knowledge lookup, then the current source-specific payload. Do not reorder CLI JSON, add timestamps, or invent scratch paths.
12
12
 
13
13
  1. Run `context align --scan --format json`. Use the returned workflow payload name, scope id, digest, and `next_command` / `show_command` fields as the continuation handles.
14
- - If the align-segments payload includes `generation_policy`, use it as the language contract for generated Node titles, summaries, rationale prose, and planned Section wording. Preserve product names, code identifiers, slugs, flags, `block_id` handles, and citation tokens exactly when needed.
14
+ - If the align-segments payload includes `generation_policy`, use it as the language contract for generated Node titles, summaries, rationale prose, and planned Section wording. Source-bound Section wording should stay close to the cited source language when it differs from the workspace language. Preserve product names, code identifiers, slugs, flags, `block_id` handles, and citation tokens exactly when needed.
15
15
  2. Read schema and payloads through CLI only:
16
16
  - `context schema align-segments`
17
17
  - `context schema align-coarse-read`
@@ -22,9 +22,10 @@ Keep the prompt shape stable: read fixed schema/protocol first, then existing kn
22
22
  - `context workflow show --payload align-segments --view segment --unwrap --format json`
23
23
  - `context workflow show --payload align-segments --view blocks --unwrap --format json` (summary only)
24
24
  - `context workflow show --payload align-segments --view windows --unwrap --format json`
25
- - Drill into content only with semantic filters such as `--window <window-id>`, `--heading <prefix>`, `--range <start:end>`, or `--token-budget <n>`.
25
+ - Drill into content only with focused filters such as `--window <window-id|src-N:M>`, `--heading <prefix>`, `--range <start:end>`, or `--token-budget <n>`. `src-N:M` means the M-th window under the `source_alias` shown by `--view windows`.
26
26
  - `--unwrap` only removes the workflow metadata envelope. It does not turn a summary view into detail output.
27
27
  3. Reuse existing knowledge before inventing candidates. For named terms or entities, prefer `context mdrive glossary match <name>` and `context mdrive node list --format json` over direct file reads. Treat `match.kind`, `match.matched`, and `match.rank` as stable lookup hints: exact title/slug/alias hits should usually reuse the existing Node instead of creating another one.
28
+ - Apply packaged `context:skill-align-workflow` Node classification gates before candidate ops and again before finalize: Action requires scale plus process evidence; Entity requires a concrete A/B tag or pure `term`; Domain requires child Nodes; fake Entities need at least two suspicious signals before downgrade.
28
29
  4. Submit generated workflow payloads directly through stdin, preferably as JSON. Use YAML schemas only for reading examples when helpful; generated artifacts should avoid YAML quoting/indentation failure loops. Do not create `/tmp` or workspace scratch files for align payloads. The CLI owns ids, reducer validation, workflow payload storage, and mechanical aggregate. You own semantic discovery, Node type/tag decisions, structure decisions, and user-facing questions.
29
30
  - Save coarse-read with `context align --coarse-read - --format json`.
30
31
  The latest `align-coarse-read` payload is only the most recent checkpoint; durable multi-source reading notes are stored under `align-candidate-ledger.source_readings`.
@@ -37,7 +38,7 @@ Keep the prompt shape stable: read fixed schema/protocol first, then existing kn
37
38
  6. Finalize only with `align-structure-decision`:
38
39
 
39
40
  ```bash
40
- context align --finalize - --digest <segments-digest>
41
+ context align --finalize -
41
42
  ```
42
43
 
43
44
  If finalize returns an `align-finalize-draft` payload, patch that saved draft with JSON Pointer paths from the returned issues instead of resubmitting the full document:
@@ -51,10 +52,32 @@ If finalize returns an `align-finalize-draft` payload, patch that saved draft wi
51
52
  }
52
53
  ```
53
54
 
54
- Submit the patch with `context align --finalize-patch - --payload-digest <draft-digest> --format json`.
55
+ Submit the patch with `context align --finalize-patch - --format json`. Add `--payload-digest` only when you intentionally want an explicit stale guard.
56
+
57
+ After a successful finalize, use a targeted ownership patch for small role corrections only; do not resubmit the whole structure just to move a few blocks between `context_only`, `ignored`, `owned`, or `shared`:
58
+
59
+ ```json
60
+ {
61
+ "schema_version": "align.ownership-patch.v1",
62
+ "base_digest": "sha256:<finalized-ownership-digest>",
63
+ "block_ownership": [
64
+ {
65
+ "block_id": "<block-id>",
66
+ "ownership_role": "owned",
67
+ "owners": ["<node-slug>"],
68
+ "visible_to": ["<node-slug>"],
69
+ "reason": "Why this block is citation evidence for the node."
70
+ }
71
+ ]
72
+ }
73
+ ```
74
+
75
+ Submit it with `context align --ownership-patch - --format json`. Keep `base_digest` in the patch body when you want stale ownership rejection. Use `context schema align-ownership-patch` for the exact shape.
55
76
 
56
77
  If `align-segments.incremental.mode` is `incremental`, the finalize step is a delta merge: submit only the Nodes and block ownership supported by the current scanned sources, and reference previous finalized Nodes when they are parents, dependencies, domain children, owners, or visibility targets. Absence of an old Node or edge is not a delete signal. Do not redeclare an old parent/domain just to attach a new child. `sections[].owner` must be a Node declared in the current payload; previous finalized Nodes can be referenced structurally but do not receive new section plans from this incremental payload. Existing or previously removed Node slugs cannot change `node_type`; `context align --scan --full` does not bypass that guard. Use a new slug for a different type, or retire the old slug through `context drop` or explicit structure correction before re-aligning.
57
78
 
79
+ `nodes[].planned_sections` is the distinct set of Section kinds planned for that Node. List each kind at most once; do not copy `sections[].section_kind` one-for-one when a Node has multiple Sections of the same kind.
80
+
58
81
  For large finalize decisions, use `block_ownership_defaults[]` instead of enumerating every block. Each default names a `source_id` plus the same ownership fields as a block-level entry except `block_id`; the CLI expands it across that source's coverable blocks. Put only exceptions in `block_ownership[]`, which override defaults for their `block_id`. Keep the payload on stdin; do not generate temp JSON files just to list hundreds of ownership rows.
59
82
 
60
83
  If a source is only navigation or placeholder context, keep the Node only when the graph/slug is still useful: set `planned_sections: []`, mark the navigation evidence `context_only` or `ignored` as appropriate, and do not promote relation lines to `owned` just to satisfy citations. Compile close will materialize an empty placeholder Node with no active Sections.
@@ -64,6 +87,7 @@ Do not submit legacy candidate tables, old patch payloads, or full-tree proposal
64
87
  ## Constraints
65
88
 
66
89
  - Node types are `domain`, `entity`, and `action`.
90
+ - Entity tag `term` is mutually exclusive with concrete A/B tags. If both identities matter, create one concrete Entity and one separate term Entity, then connect them later with Section-local `refers_to_nodes[]`.
67
91
  - Document structure uses `nodes[].contains_parent` and `edges[].edge_type = "depends_on"` only.
68
92
  - Section-local references stay in `refers_to_nodes[]`; do not project them into Node edges.
69
93
  - Semantic boundary failures should become downgrade warnings or unresolved items. Do not retry the same semantic judgment in a loop.
@@ -22,7 +22,7 @@ Before any `context capture --code` command, including `--plan`, refresh, or exp
22
22
  sh -c 'CTX_BIN="$(command -v context)" && node -e "const { createRequire } = require(\"node:module\"); createRequire(process.argv[1]).resolve(\"@c4a/extract-ts\");" "$CTX_BIN"'
23
23
  ```
24
24
 
25
- If the check fails, stop the capture task. Tell the user to install the plugin globally with `bun install -g @c4a/extract-ts` (or the exact version from a CLI `agent_hints[].command` if present), then rerun their original `context capture --code ...` command. Do not inline `@c4a/extract-ts`, do not hand-write code snapshots, and do not continue with partial capture.
25
+ If the check fails, stop the capture task and surface the CLI's `agent_hints[]` install command (the CLI picks `npm install -g` or `bun install -g` based on how `context` itself was installed). Ask the user once whether to run that command on their behalf; global installs touch shared state, so explicit confirmation is required before invoking `Bash`. If approved, run the exact command from `agent_hints[0].command`, then retry the original `context capture --code ...` invocation. If declined, leave the command visible so the user can run it manually. Do not inline `@c4a/extract-ts`, do not hand-write code snapshots, and do not continue with partial capture.
26
26
 
27
27
  Invocation note: code capture does not run through `npx`. `context capture --code` resolves `@c4a/extract` and `@c4a/extract-ts` from the installed `@c4a/context-cli` package using Node package resolution, prepares `.context/.cache/aspect-runners/<cacheKey>/c4a-extract-code.mjs`, and executes that wrapper directly. The plugin must therefore be available to the same global install that provides `context`.
28
28
 
@@ -41,7 +41,7 @@ Invocation note: code capture does not run through `npx`. `context capture --cod
41
41
  - Then run `context capture --code` with one repeated `--module <path>` for every selected package. The CLI derives and stores path filtering silently from that selection.
42
42
  - User asks to record conversation material, a decision, a revision intent, or a temporary observation → use note capture:
43
43
  - Classify once as `revision`, `decision`, or `brainstorm`; temporary observations are `brainstorm`. If unclear, ask one clarification.
44
- - For `revision` or `decision`, require an existing target. If missing, run `context query --intent node_search <user words>` and ask the user to confirm a Node or Section before writing.
44
+ - For `revision` or `decision`, require an existing target. If missing, run `context query --intent node_lookup --query "<user words>"` and ask the user to confirm a Node or Section before writing.
45
45
  - Write the body to `context capture --note --intent <intent> --anchor <node-slug>[#<section-id>] --input -` for anchored notes, or omit `--anchor` for brainstorm.
46
46
  - For `revision`, organize the stdin Markdown with headings: `旧上下文`, `修改意图`, `新内容`, `验证条件`.
47
47
  - For `decision`, organize the stdin Markdown with headings: `议题`, `选项`, `决议`, `理由`.
@@ -69,9 +69,11 @@ Report the CLI output verbatim. If the CLI reports `N sources changed`, suggest
69
69
 
70
70
  Never suggest `/context:compile` when no align plan exists or when the only active source is `aspect:code` raw snapshot data — compile refuses prose-less work and must not be used to hand-build code knowledge.
71
71
 
72
+ If capture is rejected with `agent_hints[].code = "workflow-cross-family-rejected"`, do **not** run `context workflow abandon ...` automatically. First run or ask the user to run `context workflow status --format json` and explain that another workflow is active in this workspace. Continue that workflow when it is the intended task; ask the user before abandoning it when the user wants to discard that in-progress work. If the user expected a different repository/workspace, change to the confirmed workspace root before retrying capture.
73
+
72
74
  ### Missing dependency recovery
73
75
 
74
- If the CLI returns `agent_hints[]` with `code: "capture-code-typescript-plugin-missing"`, stop. Surface the hint to the user and use `agent_hints[0].command` as the install command if the user asks you to install it for them.
76
+ If the CLI returns `agent_hints[]` with `code: "capture-code-typescript-plugin-missing"`, stop and surface the hint. Ask the user once for permission to run `agent_hints[0].command` (the CLI has already picked the correct package manager — `npm install -g` or `bun install -g` — based on how `context` itself was installed). If approved, run that exact command via `Bash` and then retry the original capture; if declined, leave the command visible for manual install. Never substitute a different package manager or version.
75
77
 
76
78
  If the CLI prints a missing-dependency error like `lark-cli not installed`, walk the user through installation:
77
79
 
@@ -13,7 +13,7 @@ The agent protocol itself still delegates to internal packaged procedures.
13
13
 
14
14
  ## Your task
15
15
 
16
- Synthesise the finalized align plan into knowledge through semantic CLI operations. The agent produces compile draft JSON per Node; the CLI owns storage, rendering, verification, and workflow payload persistence. Read workflow payloads with `context workflow show`; write through `context compile`, `context reconcile`, and `context mdrive` operations, never through direct workspace file tools.
16
+ Synthesise the finalized align plan into knowledge through semantic CLI operations. If the user explicitly authorized托管/全自动/delegated mode at the start of this conversation, create the compile workflow with `--delegated`; otherwise stay in manual/default mode. The agent produces compile draft JSON per Node; the CLI owns storage, rendering, verification, and workflow payload persistence. Read workflow payloads with `context workflow show`; write through `context compile`, `context reconcile`, and `context mdrive` operations, never through direct workspace file tools.
17
17
 
18
18
  Naming convention:
19
19
 
@@ -26,7 +26,13 @@ Modes:
26
26
  - **Default (no flag)** — draft plan + semantic reconciliation + apply writes + close.
27
27
  - **`--plan`** (opt-in when `$ARGUMENTS` contains `--plan`) — per Node, run `context compile --draft <slug> --input - --plan` so the CLI validates stdin draft content without writing active knowledge; surface a user-facing change list (new knowledge, replaced knowledge, unchanged knowledge, and why) while keeping internal Section ids / source refs in details only when needed, then **stop at the end of the per-Node loop — do NOT run close**. The user re-runs `/context:compile` without `--plan` to apply; that run does the real writes + close.
28
28
 
29
- Language policy: your explanatory prose and final reports follow the user's conversation language. Compile draft `body`, Node-facing summaries, and generated knowledge follow `NodeContext.generation_policy.language` when the CLI provides it; preserve product names, code identifiers, CLI flags, slugs, `block_id` / `source_ref` tokens, and exact quoted evidence as printed. CLI stdout/stderr, the canonical `processing <slug>` lines, paths, slugs, block ids, source refs, issue codes, flags, and command names stay as printed.
29
+ Delegated workflow mode:
30
+
31
+ - If the user explicitly authorized托管/全自动/delegated mode at the start of this conversation, add `--delegated` to the first compile workflow-creating command, preferably `context compile --scan-changes --delegated --format json`. Do not add it for vague "continue" / "继续" permission.
32
+ - `--delegated` is a workflow-level authorization, not a per-review override. It only lets the CLI auto-accept low-risk weak support when hard facts are present; unsupported evidence, missing hard facts, type drift, schema errors, ownership/structure challenges, and destructive gates still block.
33
+ - Never hand-author `decided_by: delegated_agent`; the CLI injects it only inside a delegated compile workflow.
34
+
35
+ Language policy: your explanatory prose and final reports follow the user's conversation language. Node titles, summaries, and user-facing draft explanations follow `NodeContext.generation_policy.language` when the CLI provides it. Source-bound compile draft `content` should stay close to the cited source language when it differs from the workspace language; do not translate cited English facts into Chinese just to match the workspace. Preserve product names, code identifiers, CLI flags, slugs, `block_id` / `source_ref` tokens, and exact quoted evidence as printed. CLI stdout/stderr, the canonical `processing <slug>` lines, paths, slugs, block ids, source refs, issue codes, flags, and command names stay as printed.
30
36
 
31
37
  Stable prompt/output policy: keep fixed protocol, schema, mount matrix, and workspace lookup context before per-Node payloads. For repeated Nodes, use the same command order and consume CLI JSON as-is. Do not add current timestamps, random ids, storage paths, or host absolute paths to draft payloads or reports unless the CLI explicitly returned them as semantic workspace facts.
32
38
 
@@ -34,14 +40,14 @@ Preflight:
34
40
 
35
41
  1. Run `context doctor`; output-align group must be green. If it reports missing aligned knowledge, tell the user to run `/context:align` and stop. Incremental cache group warnings are informational here; only output-align errors block compile.
36
42
  2. Run `context mdrive workspace stats --format json`, `context source list --format json`, and `context status --format json`; record the before counts and `STATUS.semantic.refreshed_source_pending_compile.source_ids[]`.
37
- 3. Run `context compile --scan-changes --format json` and parse the JSON as `COMPILE_WORKSET`. `--scan-changes` is the only workset scan flag; `--plan` is reserved for draft validation.
43
+ 3. Run `context compile --scan-changes --format json` and parse the JSON as `COMPILE_WORKSET`. If delegated workflow mode is explicitly authorized, run `context compile --scan-changes --delegated --format json` for this first scan instead. `--scan-changes` is the only workset scan flag; `--plan` is reserved for draft validation.
38
44
  - If `context workflow status --format json` has `current: null` but `last_published` is present, continue with `context compile --scan-changes`; the published finalized ownership is still the workspace structure truth. Use `context workflow list --format json` only when you need lineage/history diagnostics.
39
45
  - Compile JSON may include `source_finalize`; use it as lineage for the finalized ownership that produced the current Node set and citation ownership.
40
46
  - If `COMPILE_WORKSET.reason` is `no-changed-nodes` and there are no refreshed sources pending compile, report `no changed nodes`; stop before invoking the draft procedure, running any draft command, or running close.
41
47
  - If `COMPILE_WORKSET.status` is `unknown-input`, continue conservatively using the Nodes listed in `COMPILE_WORKSET.nodes`; keep the `unknown_inputs[]` reasons in the final report.
42
48
  - Otherwise process only `COMPILE_WORKSET.nodes`, preserving the CLI order. Per-Node `processing <slug>` echoes must match this order.
43
49
 
44
- Review input rule: normal compile flow passes the prepare payload by digest: `context reconcile review --prepare-digest <digest> --decisions - --view status`. Never pass prepare files or hand-edited review output to apply; once review writes a ready artifact for the current workflow scope, plain `context reconcile apply` consumes it.
50
+ Review input rule: normal compile flow reads the current prepare payload automatically: pass decisions with `context reconcile review --decisions - --view status`. Add `--prepare-digest` only when you intentionally want an explicit stale guard. Never pass prepare files or hand-edited review output to apply; once review writes a ready artifact for the current workflow scope, plain `context reconcile apply` consumes it.
45
51
 
46
52
  Semantic decision schema discovery: run `context schema semantic-decisions` for JSON, or `context schema semantic-decisions --format yaml` for readable YAML. Do not infer it from memory, and do not hand-edit review output; once `context reconcile review` writes a ready review artifact for the current workflow scope, plain `context reconcile apply` consumes it without re-reading any decisions file.
47
53
 
@@ -54,7 +60,7 @@ Refreshed-source loop:
54
60
  1. If `STATUS.semantic.refreshed_source_pending_compile.source_ids[]` is non-empty, process each source id before the per-Node draft loop.
55
61
  2. Run `context reconcile prepare --mode refresh --source <source-id> --format json`. Feed stdout to packaged `context:skill-semantic-reconcile`; the output includes `workflow_payload.digest` for review. Do not reconstruct the semantic decision shape from memory.
56
62
  - The prepare output omits refresh sections whose evidence block hash is unchanged. If it returns a single `status: "unchanged"` / `change_status: "unchanged"` item, report that no semantic refresh decisions are needed for that source and continue with the filtered compile workset.
57
- 3. Pass the skill output to `context reconcile review --prepare-digest <prepare-digest> --decisions - --view status`. Use stdout for readiness/issues/questions; apply reads the ready review artifact from the workflow scope. Resolve questions exactly like the per-Node loop, including `support_confirmation`, `scope_review_required`, and `omit_confirmation` handling.
63
+ 3. Pass the skill output to `context reconcile review --decisions - --view status`. Use stdout for readiness/issues/questions; apply reads the ready review artifact from the workflow scope. Resolve questions exactly like the per-Node loop, including `support_confirmation`, `scope_review_required`, and `omit_confirmation` handling.
58
64
  4. Default mode only: run plain `context reconcile apply` after `context reconcile review` returns `ready_to_apply: true`; the CLI loads the unique ready review for the current workflow scope. If questions were answered, rerun review on the updated decisions to refresh the ready artifact, then run `context reconcile apply` again. In `--plan` mode, stop after review and report the not-written refresh decisions.
59
65
  5. After all refreshed sources are applied in default mode, run `context compile --scan-changes --format json --ignore-source <source-id>` with one `--ignore-source` flag for each refresh-applied source. Use that filtered result for the per-Node loop. This does not rebuild section fingerprints early; it only removes Nodes whose remaining changed blocks came entirely from sources already handled by refresh reconciliation. If a Node still has changed blocks from other sources, unknown inputs, or full-context reasons, keep it in the ordinary per-Node loop.
60
66
 
@@ -62,15 +68,15 @@ Per-Node loop:
62
68
 
63
69
  Process Nodes sequentially. `/context:compile` may cover a multi-Node workset, but each Node must finish its own `context → draft → prepare → review → apply` loop before you apply another Node. Do not run multiple Node draft/reconcile/apply chains in parallel or bury several Node failures inside one shell batch. Capture/align can be broad; compile write decisions must be per-Node and complete.
64
70
 
65
- 1. For every workset Node, run `context compile --context <slug> --format json`. If the refreshed-source loop applied any source, append the same `--ignore-source <source-id>` flags used for the filtered workset. The JSON stdout is a compact summary with `node_context_payload.scope_id` and `node_context_payload.digest`. First inspect citation handles with `context workflow show --payload node-context --scope <scope-id> --digest <digest> --view source-refs --unwrap --format json` or `context compile --source-refs <slug> --format json`; only read the full durable NodeContext once when you are ready to pass its returned `.value` object to the draft skill. NodeContext is derived only from finalized ownership: `primary_evidence` and citation-eligible `shared_evidence` may be cited; `context_only` and every secondary shared snippet are background only and must not be cited. If NodeContext includes `generation_policy`, apply it to every generated title, summary, draft `body`, and user-facing draft explanation; do not default to English scaffolding when the workspace language is not English. `context compile --context <slug> --request-full-text <block_id> --format json` may expose full text for inspection, but it does not promote secondary shared evidence into citation eligibility; if the block should support this Node, emit `pending_ownership_challenge` or `structure_challenge` instead of writing a Section. When the workset requires full context, the NodeContext payload has `incremental.status: "full-context"` with the `unknown_inputs[]` reasons from the same entrypoint. `incremental.locator_only_changes[]` entries with `agent_action: "none"` are close-time maintenance only; do not draft them. The CLI stores the durable NodeContext and coverage candidates as workflow payloads, not root scratch files. Do not expand the context with direct file tools; the NodeContext payload is the evidence boundary. Prefer citation-eligible refs for citeable evidence and treat `context_only` as background. Do not repeatedly slice saved NodeContext JSON manually; use the compact `source-refs`, `summary`, and coverage views returned by the CLI.
66
- 2. Invoke packaged `context:skill-compile-draft` and follow its procedure to emit draft JSON. Do not reconstruct the draft shape from memory. Section writes use `body` plus optional `rewrite`; new Sections do not need `section_id`. Cite raw via `source_refs: [...]` chosen from `raw_snippets[].source_ref`; use a single-element array for one citation. The CLI rejects singular `source_ref` and quoted-evidence fields with canonical repair hints. If a note or changed raw snippet should be reviewed but intentionally not written, emit `op: "skip"` with the relevant `source_refs: [...]`; a bare skip is only for deterministic no-op cases. If a NodeContext contains only navigation or placeholder evidence (`Parent` / `Children` / `Related` / `Relations`, "no detailed content", etc.), emit `skip`; do not create a low-value `description` Section from that navigation line just to satisfy the workflow.
67
- 3. Fast path: pass the draft to `context compile --node-cycle <slug> --input - --accept-safe-defaults --format json`. This validates the draft, prepares reconcile, reviews mechanically safe defaults, and applies only when no semantic judgment remains. If stdout returns `status: "applied"`, continue to the next Node. If it returns `status: "review-required"`, use the returned `prepare` / `review` handles and continue with the manual path below; do not rerun the earlier context/source-ref reads.
68
- 4. Manual path: pass the draft to `context compile --draft <slug> --input - --plan --prepare --format json`. This validates schema, source refs, and mount matrix, stores the compile draft as a workflow payload, and prepares the semantic reconcile payload without writing active knowledge. Default stdout is a compact prepare summary; use it to inspect readiness and capture `workflow_payload.digest` / `scope_id`. If semantic judgment is needed, load the full prepare payload with `context workflow show --payload prepare --scope <scope-id> --digest <digest> --unwrap --format json` and feed that full payload to packaged `context:skill-compile-judge`. The judge output is the decision input for `context reconcile review`; keep `skill-semantic-reconcile` for refresh/drop or non-compile reconcile flows. For triage-only inspection, use `context workflow show --payload prepare --scope <scope-id> --digest <digest> --view issues --unwrap --format json`; add `--status unsupported`, `--status weak`, `--item-id <claim-id>`, or `--page-size <n>` instead of expanding huge prepare payloads. If all pending items are mechanically safe defaults, prefer `context reconcile review --prepare-digest <digest> --scope <scope-id> --accept-safe-defaults --view status` instead of invoking the skill. If most items are safe and only a few need explicit decisions, combine `--accept-safe-defaults` with `--decisions -` and submit only those explicit decisions. If the CLI returns draft revision hints, use `context compile --draft-status <slug> --format json` and `context compile --draft-patch <slug> --input - --payload-digest <digest> --plan` so only the affected action is revised, then rerun `context compile --draft ... --plan --prepare`. On hard rejection after a draft session is saved, read `context compile --draft-status <slug> --format json`, patch only the failed actions, and retry.
69
- 5. Review the prepared context before accepting defaults. Treat lexical `source_support` as a diagnostic; final support and relation judgment belong to `context:skill-compile-judge`, which must compare only listed candidates and include the same-source-ref multi-kind semantic-role check. Treat `temporal_prior` and candidate `temporal_disposition` as context for your rationale only; they do not change `default_decision` or make merge/supersede mechanically safe. If the prepare output has `items: []`, use its `next_decisions_template` as the decisions document for review; do not pass the whole prepare context as `--decisions`.
71
+ 1. For every workset Node, run `context compile --context <slug> --format json`. If the refreshed-source loop applied any source, append the same `--ignore-source <source-id>` flags used for the filtered workset. The JSON stdout is a compact summary with workflow payload handles; do not extract digests by hand. First inspect citation handles with `context compile --source-refs <slug> --format json` or `context workflow show --payload node-context --view source-refs --unwrap --format json`; only read the full durable NodeContext once when you are ready to pass its returned `.value` object to the draft skill. NodeContext is derived only from finalized ownership: `primary_evidence` and citation-eligible `shared_evidence` may be cited; `context_only` and every secondary shared snippet are background only and must not be cited. If NodeContext includes `generation_policy`, apply it to generated titles, summaries, and user-facing explanations; for source-bound draft `content`, prefer the cited source language when it differs. Do not default Node titles/summaries to English scaffolding such as "How-To", "Strategy", or "Architecture" when the workspace language is not English. `context compile --context <slug> --request-full-text <block_id> --format json` may expose full visible evidence text for inspection, including primary evidence, but it does not promote secondary shared evidence into citation eligibility; if the block should support this Node, emit `pending_ownership_challenge` or `structure_challenge` instead of writing a Section. When the workset requires full context, the NodeContext payload has `incremental.status: "full-context"` with the `unknown_inputs[]` reasons from the same entrypoint. `incremental.locator_only_changes[]` entries with `agent_action: "none"` are close-time maintenance only; do not draft them. The CLI stores the durable NodeContext and coverage candidates as workflow payloads, not root scratch files. Do not expand the context with direct file tools; the NodeContext payload is the evidence boundary. Prefer citation-eligible refs for citeable evidence and treat `context_only` as background. Do not repeatedly slice saved NodeContext JSON manually; use the compact `source-refs`, `summary`, and coverage views returned by the CLI.
72
+ 2. Invoke packaged `context:skill-compile-draft` and follow its procedure to emit draft JSON. Do not reconstruct the draft shape or Section classification rules from memory; the draft skill carries the canonical kind priority, mount matrix, examples, and reflection gates. Section writes use `content` plus optional `summary`; new Sections do not need `section_id`, and the op is exactly `op: "add"` because compile-draft `actions[]` already targets Sections. Do not use align-style op names such as `add_section` or `propose_section`. Cite raw via `source_refs: [...]` chosen from `raw_snippets[].source_ref`; use a single-element array for one citation, and use multiple refs only when the Section content actually consumes all of them. The CLI may auto-narrow over-wide citations and leaves removed refs uncovered. The CLI rejects retired `body` / `detail` / `raw`, singular `source_ref`, and quoted-evidence fields with canonical repair hints. If a note or changed raw snippet should be reviewed but intentionally not written, emit `op: "skip"` with the relevant `source_refs: [...]`; a bare skip is only for deterministic no-op cases. If a NodeContext contains only navigation or placeholder evidence (`Parent` / `Children` / `Related` / `Relations`, "no detailed content", etc.), emit `skip`; do not create a low-value `description` Section from that navigation line just to satisfy the workflow.
73
+ 3. Fast path: pass the draft to `context compile --node-cycle <slug> --input - --accept-safe-defaults --format json`. This validates the draft, prepares reconcile, reviews mechanically safe defaults, and applies only when no semantic judgment remains. If stdout returns `status: "applied"`, continue to the next Node. If it returns `status: "partial-applied"` or `status: "review-required"`, use the returned `prepare` / `review` handles and continue with the manual path below for only the remaining questions/issues; do not rerun the earlier context/source-ref reads.
74
+ 4. Manual path: pass the draft to `context compile --draft <slug> --input - --plan --prepare --format json`. This validates schema, source refs, and mount matrix, stores the compile draft as a workflow payload, and prepares the semantic reconcile payload without writing active knowledge. Default stdout is a compact prepare summary; use it to inspect readiness. If semantic judgment is needed, load the full prepare payload with `context workflow show --payload prepare --unwrap --format json` and feed that full payload to packaged `context:skill-compile-judge`. The judge output is the decision input for `context reconcile review`; keep `skill-semantic-reconcile` for refresh/drop or non-compile reconcile flows. For triage-only inspection, use `context workflow show --payload prepare --view issues --unwrap --format json`; add `--status unsupported`, `--status weak`, `--item-id <claim-id>`, or `--page-size <n>` instead of expanding huge prepare payloads. If all pending items are mechanically safe defaults, prefer `context reconcile review --accept-safe-defaults --view status` instead of invoking the skill. If most items are safe and only a few need explicit decisions, combine `--accept-safe-defaults` with `--decisions -` and submit only those explicit decisions. If the CLI returns draft revision hints, use `context compile --draft-status <slug> --format json` and `context compile --draft-patch <slug> --input - --plan` so only the affected action is revised, then rerun `context compile --draft <slug> --plan --prepare --format json` with no `--input`; it reloads the saved patched draft. On hard rejection after a draft session is saved, read `context compile --draft-status <slug> --format json`, patch only the failed actions, and retry.
75
+ 5. Review the prepared context before accepting defaults. Treat lexical `source_support` as a diagnostic; final support and relation judgment belong to `context:skill-compile-judge`, which must compare only listed candidates and include the same-source-ref multi-kind semantic-role check. Do not copy raw text merely to raise matched-term counts; there is no separate default `evidence-echo` warning, and preserved prose/bullets are valid only when they are active user-facing knowledge. Treat `temporal_prior` and candidate `temporal_disposition` as context for your rationale only; they do not change `default_decision` or make merge/supersede mechanically safe. If the prepare output has `items: []`, use its `next_decisions_template` as the decisions document for review; do not pass the whole prepare context as `--decisions`.
70
76
  - If `agent_hints[]` contains `compact-source-low-coverage` or `dense-source-low-coverage`, return to the same compile draft and add actions for the suggested uncovered evidence before semantic review. Treat the reported coverage count (`covered/total`, remaining snippets) as a required self-check, not polish. A supported first quote only proves that one action is valid; it does not prove the Node is complete.
71
- - If close later reports unresolved coverage, first use `context compile --context <slug> --cover-uncovered-only --format json` to start a targeted repair draft that contains only unresolved candidates. If every unresolved candidate in that node-scoped payload is intentionally excluded for the same reason, use `context compile --coverage-skip-unresolved --coverage-disposition-node <slug> --payload-digest <digest> --reason "<reason>"` instead of hand-writing a long disposition JSON. Use targeted `coverage-disposition` only when candidates need different outcomes.
72
- 6. Pass the judge skill output to `context reconcile review --prepare-digest <prepare-digest> --decisions - --view status`. Use stdout for compact readiness/issues/questions. If questions are returned, ask the user in business language and convert unresolved `ask_user` items into final actions before applying. For `support_confirmation`, use `question.group_key` when present: group only questions that share that key and are all ordinary summary/compression checks; ask once with a compact list of claims and cited evidence. If the user confirms the group, keep each final write action and add `decided_by: user`. Do not group questions that add new facts, have missing hard facts, or have different source/evidence boundaries. If review reports unsupported evidence, revise the draft or rerun the judge with corrected source_refs rather than forcing a decision. For `scope_review_required`, run `context:skill-semantic-reconcile` once more over the prepare context and current decisions before asking the user; if it still cannot resolve the scope, ask the user. For `omit_confirmation`, ask the user; only a confirmed no-write answer may become `action: omit` with `decided_by: user`. Never mark `decided_by: user` on your own; auto mode or permission to continue is not user confirmation.
73
- 7. Default mode only: run plain `context reconcile apply` after `context reconcile review --prepare-digest ... --view status` returns `ready_to_apply: true`; the CLI applies the unique ready review for the current workflow scope. If questions were answered, rerun review on the updated decisions, then run `context reconcile apply` again. This writes active knowledge, verifies, and records the semantic ledger. In `--plan` mode, stop after review and report the not-written decisions.
77
+ - If close later reports unresolved coverage, first use `context compile --context <slug> --cover-uncovered-only --format json` to start a targeted repair draft that contains only unresolved candidates. If every unresolved candidate in that node-scoped payload is intentionally excluded for the same reason, use `context compile --coverage-skip-unresolved --coverage-disposition-node <slug> --reason "<reason>"` instead of hand-writing a long disposition JSON. Use targeted `coverage-disposition` only when candidates need different outcomes.
78
+ 6. Pass the judge skill output to `context reconcile review --decisions - --view status`. Use stdout for compact readiness/issues/questions. If questions are returned, ask the user in business language and convert unresolved `ask_user` items into final actions before applying. For `support_confirmation`, use `question.group_key` when present: group only questions that share that key and are all ordinary summary/compression checks; ask once with a compact list of claims and cited evidence. If the user confirms the group, keep each final write action and add `decided_by: user`. Do not group questions that add new facts, have missing hard facts, or have different source/evidence boundaries. If review reports unsupported evidence, revise the draft or rerun the judge with corrected source_refs rather than forcing a decision. For `scope_review_required`, run `context:skill-semantic-reconcile` once more over the prepare context and current decisions before asking the user; if it still cannot resolve the scope, ask the user. For `omit_confirmation`, ask the user; only a confirmed no-write answer may become `action: omit` with `decided_by: user`. Never mark `decided_by: user` on your own; auto mode or permission to continue is not user confirmation.
79
+ 7. Default mode only: run plain `context reconcile apply` after `context reconcile review --view status` returns `ready_to_apply: true`; the CLI applies the unique ready review for the current workflow scope. If questions were answered, rerun review on the updated decisions, then run `context reconcile apply` again. This writes active knowledge, verifies, and records the semantic ledger. In `--plan` mode, stop after review and report the not-written decisions.
74
80
  8. Persistent failure → stop and surface the full rejection list; never edit rendered files to bypass.
75
81
 
76
82
  Close (default mode only — skip entirely in `--plan` mode):
@@ -81,6 +87,8 @@ Close (default mode only — skip entirely in `--plan` mode):
81
87
 
82
88
  `context compile --close` may archive explicit debug scratch files through the CLI-owned output lifecycle. Normal compile state lives in workflow-scoped payloads. Current align state is internal CLI state, not a file protocol. Do not move, delete, or archive workspace output files yourself; the CLI owns that lifecycle.
83
89
 
90
+ Close only projects finalized Nodes that materialize as a CLI-written knowledge article or as an explicit no-write placeholder declared by align with `planned_sections: []`. A compile skip action records reviewed no-write evidence, but it does not by itself turn an arbitrary finalized Node into a placeholder.
91
+
84
92
  In plan mode, your final report is the aggregated user-facing change list across all Nodes + "re-run `/context:compile` without `--plan` to apply"; do not run `context compile --close` or `context verify` (they only make sense against a real write).
85
93
 
86
94
  Never claim success unless `context compile --close` exited 0 and `context verify` is green. The only exception is the `no-changed-nodes` gate, where you report that compile stopped before draft and no files were written. Never hand-write rendered knowledge, index, or changelog files — the CLI is the sole writer.
@@ -93,7 +101,12 @@ context compile --draft billing-api --input - --plan --prepare --format json <<'
93
101
  "schema_version": "compile.draft.v2",
94
102
  "target_node": "billing-api",
95
103
  "actions": [
96
- { "op": "skip", "reason": "no new evidence in changed snippets" }
104
+ {
105
+ "op": "add",
106
+ "kind": "description",
107
+ "content": "Billing API exposes invoice lookup and payment capture endpoints.",
108
+ "source_refs": ["src-1#billing-api L10-18@7a6f4c9d2e10"]
109
+ }
97
110
  ]
98
111
  }
99
112
  JSON
@@ -15,6 +15,7 @@ Naming convention:
15
15
  Use packaged `context:skill-context-query` end to end for `$ARGUMENTS`.
16
16
 
17
17
  This command is intentionally a thin entrypoint. Do not duplicate the query protocol here; the skill owns the hit/miss/select handling, supplemental lookup, citation, gap, and broad-query rules.
18
+ The packaged skill also owns scoped orientation filters such as `context query --intent orientation --tag <tag>` / `--domain <slug>`, Node lookup through `context query --intent node_lookup --query "<keyword>"`, Node views through `context query --intent node_view --scope <slug>`, and Section search through `context query --intent section_search --scope <slug> --query "<keywords>"`.
18
19
 
19
20
  Never use direct workspace file tools for local knowledge. Workspace evidence must come from `context query` commands only; the packaged skill may run its documented `context query --intent orientation` or empty `context query` command before querying, but that output is not evidence.
20
21
  Never use Python, Node.js, shell scripts, `ls`, `find`, `rg`, `cat`, or similar ad-hoc commands to inspect `WORKSPACE_DIR`, `.context`, or `/tmp` workflow artifacts while answering a query.
@@ -19,8 +19,8 @@ Run the align workflow through the CLI-owned beta.8 payload chain: scan segments
19
19
  - Retired payloads include candidate tables, decision patches, and full-tree finalize documents.
20
20
  - Existing knowledge is the lookup registry. Use `context mdrive glossary match <name>` / `context mdrive node list --format json` for term/entity reuse; do not read `knowledge/**` and do not create a separate registry file.
21
21
  - Keep cache-friendly prompt order: fixed protocol and schemas first, existing knowledge lookup second, source-shared payload views third, current candidate batch last. Preserve CLI JSON order and do not add timestamps, random ids, scratch paths, or host paths to generated payloads.
22
- - `align-segments.generation_policy` is the workspace language contract for generated Node titles, summaries, rationale prose, and planned Section wording. Preserve product names, code identifiers, slugs, flags, `block_id` handles, and `source_ref` tokens exactly when needed.
23
- - Gate rules for `domain` and `action` proposals are in `references/gates.md`.
22
+ - `align-segments.generation_policy` is the workspace language contract for generated Node titles, summaries, rationale prose, and planned Section wording. Source-bound Section wording should stay close to the cited source language when it differs from the workspace language. Preserve product names, code identifiers, slugs, flags, `block_id` handles, and `source_ref` tokens exactly when needed.
23
+ - Node type, tag, fake-Entity, `domain`, and `action` gates are in `references/gates.md`.
24
24
  - Coarse-read density and neutral signal rules are in `references/density-profile.md`.
25
25
  - Candidate anomaly handling, `label_hint`, and `llm_slug_hint` reference rules are in `references/candidate-resolution.md`.
26
26
 
@@ -31,27 +31,29 @@ Run the align workflow through the CLI-owned beta.8 payload chain: scan segments
31
31
  Use this only inside `/context:align`.
32
32
 
33
33
  1. Start from `align-segments`.
34
- 2. Inspect it through compact CLI views, not shell parsing: `context workflow show --payload align-segments --view segment --unwrap --format json`, `--view blocks`, and `--view windows`. Read and obey `generation_policy` before authoring any title, summary, rationale, or planned Section wording. The default `blocks` view is a structure summary; drill into content with `--window <window-id>`, `--heading <prefix>`, `--range <start:end>`, or `--token-budget <n>`. `--unwrap` only removes the workflow metadata envelope; it does not change summary/detail behavior.
34
+ 2. Inspect it through compact CLI views, not shell parsing: `context workflow show --payload align-segments --view segment --unwrap --format json`, `--view blocks`, and `--view windows`. Read and obey `generation_policy` before authoring any title, summary, rationale, or planned Section wording. The default `blocks` view is a structure summary; drill into content with `--window <window-id|src-N:M>` (`src-N:M` means the M-th window under `source_alias` src-N from `--view windows`), `--heading <prefix>`, `--range <start:end>`, or `--token-budget <n>`. `--unwrap` only removes the workflow metadata envelope; it does not change summary/detail behavior.
35
35
  3. Query existing knowledge for reusable names before proposing new term/service/system/action Nodes. `context mdrive glossary match <name>` returns deterministic `match.kind`, `match.matched`, and `match.rank`; exact title/slug/alias hits should usually become references to the existing Node, not duplicate candidates.
36
36
  4. Produce coarse-read anchors and neutral content signals as JSON. Pick `density_profile` using `references/density-profile.md`; content signals describe text shape only, not final Node type. Submit the artifact through stdin with `context align --coarse-read - --format json`. The latest `align-coarse-read` payload is only the most recent checkpoint; durable multi-source reading notes live in `align-candidate-ledger.source_readings`. For multiple sources, submit one envelope with `coarse_reads[]`; single-source payloads remain valid.
37
- 5. Produce candidate ops batches as JSON. Before each batch, refresh the Term Entity Boundary in `references/gates.md`; its TTL is one batch or about ten candidates, whichever comes first. Use `local:<name>` only inside the current batch; submit each batch through stdin with `context align --ops - --format json`. `--ledger-digest <digest>` is optional; usually omit it and pass it only when you intentionally want stale-batch rejection for a high-assurance retry. The CLI reducer assigns durable candidate ids. For `merge_into`, `supersede`, and `reject`, include the required `*_label_hint` fields from the visible candidate labels.
37
+ 5. Produce candidate ops batches as JSON. Before each batch, refresh the Node classification gates in `references/gates.md`; their TTL is one batch or about ten candidates, whichever comes first. Use `local:<name>` only inside the current batch; submit each batch through stdin with `context align --ops - --format json`. `--ledger-digest <digest>` is optional; usually omit it and pass it only when you intentionally want stale-batch rejection for a high-assurance retry. The CLI reducer assigns durable candidate ids. For `merge_into`, `supersede`, and `reject`, include the required `*_label_hint` fields from the visible candidate labels.
38
38
  6. Read the CLI-written candidate ledger and aggregate with `context workflow show --payload align-candidate-ledger --view ledger --unwrap --format json` and `context workflow show --payload align-candidate-aggregate --view aggregate --unwrap --format json`. To revisit one source's coarse-read notes, add `--source <source-id>` to the ledger view; candidates do not carry source ids, so add `--status` or `--candidate-id` only when you also need candidate rows. Treat aggregate fields as mechanical statistics and warnings, not semantic recommendations. Review `anomaly_signals[]`; address clear mistakes with another ops batch, otherwise continue. These signals are warnings and do not by themselves block finalizing.
39
39
  7. If the CLI returns `agent_hints[]`, follow them before retrying. Legacy-protocol hints mean the submitted payload/schema is retired; switch to the beta.8 schema named in the hint instead of reshaping old fields.
40
- 8. Before producing `align-structure-decision`, refresh and apply `references/gates.md`: re-run the Term Entity Boundary decision tree, every `action` needs the five action probes plus structured `inference_sources`, and every `domain` needs `scope_blocks`, resolvable `child_refs`, and `grouping_reason`.
41
- 9. Produce `align-structure-decision` as JSON with finalized nodes, `contains_parent`, `depends_on`, and one `block_ownership[]` entry per coverable block. Node titles and summaries must follow the latest `generation_policy` language; do not default to English scaffolding such as "How-To", "Strategy", or "Architecture" when the workspace language is not English. Submit it through stdin with `context align --finalize - --digest <segments-digest>`. Prefer stable `llm_slug_hint` values for `contains_parent_ref`, `from_ref`, `to_ref`, owners, and section owners while the final slug is still being normalized.
40
+ 8. Before producing `align-structure-decision`, refresh and apply `references/gates.md`: classify Node type in order (`action` scale + process evidence, then concrete/term `entity`, then child-bearing `domain`), reject fake Entities only when at least two suspicious signals match, keep `term` separate from concrete A/B tags, and provide required `action_gate` / `domain_gate` fields.
41
+ 9. Produce `align-structure-decision` as JSON with finalized nodes, `contains_parent`, `depends_on`, and one `block_ownership[]` entry per coverable block. Node titles and summaries must follow the latest `generation_policy` language; do not default to English scaffolding such as "How-To", "Strategy", or "Architecture" when the workspace language is not English. Submit it through stdin with `context align --finalize -`; the CLI resolves the current align-segments payload. Prefer stable `llm_slug_hint` values for `contains_parent_ref`, `from_ref`, `to_ref`, owners, and section owners while the final slug is still being normalized.
42
42
 
43
43
  If `align-segments.incremental.mode` is `incremental`, finalize is a delta merge. Submit only the Nodes and ownership supported by the current scanned sources; reference previous finalized Nodes when they are parents, dependencies, domain children, owners, or visibility targets. Absence of an old Node or edge is not a delete signal. Do not redeclare an old parent/domain just to attach a new child. `sections[].owner` must be a Node declared in the current payload; previous finalized Nodes can be referenced structurally but do not receive new section plans from this incremental payload. Existing or previously removed Node slugs cannot change `node_type`; `context align --scan --full` does not bypass that guard. Use a new slug for a different type, or retire the old slug through `context drop` or explicit structure correction before re-aligning.
44
44
 
45
+ `nodes[].planned_sections` is the distinct set of Section kinds planned for that Node. List each kind at most once; do not copy `sections[].section_kind` one-for-one when a Node has multiple Sections of the same kind.
46
+
45
47
  For large finalize decisions, use `block_ownership_defaults[]` instead of enumerating every block. Each default names a `source_id` plus the same ownership fields as a block-level entry except `block_id`; the CLI expands it across that source's coverable blocks. Put only exceptions in `block_ownership[]`, which override defaults for their `block_id`. Keep the payload on stdin; do not generate temp JSON files just to list hundreds of ownership rows.
46
48
 
47
- If a finalized Node is intentionally navigation-only or placeholder-only, set `planned_sections: []` and keep its relation/placeholder blocks as `context_only` or `ignored`; do not assign `owned` evidence or plan a description solely to keep the Node alive. Compile close will create an empty placeholder Node with no active Sections.
49
+ If a finalized Node is intentionally navigation-only or placeholder-only, set `planned_sections: []` and keep its relation/placeholder blocks as `context_only` or `ignored`; do not assign `owned` evidence or plan a description solely to keep the Node alive. This is the expected placeholder-domain shape when the graph/slug is useful but the source has no citation-worthy body content. Compile close will create an empty placeholder Node with no active Sections.
48
50
 
49
51
  Each `block_ownership[]` entry sets `ownership_role` to one of five values, and the **shape of the rest of the entry depends on the role**. Set `ownership_role` first and only include the fields that role requires; surplus fields trigger schema errors. The CLI returns `agent_hints[].correct_shape` with the canonical JSON skeleton on any role/field mismatch — reshape that entry to match it instead of guessing.
50
52
 
51
53
  - `owned`: exactly one slug in `owners[]`, plus `visible_to[]` and `reason`. Do not include `primary_owner`, `context_prefix`, or `question_id`.
52
54
  - `shared`: at least two slugs in `owners[]`, `primary_owner` chosen from those owners (the Node that authors cited Sections from this block; secondaries receive compact context and must request full text or raise an ownership challenge before citing it), `visible_to[]`, `reason`. Do not include `context_prefix` or `question_id`.
53
- - `context_only`: **omit `owners` and `primary_owner` entirely.** Required: `context_prefix` (short summary travelling with citing Sections), `visible_to[]`, `reason`. Do not include `question_id`.
54
- - `ignored`: **omit `owners`, `primary_owner`, `context_prefix`, and `visible_to`.** Required: `reason`. Use for outdated markers, navigation/external-link blocks, and placeholders without independent knowledge. Do not include `question_id`.
55
+ - `context_only`: **omit `owners` and `primary_owner` entirely.** Required: `context_prefix` (short summary travelling with citing Sections), `visible_to[]`, `reason`. Do not include `question_id`. Also use this for **external-URL reference-link blocks** (orphan `[label]: https://...` / `[label]: http://...` definitions, including ByteDance internal hosts and Lark / docs wikis) when no Node in this batch clearly owns the references — the URLs themselves are unique knowledge not duplicated in body prose, so they must stay reachable downstream even if no inline body usage exists. `context_only` keeps those URLs as background only; compile must not cite them as active Sections unless a later ownership patch upgrades the block to `owned` / primary `shared`.
56
+ - `ignored`: **omit `owners`, `primary_owner`, `context_prefix`, and `visible_to`.** Required: `reason`. Use for outdated markers, **intra-workspace navigation lines** (`Parent:` / `Children:` / `Related:` / `Relations:` rows whose targets are other Nodes already represented in the align graph), and placeholders without independent knowledge. **Do not put external-URL reference-link blocks here** — those carry unique URLs that the align graph cannot reconstruct; route them to `context_only` (or `owned` / `shared` if a Node should author a citation-eligible "相关链接" Section). Do not include `question_id`.
55
57
  - `unresolved`: **omit `owners`, `primary_owner`, and `context_prefix`.** Required: `question_id` (matching a top-level `unresolved[].question_id`) and `reason`. Use when classification is blocked by missing evidence.
56
58
 
57
59
  After finalize, a second `context align --finalize` is rejected with `workflow-finalize-locked`; follow the returned `remediation_options[]` instead of resubmitting into the finalized workflow. Use `context workflow list --format json` when you need to audit finalize history.
@@ -67,7 +69,27 @@ Use this only inside `/context:align`.
67
69
  }
68
70
  ```
69
71
 
70
- Submit it with `context align --finalize-patch - --payload-digest <draft-digest> --format json`. If issues remain, patch the remaining issue paths; if validation passes, the CLI commits the finalized workflow artifacts.
72
+ Submit it with `context align --finalize-patch - --format json`. Add `--payload-digest` only when you intentionally want an explicit stale guard. If issues remain, patch the remaining issue paths; if validation passes, the CLI commits the finalized workflow artifacts.
73
+
74
+ After finalize has succeeded, do not resend the full structure just to correct a few block roles. Submit a narrow ownership patch against the current finalized ownership digest:
75
+
76
+ ```json
77
+ {
78
+ "schema_version": "align.ownership-patch.v1",
79
+ "base_digest": "sha256:<finalized-ownership-digest>",
80
+ "block_ownership": [
81
+ {
82
+ "block_id": "<block-id>",
83
+ "ownership_role": "owned",
84
+ "owners": ["<node-slug>"],
85
+ "visible_to": ["<node-slug>"],
86
+ "reason": "Why this block is citation evidence for the node."
87
+ }
88
+ ]
89
+ }
90
+ ```
91
+
92
+ Submit it with `context align --ownership-patch - --format json`. Keep `base_digest` in the patch body when you want stale ownership rejection. Use `context schema align-ownership-patch` when uncertain.
71
93
 
72
94
  Never write raw, cache, knowledge, `/tmp`, or workspace scratch files. Never pipe `context ... --format json` through `jq`, `head`, `tail`, `sed`, `cat`, `2>&1`, Python, Node.js, or shell scripts. Never read host persisted output files such as Claude `tool-results/**`; rerun a narrower `context workflow show` command instead. Never submit old candidate-table, decision-patch, or full-tree payloads.
73
95
 
@@ -1,51 +1,96 @@
1
- # Candidate Validation Gates
1
+ # Node Classification Gates
2
2
 
3
- Use these gates before producing `align-structure-decision`. The CLI may reject malformed gates or downgrade weak `domain` / `action` proposals to `entity`.
3
+ Use these gates before every candidate batch and immediately before `align-structure-decision`.
4
+ Align owns Node type, tag, graph, planned Section, and ownership classification. It does **not** write Section prose.
5
+
6
+ ## Node Type Order
7
+
8
+ Answer in this order and stop at the first match:
9
+
10
+ 1. **Action?** A large executable event / process with both:
11
+ - scale: can support `planned_sections` with at least two distinct Section kinds, or contains at least one child Action;
12
+ - process evidence: explicit steps, phases, trigger -> handling -> result, role collaboration, or repeatable plan. Parallel lists such as "three API modes" are not process evidence.
13
+ 2. **Entity?** A concrete independent subject with retrieval value: deployable code, product/application/system, library/module/CLI/symbol, or an atomic term/pattern.
14
+ 3. **Domain?** A container/scope that groups at least one child Node.
15
+ 4. Otherwise do not create a Node; leave the material for compile as a Section under the owning Node.
16
+
17
+ Good examples:
18
+
19
+ | Type | Examples |
20
+ |---|---|
21
+ | `domain` | "X business domain", "Y technical area", "Z research topic" |
22
+ | `entity` concrete | `@acme/api-server`, `@acme/ui-kit` `Button`, "X sub-application" |
23
+ | `entity` term | "X identifier", "Y business metric", idempotency |
24
+ | `action` | "user submits X request end-to-end flow", "operator executes Y change flow", "team Z release flow" |
25
+
26
+ ## Entity Tag Rules
27
+
28
+ Use `tags` to state what the Entity is. Legal combinations:
29
+
30
+ | Case | Tags |
31
+ |---|---|
32
+ | Runtime/code object | one A tag: `app`, `service`, `lib`, `cli`, `module`, or `symbol` |
33
+ | Product-analysis object | one B tag: `application` or `system` |
34
+ | Code + product object | one A tag plus one B tag |
35
+ | Pure term / pattern | only `term` |
36
+
37
+ `term` is mutually exclusive with A/B tags. React is `[lib]`, not `[lib, term]`; if a separate term entry is useful, create another Entity tagged `[term]` and let compile use Section-local `refers_to_nodes[]`.
4
38
 
5
39
  ## Action Gate
6
40
 
7
- Use `node_type: action` only when the candidate is a user story, runbook, how-to, roadmap, or other planned procedure. Fill both `action_probe` and `action_gate`.
41
+ Use `node_type: action` only after the Node Type Order says action. Fill `action_probe` and `action_gate`.
8
42
 
9
- `action_probe` and `action_gate` use the same five booleans:
43
+ `action_probe` still uses the five schema booleans, but the semantic bar is:
10
44
 
11
45
  | Field | Meaning | Evidence rule |
12
46
  |---|---|---|
13
- | `has_steps_or_phases` | The source contains explicit steps, phases, ordered work, or a procedural sequence. | Hard requirement. Must be directly supported by block evidence. |
14
- | `has_actor_or_role` | A user, system, operator, service, or role performs the work. | May be inferred, but inference must be recorded. |
15
- | `has_outcome_or_goal` | The action has a target result, acceptance condition, or operational goal. | May be inferred, but inference must be recorded. |
16
- | `is_repeatable_or_planned` | The work is repeatable, scheduled, policy-like, or intentionally planned. | May be inferred, but inference must be recorded. |
17
- | `queries_answerable_with_refs` | The resulting Node can answer how/when/who/what-to-do questions from cited blocks. | May be inferred, but inference must be recorded. |
47
+ | `has_steps_or_phases` | Process evidence exists: steps, phases, trigger -> handling -> result, role collaboration, or repeatable plan. | Hard requirement; support it from block evidence. |
48
+ | `has_actor_or_role` | A user, system, operator, service, or role performs the work. | May be inferred; record the source. |
49
+ | `has_outcome_or_goal` | The process has a target result, acceptance condition, or operational goal. | May be inferred; record the source. |
50
+ | `is_repeatable_or_planned` | The work is repeatable, scheduled, policy-like, or intentionally planned. | May be inferred; record the source. |
51
+ | `queries_answerable_with_refs` | The Node can answer how/when/who/what-to-do questions from cited blocks. | May be inferred; record the source. |
52
+
53
+ Do not emit an Action for a single sentence, a one-off conclusion, a short operation, or a parallel enumeration. Those become Sections under the owning Entity or Domain.
54
+
55
+ Action anti-examples:
56
+
57
+ | Candidate | Correct routing |
58
+ |---|---|
59
+ | "migrate to X tool" as one conclusion | `decision` Section under the owning Entity |
60
+ | "component X usage" as one sentence | `description` + maybe `example` under X |
61
+ | "submit -> validate -> generate" as one unexpanded sentence | `spec` Section under X/Y |
62
+ | "three API call modes" | `comparison`, `spec`, or `description` Section; not Action |
18
63
 
19
- `has_steps_or_phases: false` means do not emit an action Node. If the subject has a stable named definition that people can reference, use `entity` with tag `term`. Routing schemes, durable rules, and data-shape descriptions belong inside the matching domain/entity/action Sections (`spec`, `principle`, `decision`, `comparison`, `warning`, and related mounted kinds).
64
+ ## Fake Entity Gate
20
65
 
21
- ## Term Entity Boundary
66
+ A relationship-style title is only suspicious by itself. Downgrade or change type when at least **two** signals are true:
22
67
 
23
- Use `entity` + `tags: [term]` only for a stable named definition. The core content should fit a 1-3 sentence glossary entry answering "what is X?" without if/else branches, steps, trade-offs, or "we choose" reasoning.
68
+ 1. Title contains relationship language such as "X impact on Y", "Y under X", "Y side of X", "X migration", or "X collection".
69
+ 2. No legal Entity tag fits.
70
+ 3. The Node does not stand alone away from its upstream Node.
24
71
 
25
- Decision tree:
72
+ Repairs:
26
73
 
27
- 1. If the subject is a procedure, ordered work, runbook, how-to, or repeated planned operation, use an `action` Node.
28
- 2. If the subject is a concrete product, service, system, app, library, module, CLI, or code symbol, use the matching concrete `entity` tag.
29
- 3. If the content is a rule, risk, design choice, comparison, data shape, durable behavior, or operational detail, do not create a Node for it; place it as a Section under the owning Node.
30
- 4. If the subject is a stable named definition that can be written as a short glossary entry and referenced across documents, use `entity` + `tags: [term]`.
31
- 5. If explaining the subject requires alternatives, steps, condition branches, trade-offs, or "we choose" reasoning, it is not `term`; route it to an owning Section or an `action` Node.
74
+ | Pattern | Repair |
75
+ |---|---|
76
+ | "X impact on Y" | Section under X with `refers_to_nodes: [Y]` |
77
+ | "Y under X condition" | Section under Y; X is a condition in the Section body |
78
+ | "X subsystem migration" | Action only if it clears the Action Gate; otherwise `decision` Section under X |
79
+ | "X error collection" / "X FAQ collection" | `faq` / `incident` Sections under X |
32
80
 
33
- Term boundary TTL: re-run this decision tree before every candidate-ops batch and again immediately before `align-structure-decision`. If you have processed more than one batch or about ten candidates since the last check, treat the previous check as expired.
81
+ ## Domain Gate
34
82
 
35
- Good `term` examples:
83
+ Use `node_type: domain` only for a scope that groups child Nodes. Fill:
36
84
 
37
- - `Data Region`: a named deployment or compliance scope used across documents.
38
- - `IDC` / `Region`: named scope terms with stable definitions.
39
- - `request-id`: a named identifier with a stable meaning.
40
- - `target-region`: a named cookie, header, or routing key.
41
- - `Dynamic Site Acceleration`: a named traffic acceleration category.
85
+ | Field | Meaning |
86
+ |---|---|
87
+ | `scope_blocks[]` | Blocks that describe the scope boundary or grouping. |
88
+ | `child_refs[]` | Candidate ids, local refs, or final slugs for children in the scope. |
89
+ | `grouping_reason` | Why these children belong together under this domain. |
42
90
 
43
- Not `term`:
91
+ If a domain has no resolvable child refs, no clear grouping reason, or only one same-file child without a broader scope, emit an Entity instead.
44
92
 
45
- - cookie-plus-IP routing: a conditional routing scheme; put it in the owning service/system as `spec`.
46
- - shared load-balancer rollout: a design choice with constraints; use `spec`, `principle`, or `decision` under the owning entity.
47
- - six-dimensional resilience matrix: a structured comparison/framework; use a domain/entity `comparison` or `spec` Section.
48
- - CDN scheduling strategy: service behavior and design choices; model the CDN or traffic service as `service` and place the strategy in Sections.
93
+ Scope-name titles such as "X 业务域", "Y 领域", "business domain", or "technical area" are a warning sign when proposed as Entity. Keep them as Entity only when the subject is an atomic term or concrete object; otherwise use Domain with `domain_gate.child_refs`.
49
94
 
50
95
  ## Inference Sources
51
96
 
@@ -80,16 +125,11 @@ Allowed `source_type` values:
80
125
  | `ref-node` | An existing or same-decision Node reference supplies the signal. Include `ref_nodes`. |
81
126
  | `inferred-from-block` | The signal is inferred from block content. Keep the rationale short and concrete. |
82
127
 
83
- Each source must include `rationale` and at least one of `evidence_blocks[]` or `ref_nodes[]`. Do not write free-text-only inference explanations.
128
+ Each source must include `rationale` when inferred and at least one of `evidence_blocks[]` or `ref_nodes[]`.
84
129
 
85
- ## Domain Gate
86
-
87
- Use `node_type: domain` only for a scope that groups multiple child Nodes. Fill:
88
-
89
- | Field | Meaning |
90
- |---|---|
91
- | `scope_blocks[]` | Blocks that describe the scope boundary or grouping. |
92
- | `child_refs[]` | Candidate ids, local refs, or final slugs for children in the scope. |
93
- | `grouping_reason` | Why these children belong together under this domain. |
130
+ ## Final Reflection
94
131
 
95
- If a domain has no resolvable child refs, no clear grouping reason, or only one same-file child without a broader scope, emit an `entity` instead. Weak domain gates are downgraded by finalize and recorded in `audit_warnings`.
132
+ - Entity cannot pick a legal tag, or depends on its upstream title to make sense -> downgrade to Section or change type.
133
+ - Action only supports one Section -> downgrade to Section. The discriminator is scale, not the presence of "step" words.
134
+ - Action "steps" are parallel options/configs -> route to Entity `comparison` / `spec` / `description`.
135
+ - Domain has no children -> delete it or merge it into a larger Domain.