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

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@c4a/context-cli",
3
- "version": "0.5.29-beta.16",
3
+ "version": "0.5.29-beta.18",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "context": "./cli.js"
package/plugin/README.md CHANGED
@@ -1,10 +1,12 @@
1
- # C4A Context Advanced Agentic Search Over Compiled Knowledge
1
+ # Agentic Context System Over Compiled Knowledge
2
2
 
3
3
  > [中文版本](./README_CN.md)
4
4
 
5
5
  <p align="center"><img src="./assets/logo.svg" alt="C4A Context" width="180"/></p>
6
6
 
7
- An Agentic Search system built for AI Agents. It pre-compiles Feishu docs, local Markdown, code structure, and hand-curated business material into structured, traceable knowledge, so an agent can perform high-precision search over it through a dedicated CLI.
7
+ An Agentic knowledge system built for AI Agents. It pre-compiles Feishu docs, local Markdown, code structure, and hand-curated business material into structured, traceable knowledge, so an agent can perform high-precision search over it through a dedicated CLI.
8
+
9
+ This repository is the **local standalone build of C4A System**. The full C4A System will add online services with stronger multi-user collaboration support — releasing soon.
8
10
 
9
11
  ## Why C4A Context
10
12
 
@@ -13,25 +15,29 @@ When an AI agent looks up information in a project, it mostly relies on file sea
13
15
  - **Slow retrieval**: the whole repo has to be scanned to locate the relevant piece;
14
16
  - **Context bloat**: large amounts of raw text are pushed into the context window, dragging down downstream reasoning quality.
15
17
 
16
- Vanilla RAG handles basic retrieval, but relying on Embedding-based chunk recall has inherent flaws: **vector models lose key information and distort semantics at both the indexing and retrieval stages, which significantly amplifies LLM hallucination**; recalled chunks are often misaligned with the actual intent, so the agent still has to do a second-pass filter — accuracy has a clear ceiling.
18
+ Vanilla RAG handles basic retrieval, but relying on Embedding-based chunk recall has inherent flaws: **vector models lose key information and distort semantics at both the indexing and retrieval stages, which significantly amplifies LLM hallucination**; meanwhile, the downstream LLM is far better at intent recognition than vector similarity, yet the upstream RAG stage already caps recall quality before the LLM gets to see it overall accuracy is bounded by the upstream pipeline rather than by the model.
17
19
 
18
- C4A Context takes a different path: **drop vector embeddings entirely, and let the LLM itself drive structured knowledge management and precise retrieval**. Each piece of raw material is pre-compiled into a structured knowledge unit (Section) carrying a Fact array, cross-references, and traceable source quotes; the agent then queries that base through dedicated tools and lands on Node / Section-level content directly. Backed by a standardized compile flow and a purpose-built query CLI, the knowledge base reaches a precision close to hand-curated material, and in most scenarios outperforms file search and general-purpose RAG.
20
+ C4A Context takes a different path: **drop vector embeddings entirely, and let the LLM itself drive structured knowledge management and precise retrieval**. Each piece of raw material is pre-compiled into a typed structured knowledge unit (Section, classified as spec / example / warning / faq, etc.) carrying cross-references and traceable source quotes; the agent then queries that base through dedicated tools and lands on Node / Section-level content directly. Compilation runs through a harness-style loop — the CLI orchestrates small-window iterations of knowledge production, so the agent never has to ingest the whole corpus at once; at query time the CLI hits the Section index directly, with zero LLM calls on the runtime path. Backed by a standardized compile flow and a purpose-built query CLI, the knowledge base reaches a precision close to hand-curated material and **significantly outperforms** both file search and general-purpose RAG — benchmark scores approach 100%.
19
21
 
20
22
  ## Where it fits
21
23
 
22
- Best suited to the **long-term maintenance of project knowledge** compile material from different versions and sources into orthogonal structured content (orthogonal meaning: knowledge from each source is non-redundant, has a clear boundary, and can be maintained independently), avoiding uncontrolled knowledge-base growth over time. Particularly fits long-running large projects, multi-team collaboration, and complex business systems with many documentation sources.
24
+ **Producer side long-term project knowledge maintenance**: compile material from different versions and sources into orthogonal structured content (each source non-redundant, with clear boundaries, independently maintainable), so the knowledge base doesn't bloat uncontrollably over time. Particularly suited to long-running large projects, multi-team collaboration, and complex business systems with many documentation sources.
25
+
26
+ **Consumer side — high-reliability agent workflows**: coding, on-call operations, QA, and similar scenarios with zero tolerance for hallucination and a need for stable, high-quality recall — eliminates fabricated agent output.
23
27
 
24
28
  ## Core capabilities
25
29
 
26
30
  C4A Context creates a `.context/` workspace under your project directory (the name is configurable) and provides a complete closed loop:
27
31
 
28
32
  - **Capture** — pull in Feishu docs, local Markdown, code structure, design specs, API specs, and other multi-source business material;
29
- - **Compile** — let the AI process raw material into structured knowledge under a single protocol — not a summary, but a standardized Section with a Fact array, cross-references, and source traceability;
33
+ - **Compile** — let the AI process raw material into structured knowledge under a single protocol — not a summary, but typed Sections (spec / example / warning, etc.) with cross-references and source traceability;
30
34
  - **Query & use** — query local structured knowledge directly from Claude / Cursor / Codex etc., landing on Node and Section precisely; or hand the whole knowledge base to another LLM;
31
35
  - **Knowledge governance** — drop deprecated material and reclaim its derived knowledge in one go; the knowledge base self-checks integrity and self-heals.
32
36
 
33
37
  Day to day, work loops through **capture → compile → query & use → governance**; you don't re-run everything from scratch — update incrementally on demand.
34
38
 
39
+ <p align="center"><img src="./assets/workflow-en.png" alt="C4A Context workflow example: single-doc vs multi-doc batch" width="1280"/></p>
40
+
35
41
  ## Install
36
42
 
37
43
  Every Agent needs the `context` CLI first:
@@ -39,7 +45,7 @@ Every Agent needs the `context` CLI first:
39
45
  ```bash
40
46
  npm i -g @c4a/context-cli
41
47
  # or
42
- bunx @c4a/context-cli
48
+ bun add -g @c4a/context-cli
43
49
  ```
44
50
 
45
51
  Then install the plugin matching the agent you use:
@@ -53,6 +59,8 @@ Then install the plugin matching the agent you use:
53
59
 
54
60
  Once installed, the agent exposes entry points like `/context:*` (Claude) or `/context-*` (Cursor).
55
61
 
62
+ > **Tip — updating the Claude Code plugin**: Claude Code caches the installed plugin locally. When upgrading to a new version, uninstall the old plugin first, run `context clean-cache`, then reinstall — this guarantees the new version takes effect immediately.
63
+
56
64
  ## Manual workflow
57
65
 
58
66
  From your project directory:
@@ -66,16 +74,22 @@ From your project directory:
66
74
 
67
75
  Each step writes readable files and a changelog under `.context/`, so you can review or roll back at any time.
68
76
 
69
- ## Managed workflow
77
+ ## Automated workflow
70
78
 
71
79
  After completing the **Install** step above, you can hand this document to an AI Agent (or an automation harness such as OpenClaw), point it at the project workspace and any existing knowledge base, and let it run the entire flow autonomously — cutting most of the manual work.
72
80
 
73
81
  **Environment**: Claude Opus 4.6+ or Codex 5.5+ is recommended, so the agent can resolve instructions correctly and handle the decision/clarification steps during compile.
74
82
 
75
- **Core managed prompt** — paste directly to the Agent or automation tool:
83
+ **Core automation prompt** — paste directly to the Agent or automation tool:
76
84
 
77
85
  ```
78
- Please initialize a project knowledge base in the current directory (choose Chinese as the language; keep all other parameters as defaults), and run the full knowledge-management flow through the context CLI — including but not limited to: workspace init, multi-source capture, alignment, AI compile, and query validation. For any clarification or decision (source priority, compile-rule tweaks, knowledge-unit classification, etc.), make the call on your own and log every operation, keeping the knowledge base structured and traceable.
86
+ Please initialize a project knowledge base in the current directory (choose Chinese as the language; keep all other parameters as defaults), and run the full knowledge-management flow through the context CLI.
87
+
88
+ Knowledge sources (restrict to these):
89
+ - Feishu docs: https://[URLS]
90
+ - Local files: /local/path/*.md
91
+
92
+ Work includes but is not limited to: workspace init, multi-source capture, alignment, AI compile, and query validation. For any clarification or decision (source priority, compile-rule tweaks, knowledge-unit classification, etc.), make the call on your own and log every operation, keeping the knowledge base structured and traceable.
79
93
  ```
80
94
 
81
95
  > Knowledge building is a long iterative process: it involves many detail-level decisions and clarifications. Automation can take over most of the repetitive work, but cannot fully replace human judgment.
@@ -85,14 +99,28 @@ Please initialize a project knowledge base in the current directory (choose Chin
85
99
 
86
100
  The compiled knowledge base can be packaged for distribution:
87
101
 
88
- - export as a **Skills** package;
89
- - export as **LLMs.txt**;
102
+ - export as a **Skills** package — `context build --format skills-pack`;
103
+ - export as **LLMs.txt** — `context build --format llms`;
90
104
  - [TODO] publish to the **C4A platform** as an MCP service for other AIs to query live;
91
105
  - [TODO] publish as a standalone Plugin knowledge package, with retrieval quality on par with the MCP service and CLI.
92
106
 
107
+ ## Recommended environment
108
+
109
+ Measured behavior of Agent + model combinations across instruction following, parameter hallucination, and extraction quality (scored 0–100):
110
+
111
+ | Agent | Model | Instruction following | Parameter hallucination | Extraction quality |
112
+ |---|---|---:|---|---:|
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 |
116
+ | Claude | DeepSeek V4 | 80 | Frequent | 55 |
117
+ | Claude | DeepSeek V4 Flash | 65 | Frequent | 50 |
118
+
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
+
93
121
  ## About this repository
94
122
 
95
- The contents of this repository are auto-generated and published by the [c4a project](https://github.com/context4ai/c4a) — do not edit by hand. Issues and PRs should go to the c4a monorepo.
123
+ The contents of this repository are auto-generated and published by the [c4a project](https://github.com/context4ai/c4a) — do not edit by hand.
96
124
 
97
125
  The c4a project provides end-to-end infrastructure for knowledge processing and hosting, covering the CLI, the knowledge-management Studio, and MCP services; open-source release is planned for late May 2026.
98
126
 
@@ -1,10 +1,12 @@
1
- # C4A Context Advanced Agentic Search Over Compiled Knowledge
1
+ # Agentic Context System Over Compiled Knowledge
2
2
 
3
3
  > [English](./README.md)
4
4
 
5
5
  <p align="center"><img src="./assets/logo.svg" alt="C4A Context" width="180"/></p>
6
6
 
7
- 专为 AI Agent 打造的 Agentic Search 系统,将飞书文档、本地 Markdown、代码结构、人工整理的业务资料预编译为结构化、可溯源的知识,再让智能体通过专用命令行工具,在这套知识上完成高精度检索。
7
+ 专为 AI Agent 打造的 Agentic 知识系统,将飞书文档、本地 Markdown、代码结构、人工整理的业务资料预编译为结构化、可溯源的知识,再让智能体通过专用命令行工具,在这套知识上完成高精度检索。
8
+
9
+ 本仓库是 **C4A System 的本地独立可运行版本**;完整的 C4A System 将支持在线服务、更适合多人协同,即将发布。
8
10
 
9
11
  ## 为什么选择 C4A Context
10
12
 
@@ -13,25 +15,29 @@
13
15
  - **检索效率低下**:需要全盘扫描仓库内容才能定位关键信息;
14
16
  - **上下文冗余膨胀**:大量原始文本被注入上下文窗口,直接拉低后续推理质量。
15
17
 
16
- 传统 RAG 虽能解决基础检索问题,但依赖 Embedding 向量分片召回存在天然缺陷:**无论在生产环节还是检索环节,向量模型都会造成关键信息丢失、语义失真,显著放大大模型幻觉问题**;同时向量召回的内容往往与实际意图错位,智能体仍需二次过滤,整体精度存在明显天花板。
18
+ 传统 RAG 虽能解决基础检索问题,但依赖 Embedding 向量分片召回存在天然缺陷:**无论在生产环节还是检索环节,向量模型都会造成关键信息丢失、语义失真,显著放大大模型幻觉问题**;同时,明明 LLM 本身的意图识别能力远强于向量相似度,前置 RAG 检索环节却先一步拉低召回质量,整体精度的上限被前置链路封顶。
17
19
 
18
- C4A Context 采用全新思路:**放弃向量嵌入依赖,直接基于大模型完成知识的结构化管理与精准检索**。将各类原始资料预编译为包含 Fact array、交叉引用、可溯源原文的结构化知识单元(Section),智能体通过查询工具精准命中 Node / Section 级内容。依托标准化编译流程与专用查询能力,知识库精度接近人工梳理效果,在多数场景下综合表现优于传统文件检索与通用 RAG
20
+ C4A Context 采用全新思路:**放弃向量嵌入依赖,直接基于大模型完成知识的结构化管理与精准检索**。将各类原始资料预编译为按类型分类、带交叉引用、能溯源到原文的结构化知识单元(Section),智能体通过查询工具精准命中 Node / Section 级内容。编译阶段通过类似 Harness 的机制,让 Agent 按 CLI 的意图在小上下文窗口内循环完成知识生产任务,绕开一次性塞入大段原文造成的上下文膨胀;查询阶段直接走 CLI 在 Section 索引上命中,运行时无需调用 LLM。依托标准化编译流程与专用查询能力,知识库精度接近人工梳理效果,综合表现**显著优于**传统文件检索与通用 RAG —— benchmark 得分接近 100%。
19
21
 
20
22
  ## 适合场景
21
23
 
22
- 面向项目知识的长期维护把不同版本、不同来源的资料编译为彼此正交的结构化内容(正交的结构化内容 = 各来源知识互不冗余、边界清晰、可独立维护),避免知识库随时间膨胀失控。尤其适合长期迭代的大型项目、多团队协作、多文档来源的复杂业务系统。
24
+ **生产侧项目知识的长期维护**:把不同版本、不同来源的资料编译为彼此正交的结构化内容(各来源知识互不冗余、边界清晰、可独立维护),避免知识库随时间膨胀失控。尤其适合长期迭代的大型项目、多团队协作、多文档来源的复杂业务系统。
25
+
26
+ **消费侧 — Agent 协作的高可靠工作流**:编码、线上运维、质量保障等对幻觉零容忍、要求召回稳定的场景,杜绝 Agent 编造内容。
23
27
 
24
28
  ## 核心能力
25
29
 
26
30
  C4A Context 在项目目录下创建 `.context/` 工作目录(目录名可自定义),提供完整闭环能力:
27
31
 
28
32
  - **采集**:拉取飞书文档、本地 Markdown、代码结构、设计规范、接口文档等多源业务资料;
29
- - **编译**:由 AI 按统一协议将原始素材加工为结构化知识 — 并非简单摘要,而是附带 Fact array、交叉引用、原文溯源的标准化 Section;
33
+ - **编译**:由 AI 按统一协议将原始素材加工为结构化知识 — 并非简单摘要,而是按类型分类(spec / example / warning 等)、附带交叉引用与原文溯源的标准化 Section;
30
34
  - **检索使用**:在 Claude / Cursor / Codex 等工具中直接查询本地结构化知识,精准定位 Node 与 Section;也可将完整知识库导入其他大模型使用;
31
35
  - **知识治理**:支持废弃资料撤回,连带派生知识同步回收;自动校验知识库完整性,实现问题自愈。
32
36
 
33
37
  日常使用围绕 **采集 → 编译 → 检索使用 → 知识治理** 形成闭环,无需全量重复执行,按需增量更新。
34
38
 
39
+ <p align="center"><img src="./assets/workflow.png" alt="C4A Context 工作流示例:单文档 vs 多文档批量" width="1280"/></p>
40
+
35
41
  ## 安装
36
42
 
37
43
  所有 Agent 均需先安装 `context` 命令行工具:
@@ -39,7 +45,7 @@ C4A Context 在项目目录下创建 `.context/` 工作目录(目录名可自
39
45
  ```bash
40
46
  npm i -g @c4a/context-cli
41
47
  # 或
42
- bunx @c4a/context-cli
48
+ bun add -g @c4a/context-cli
43
49
  ```
44
50
 
45
51
  随后按所用 Agent 安装对应插件:
@@ -53,6 +59,8 @@ bunx @c4a/context-cli
53
59
 
54
60
  安装完成后,在对应 Agent 中即可通过 `/context:*`(Claude)或 `/context-*`(Cursor)等入口调用。
55
61
 
62
+ > **Tip — Claude Code 插件更新**:Claude Code 插件存在本地缓存,升级到新版本时建议先卸载旧插件,执行 `context clean-cache` 清理缓存,再重新安装,确保新版本立即生效。
63
+
56
64
  ## 手动流程
57
65
 
58
66
  进入项目目录后:
@@ -66,14 +74,20 @@ bunx @c4a/context-cli
66
74
 
67
75
  每一步都会在 `.context/` 中留下可读文件与 changelog,支持随时回看与回滚。
68
76
 
69
- ## 托管流程
77
+ ## 自动化流程
70
78
 
71
79
  完成前文「安装」步骤后,可直接让 AI Agent 或龙虾(OpenClaw)等自动化工具阅读本文档,指定项目工作区目录,引用存量知识目录自主开展全流程工作,大幅降低人工操作成本。
72
80
 
73
81
  **环境要求**: 建议使用 Claude Opus 4.6+ 或 Codex 5.5 及以上版本,确保 Agent 能精准解析指令、处理知识编译中的决策与澄清工作。
74
- **托管核心指令**:可直接复制给 Agent/龙虾工具
82
+ **自动化核心指令**:可直接复制给 Agent/龙虾工具
75
83
  ```
76
- 请你在当前目录初始化项目知识库(配置选择中文,其余参数按默认设置),并通过 context 工具完成全流程知识管理工作,包括但不限于:工作区初始化、多源资料采集、知识对齐、AI 编译、检索校验,过程中所有需要澄清的细节、决策类事项(如资料优先级、编译规则微调、知识单元分类等),由你自主把控并记录操作日志,确保知识库结构化、可溯源。
84
+ 请你在当前目录初始化项目知识库(配置选择中文,其余参数按默认设置),并通过 context 工具完成全流程知识管理工作。
85
+
86
+ 知识来源(仅限以下):
87
+ - 飞书文档:https://[URLS]
88
+ - 本地文件:/local/path/*.md
89
+
90
+ 工作内容包括但不限于:工作区初始化、多源资料采集、知识对齐、AI 编译、检索校验。过程中所有需要澄清的细节、决策类事项(如资料优先级、编译规则微调、知识单元分类等),由你自主把控并记录操作日志,确保知识库结构化、可溯源。
77
91
  ```
78
92
  > 知识建设是长期迭代的过程,涉及大量细节决策与需求澄清,自动化工具可承担大部分重复性工作,但无法完全替代人工判断;
79
93
  > 建议研发类核心知识(如代码结构、设计规范、接口细节等)在冷启阶段以人工维护为主,待知识库框架稳定后,再交由 Agent 负责增量更新与日常治理,避免核心知识偏差
@@ -83,14 +97,28 @@ bunx @c4a/context-cli
83
97
 
84
98
  完整知识库支持对外打包发布:
85
99
 
86
- - 导出为 **Skills** 包;
87
- - 导出为 **LLMs.txt**;
100
+ - 导出为 **Skills** 包:`context build --format skills-pack`;
101
+ - 导出为 **LLMs.txt**:`context build --format llms`;
88
102
  - [TODO] 发布至 **C4A 平台**,作为 MCP 服务供其他 AI 实时查询;
89
103
  - [TODO] 发布为独立 Plugin 知识包,具备与 MCP 及 CLI 同等精度的检索能力。
90
104
 
105
+ ## 环境推荐
106
+
107
+ 不同 Agent 与模型组合在指令遵循、参数幻觉、提取质量三项上的实测表现(0–100 分):
108
+
109
+ | Agent | 模型 | 指令遵循度 | 参数幻觉 | 提取质量 |
110
+ |---|---|---:|---|---:|
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 |
114
+ | Claude | DeepSeek V4 | 80 | 经常 | 55 |
115
+ | Claude | DeepSeek V4 Flash | 65 | 经常 | 50 |
116
+
117
+ **建议**:目前优先使用 Claude Opus 或 GPT;DeepSeek V4 在指令遵循与提取质量上仍有差距,需配合 CLI 进一步优化,预计 v0.5.40 完成 DeepSeek V4 适配并达到 90+ 综合得分。
118
+
91
119
  ## 关于本仓库
92
120
 
93
- 本仓库内容由 [c4a 项目](https://github.com/context4ai/c4a) 自动生成发布,请勿手动编辑。Issue 与 PR 请提交至 c4a 主仓。
121
+ 本仓库内容由 [c4a 项目](https://github.com/context4ai/c4a) 自动生成发布,请勿手动编辑。
94
122
 
95
123
  该项目提供端到端的知识处理与托管基础设施,涵盖 CLI 工具、知识管理 Studio、MCP 服务等,预计 2026 年 5 月底开源。
96
124
 
Binary file
Binary file
@@ -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, 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. 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`
@@ -27,9 +27,12 @@ Keep the prompt shape stable: read fixed schema/protocol first, then existing kn
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
28
  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
29
  - Save coarse-read with `context align --coarse-read - --format json`.
30
+ 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`.
31
+ For multiple sources, submit one envelope with `coarse_reads[]`; single-source payloads remain valid.
30
32
  - Submit each candidate batch with `context align --ops - --format json`.
31
- - After the first batch, pass the current ledger digest as `--ledger-digest <digest>` so stale batches are rejected.
32
- - Read the resulting payloads 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`.
33
+ - `--ledger-digest <digest>` is optional. Usually omit it and let the CLI merge against the current ledger; pass it only when you intentionally want stale-batch rejection for a high-assurance retry.
34
+ - Read the resulting payloads 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.
35
+ - Review `anomaly_signals[]` as warnings: fix clear mistakes with another ops batch, otherwise continue to finalize and carry the warning rationale in your final decision/report.
33
36
  5. If any CLI command returns `agent_hints[]`, follow those hints before retrying. Legacy-protocol hints mean the submitted payload or schema name is retired; switch to the beta.8 schema named in the hint instead of adapting old fields.
34
37
  6. Finalize only with `align-structure-decision`:
35
38
 
@@ -37,6 +40,25 @@ Keep the prompt shape stable: read fixed schema/protocol first, then existing kn
37
40
  context align --finalize - --digest <segments-digest>
38
41
  ```
39
42
 
43
+ 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:
44
+
45
+ ```json
46
+ {
47
+ "schema_version": "align.finalize-patch.v1",
48
+ "operations": [
49
+ { "op": "replace", "path": "/block_ownership/3/primary_owner", "value": "rspack" }
50
+ ]
51
+ }
52
+ ```
53
+
54
+ Submit the patch with `context align --finalize-patch - --payload-digest <draft-digest> --format json`.
55
+
56
+ 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
+
58
+ 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
+
60
+ 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.
61
+
40
62
  Do not submit legacy candidate tables, old patch payloads, or full-tree proposal files. Do not write `knowledge/`; align finalize writes finalized workflow artifacts and source ownership only.
41
63
 
42
64
  ## Constraints
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  description: "Capture URLs, local Markdown, source code, stdin path lists, inbox/refresh sources, or conversation notes as Context sources."
3
3
  argument-hint: "[url | ./path.md [./more.md...] | --code [path] | --stdin | --inbox | --refresh | note]"
4
- allowed-tools: Bash(context:*, brew:*, curl:*, sh:*, scoop:*, choco:*, lark-cli:*), WebFetch
4
+ allowed-tools: Bash(context:*, bun:*, brew:*, curl:*, sh:*, scoop:*, choco:*, lark-cli:*), WebFetch
5
5
  ---
6
6
 
7
7
  <!--
@@ -14,6 +14,18 @@ length exemption for self-contained slash commands.
14
14
 
15
15
  Capture is entirely CLI-driven — your role is to route the right `context capture` invocation and relay its output. Never hand-write captured source snapshots: the CLI owns normalisation (NFC, BOM strip, line endings) and the `content_hash` contract, so any manual edit breaks idempotency.
16
16
 
17
+ ### Code capture dependency preflight
18
+
19
+ Before any `context capture --code` command, including `--plan`, refresh, or explicit `--module` runs, verify that the TypeScript extraction plugin is installed in the same global package environment as the `context` executable:
20
+
21
+ ```bash
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
+ ```
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.
26
+
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
+
17
29
  ### Route by argument
18
30
 
19
31
  - `$ARGUMENTS` starts with `http://` / `https://` → `context capture $ARGUMENTS` (feishu URLs need `lark-cli`).
@@ -59,6 +71,8 @@ Never suggest `/context:compile` when no align plan exists or when the only acti
59
71
 
60
72
  ### Missing dependency recovery
61
73
 
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.
75
+
62
76
  If the CLI prints a missing-dependency error like `lark-cli not installed`, walk the user through installation:
63
77
 
64
78
  1. Ask once up-front whether to proceed with install. If no → stop and tell the user to install manually from the tool's official README, then re-run.
@@ -26,7 +26,7 @@ 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. Knowledge drafts, Section `content` / `detail`, and Node-facing summaries follow `NodeContext.generation_policy.language` when the CLI provides it; preserve product names, code identifiers, CLI flags, slugs, `source_ref` tokens, and exact quoted evidence as printed. CLI stdout/stderr, the canonical `processing <slug>` lines, paths, slugs, source refs, issue codes, flags, and command names stay as printed.
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.
30
30
 
31
31
  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
32
 
@@ -62,13 +62,14 @@ Per-Node loop:
62
62
 
63
63
  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
64
 
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, Section content/detail, 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. 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.
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
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-semantic-reconcile`. 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 before a draft session exists, read the error verbatim, fix the draft via the skill's self-verify, and retry up to 3 times.
69
- 5. Review the prepared context before accepting defaults. If it reports unsupported `source_support`, repair/split evidence before review; unsupported items cannot be accepted with `accept_default` or user confirmation. 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`.
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`.
70
70
  - 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
- 6. Pass the 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, choose or split the draft `source_refs[]` so each action is independently supported (use `source_support.evidence_block_candidates` to pick prepared evidence blocks or split unrelated claims), then rerun review. 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.
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.
72
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.
73
74
  8. Persistent failure → stop and surface the full rejection list; never edit rendered files to bypass.
74
75
 
@@ -109,7 +110,7 @@ context compile --draft billing-api --input - --plan --prepare --format json <<'
109
110
  {
110
111
  "op": "skip",
111
112
  "reason": "reviewed; intentionally not written",
112
- "source_refs": ["src-1#reviewed-note L12-14@ab12cd34ef56"]
113
+ "source_refs": ["src-1#reviewed-note L12-14@7a6f4c9d2e10"]
113
114
  }
114
115
  ]
115
116
  }
@@ -19,7 +19,7 @@ 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, and `source_ref` tokens exactly when needed.
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
23
  - Gate rules for `domain` and `action` proposals 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`.
@@ -33,13 +33,19 @@ Use this only inside `/context:align`.
33
33
  1. Start from `align-segments`.
34
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.
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
- 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`.
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` and pass `--ledger-digest <digest>` after the first batch. 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
- 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`. Treat aggregate fields as mechanical statistics and warnings, not semantic recommendations. Resolve every `anomaly_signals[]` entry as accept, dismiss, or unresolved before finalizing.
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.
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
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
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.
42
42
 
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
+
45
+ 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
+
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.
48
+
43
49
  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.
44
50
 
45
51
  - `owned`: exactly one slug in `owners[]`, plus `visible_to[]` and `reason`. Do not include `primary_owner`, `context_prefix`, or `question_id`.
@@ -50,6 +56,19 @@ Use this only inside `/context:align`.
50
56
 
51
57
  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.
52
58
 
59
+ If finalize returns an `align-finalize-draft` payload, patch the saved draft instead of rewriting the whole finalize document. Use JSON Pointer paths from the returned issues and submit only the corrections:
60
+
61
+ ```json
62
+ {
63
+ "schema_version": "align.finalize-patch.v1",
64
+ "operations": [
65
+ { "op": "replace", "path": "/block_ownership/3/primary_owner", "value": "rspack" }
66
+ ]
67
+ }
68
+ ```
69
+
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.
71
+
53
72
  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.
54
73
 
55
74
  </procedures>
@@ -55,19 +55,19 @@ Not `term`:
55
55
  inference_sources:
56
56
  actor:
57
57
  source_type: explicit-block
58
- evidence_blocks: [b0001]
58
+ evidence_blocks: [7a6f4c9d2e10]
59
59
  rationale: "The block names the operator role."
60
60
  outcome_or_goal:
61
61
  source_type: inferred-from-block
62
- evidence_blocks: [b0001]
62
+ evidence_blocks: [7a6f4c9d2e10]
63
63
  rationale: "The block describes recovery as the expected result."
64
64
  repeatability_or_plan:
65
65
  source_type: heading-and-block
66
- evidence_blocks: [b0001]
66
+ evidence_blocks: [7a6f4c9d2e10]
67
67
  rationale: "The runbook heading and ordered list indicate planned reuse."
68
68
  answerability:
69
69
  source_type: explicit-block
70
- evidence_blocks: [b0001]
70
+ evidence_blocks: [7a6f4c9d2e10]
71
71
  rationale: "The steps answer how the operation is performed."
72
72
  ```
73
73
 
@@ -30,9 +30,9 @@ command. It does not hand-edit rendered knowledge.
30
30
  - Content / Section issues (`invalid-section-mount`, `body-ad-hoc-heading`, `dangling-source-alias`) → user re-runs `/context:compile` (draft loop fixes its own Section actions; the close stage does not patch)
31
31
  - Structural issues (`contains-cycle`, `edge-dangling-node`, `duplicate-slug`, `invalid-node-type`, `domain-same-file-child`) → user runs `/context:align` to revise the plan
32
32
  - Source issues (`dropped-source-reference`) → user runs `/context:drop <id>` to complete the drop
33
- - Exit 0 → summarise node/section totals, verify, `recompiled`, `locator_updates`, `rebuilt`, fingerprint rebuild count, and archive status / archived file count when printed; then stop.
33
+ - Exit 0 → summarise node/section totals, verify, `recompiled`, `locator_updates`, `rebuilt`, fingerprint rebuild count, archive status / archived file count, and any `ready_with_debt` coverage warnings when printed; then stop.
34
34
  - Exit 2 → report the full issue list verbatim + point at the right re-entry command above. Do not hand-open the affected rendered article.
35
- - If exit 2 includes `coverage-high-signal-unresolved`, follow the CLI hint. Read the node-scoped payload with `context workflow show --payload coverage-candidates --scope <node-run-scope> --view coverage` or inspect `context schema coverage-disposition`; do not guess workspace-scope payload paths.
35
+ - Coverage warning choice: `ready_with_debt` means close succeeded and unresolved coverage remains visible. You may either continue with the warning recorded, or run an uncovered-only repair/skip round. If all unresolved candidates are intentionally excluded for the same reason, use `context compile --coverage-skip-unresolved --coverage-disposition-node <slug> --payload-digest <digest> --reason "<reason>"`; otherwise inspect `context schema coverage-disposition`.
36
36
  - Never re-run `context compile --draft` from close to paper over verify failures. Draft failures belong in the draft loop.
37
37
  - Do not use Python, Node.js, shell scripts, `ls`, `find`, `rg`, `cat`, or similar ad-hoc commands to inspect `WORKSPACE_DIR`, `.context`, knowledge files, or `/tmp` workflow artifacts.
38
38
  - Derivable files self-heal: missing `_index.md` or `changelog.md` is rebuilt inside `compile --close` before the append, locator-only source moves are refreshed, non-canonical but hash-valid `source_ref` locators are canonicalized, and high-signal coverage candidates already backed by active Sections are marked covered. No pre-check needed.
@@ -62,11 +62,10 @@ Close is one in-process command with one exit code:
62
62
  | Outcome | Agent action |
63
63
  |---|---|
64
64
  | Exit 0, 0 issues | Summarise those counts in the user's language: Nodes touched; Sections added / updated / superseded / deprecated / skipped; `recompiled`; `locator_updates`; `rebuilt`; verify green. Stop. |
65
- | Exit 0, warnings only | Summarise + list warnings verbatim. Point at `/context:status` or `context cache status` when the warning is incremental-cache-related. Stop. |
65
+ | Exit 0, warnings only | Summarise + list warnings verbatim. For coverage warnings, name both choices: continue with `ready_with_debt`, or run an uncovered-only repair/skip round through `context compile --coverage-skip-unresolved` or `context schema coverage-disposition`. Stop. |
66
66
  | Exit 2, Section / content issue | Surface the full issue list; point the user at re-running `/context:compile` (the draft loop owns Section writes). Do NOT Edit the affected rendered article. |
67
67
  | Exit 2, structural issue (cycle, duplicate slug, `invalid-node-type`, `domain-same-file-child`) | Surface the full issue list; point the user at `/context:align` to revise structure. Do not re-run compile. |
68
68
  | Exit 2, `dropped-source-reference` | Surface the source-id; point the user at `/context:drop <id>` to complete the drop cleanup. |
69
- | Exit 2, `coverage-high-signal-unresolved` | Read the node-scoped coverage payload named in the CLI hint. If the candidate is intentionally covered by sibling Nodes or should not be written for this Node, submit `action: skip` with a reason; for skip only, `source_refs` may be omitted to dispose the whole candidate. |
70
69
 
71
70
  The close stage never edits rendered knowledge on the agent side. Every verify error routes back to the correct upstream command (compile / align / drop), never sideways into a hand Edit. Use the CLI issue code and hint printed by `context compile --close` for the error→command mapping.
72
71