@haposoft/cafekit 0.8.13 → 0.8.14

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/README.md CHANGED
@@ -80,6 +80,7 @@ CafeKit ships many skills, but the main release surface is:
80
80
  - `/hapo:develop <feature-name>`: implement from approved spec artifacts
81
81
  - `/hapo:debug <issue>`: diagnose bugs, incidents, CI failures, flaky tests, UI regressions, and performance issues before fixing
82
82
  - `/hapo:hotfix <issue>`: fix diagnosed bugs with root-cause, verification, prevention, and side-effect gates
83
+ - `/hapo:docs [init|update|summarize|reconstruct]`: create project docs or reconstruct as-is system documentation from source code
83
84
  - `/hapo:test [scope|--full]`: run verification and return a structured verdict
84
85
  - `/hapo:code-review [scope|--pending]`: adversarial review focused on correctness, regressions, and security
85
86
  - `/hapo:generate-graph <diagram request>`: generate technical SVG/PNG diagrams
@@ -125,6 +126,14 @@ Generate a diagram:
125
126
  /hapo:generate-graph Draw a sequence diagram for auth flow between browser, API, and database
126
127
  ```
127
128
 
129
+ Reconstruct current-state docs for an existing or legacy system:
130
+
131
+ ```bash
132
+ /hapo:docs reconstruct apps/legacy-admin
133
+ ```
134
+
135
+ The reconstruct bundle includes as-is markdown/JSON evidence and a self-contained `overview.html` review dashboard before the approved docs are handed to `/hapo:specs`.
136
+
128
137
  ## Spec Artifacts
129
138
 
130
139
  CafeKit's current spec workflow writes artifacts under:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@haposoft/cafekit",
3
- "version": "0.8.13",
3
+ "version": "0.8.14",
4
4
  "description": "Claude Code-first spec-driven workflow for AI coding assistants. Bundles CafeKit hapo: skills, runtime hooks, agents, and installer scaffolding.",
5
5
  "author": "Haposoft <nghialt@haposoft.com>",
6
6
  "license": "MIT",
@@ -18,7 +18,7 @@ const ROUTES = [
18
18
  strong: ['spec', 'specs', 'requirements', 'acceptance criteria', 'task breakdown', 'đặc tả', 'dac ta', '仕様', '仕様書', '要件', '受け入れ条件', 'タスク分解', '仕様を作って', '仕様を作成'],
19
19
  medium: ['requirement', 'ears', 'design doc', 'scope', '--validate', 'yêu cầu', 'yeu cau', 'phạm vi', 'pham vi', 'validate spec', 'kiểm tra spec', 'kiem tra spec', '要求', '設計書', 'スコープ', '検証', '仕様を確認'],
20
20
  weak: ['tính năng mới', 'tinh nang moi', 'feature idea', 'user story', 'criteria', 'task list', '新機能', 'ユーザーストーリー', '基準', 'タスクリスト'],
21
- negative: ['commit', 'push', 'bug', 'error', 'production', 'pptx', 'pdf'],
21
+ negative: ['commit', 'push', 'bug', 'error', 'production', 'pptx', 'pdf', 'reconstruct requirements', 'as-is requirements', 'legacy system documentation', 'documentation from source code', 'docs from source code', 'ソースコードから'],
22
22
  }),
23
23
  route('hapo:develop', 'implementation from an approved spec or task list', 75, {
24
24
  strong: ['develop', 'implement', 'implementation', 'theo spec', 'theo specs', 'approved spec', 'làm theo spec', 'lam theo spec', '実装', '開発', '仕様に沿って', '仕様どおり', '承認済み仕様'],
@@ -98,6 +98,12 @@ const ROUTES = [
98
98
  weak: ['mind map', 'dependency map', 'system map', 'マインドマップ', '依存関係図', 'システム図'],
99
99
  negative: ['pptx', 'slide deck'],
100
100
  }),
101
+ route('hapo:docs', 'project documentation, codebase docs, or source-backed as-is reconstruction', 51, {
102
+ strong: ['hapo:docs', 'project docs', 'system docs', 'codebase docs', 'codebase documentation', 'documentation from source code', 'docs from source code', 'generate docs from codebase', 'dựng tài liệu từ source code', 'dung tai lieu tu source code', 'tài liệu hệ thống', 'tai lieu he thong', 'tài liệu hiện trạng', 'tai lieu hien trang', 'tạo tài liệu project', 'tao tai lieu project', 'legacy documentation', 'legacy system documentation', 'as-is documentation', 'as-is requirements', 'requirement reconstruction', 'reconstruct requirements', 'reconstruct requirements from legacy system', 'ソースコードから仕様書', 'ソースコードから仕様書を作成', 'ソースコードからドキュメント', '既存システムのドキュメント', '現行仕様書', 'as-isドキュメント'],
103
+ medium: ['create docs', 'update docs', 'refresh docs', 'summarize codebase', 'system documentation', 'source to docs', 'reverse documentation', 'current-state docs', 'existing system docs', 'legacy docs', 'legacy system', 'dựng docs', 'dung docs', 'tạo docs', 'tao docs', 'cập nhật docs', 'cap nhat docs', 'tóm tắt codebase', 'tom tat codebase', 'dựng lại tài liệu', 'dung lai tai lieu', '仕様書を作成', 'ドキュメント作成', 'ドキュメント更新', 'コードベース要約', '既存システム', 'レガシーシステム'],
104
+ weak: ['docs', 'documentation', 'document project', 'document codebase', 'as-is', 'reconstruct', 'hiện trạng', 'hien trang', 'tài liệu', 'tai lieu', 'ドキュメント', '資料化', '仕様化', '現状'],
105
+ negative: ['official docs', 'latest docs', 'library docs', 'framework docs', 'api docs lookup', 'context7', 'best practice', 'research', 'pptx', 'slide'],
106
+ }),
101
107
  route('hapo:brainstorm', 'early ideation or unclear solution direction', 50, {
102
108
  strong: ['brainstorm', 'ý tưởng', 'y tuong', 'phương án', 'phuong an', 'gợi ý', 'goi y', 'ブレスト', 'アイデア', '案', '提案して', '相談'],
103
109
  medium: ['idea', 'ideas', 'approach', 'options', 'tradeoff', 'chủ đề', 'chu de', 'cần làm gì', 'can lam gi', 'アプローチ', '選択肢', 'トレードオフ', 'テーマ', '何をすれば'],
@@ -15,6 +15,7 @@
15
15
  "debug",
16
16
  "develop",
17
17
  "devops",
18
+ "docs",
18
19
  "docx",
19
20
  "frontend-design",
20
21
  "frontend-development",
@@ -56,6 +57,7 @@
56
57
  "scripts": {
57
58
  "required": [
58
59
  "validate-docs.cjs",
60
+ "validate-docs-reconstruct.cjs",
59
61
  "browser-tool.cjs",
60
62
  "validate-spec-output.cjs"
61
63
  ]
@@ -0,0 +1,176 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * CafeKit as-is reconstruction bundle validator.
4
+ *
5
+ * The docs workflow is LLM-authored, so the bundle shape and evidence links
6
+ * must be checked deterministically before it is handed to human review.
7
+ */
8
+
9
+ const fs = require('fs');
10
+ const path = require('path');
11
+
12
+ const DOCUMENT_FILES = [
13
+ 'overview.html',
14
+ 'system-overview.md',
15
+ 'requirements-as-is.md',
16
+ 'roles-and-permissions.md',
17
+ 'entities-and-statuses.md',
18
+ 'business-rules.md',
19
+ 'integrations.md',
20
+ 'architecture-c4.md',
21
+ 'constraints-risks-and-decisions.md',
22
+ 'glossary.md',
23
+ 'evidence-map.md',
24
+ 'unknowns-and-assumptions.md',
25
+ ];
26
+ const REQUIRED_FILES = ['reconstruction.json', ...DOCUMENT_FILES];
27
+ const EVIDENCE_ID_RE = /\bE-[A-Z]+-\d{3}\b/g;
28
+
29
+ function usage() {
30
+ console.error('Usage: node .claude/scripts/validate-docs-reconstruct.cjs docs/as-is/<scope>');
31
+ }
32
+
33
+ function readJson(filePath, errors) {
34
+ try {
35
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
36
+ } catch (error) {
37
+ errors.push(`reconstruction.json: invalid JSON (${error.message})`);
38
+ return null;
39
+ }
40
+ }
41
+
42
+ function readText(filePath) {
43
+ return fs.readFileSync(filePath, 'utf8');
44
+ }
45
+
46
+ function uniqueMatches(text, pattern) {
47
+ return [...new Set(text.match(pattern) || [])].sort();
48
+ }
49
+
50
+ function validateMeta(bundle, meta, errors) {
51
+ for (const key of [
52
+ 'scope',
53
+ 'generated_at',
54
+ 'status',
55
+ 'docs_root',
56
+ 'source_revision',
57
+ 'source_branch',
58
+ 'evidence_policy',
59
+ 'review_gate',
60
+ 'review_status',
61
+ 'approved_for_specs',
62
+ 'documents',
63
+ 'counts',
64
+ 'next_recommended_step',
65
+ ]) {
66
+ if (!(key in meta)) errors.push(`reconstruction.json.${key}: missing`);
67
+ }
68
+
69
+ for (const key of ['scope', 'generated_at', 'docs_root', 'source_revision', 'source_branch']) {
70
+ if (key in meta && (typeof meta[key] !== 'string' || meta[key].trim() === '')) {
71
+ errors.push(`reconstruction.json.${key}: must be a non-empty string`);
72
+ }
73
+ }
74
+ if (meta.approved_for_specs !== false && meta.review_status !== 'approved') {
75
+ errors.push('reconstruction.json.approved_for_specs: only approved review may set true');
76
+ }
77
+ if (!Array.isArray(meta.documents)) {
78
+ errors.push('reconstruction.json.documents: must be an array');
79
+ return;
80
+ }
81
+
82
+ const declared = [...meta.documents].sort();
83
+ const expected = [...DOCUMENT_FILES].sort();
84
+ if (JSON.stringify(declared) !== JSON.stringify(expected)) {
85
+ errors.push('reconstruction.json.documents: must exactly list the as-is document bundle');
86
+ }
87
+ if (typeof meta.docs_root === 'string' && !meta.docs_root.includes(path.basename(bundle))) {
88
+ errors.push('reconstruction.json.docs_root: must point at this scope bundle');
89
+ }
90
+ }
91
+
92
+ function requirementBlocks(text) {
93
+ const matches = [...text.matchAll(/^##\s+(R-ASIS-\d{3})\b[^\n]*$/gm)];
94
+ return matches.map((match, index) => ({
95
+ id: match[1],
96
+ text: text.slice(match.index, matches[index + 1]?.index ?? text.length),
97
+ }));
98
+ }
99
+
100
+ function validateRequirements(bundle, evidenceText, errors) {
101
+ const requirementPath = path.join(bundle, 'requirements-as-is.md');
102
+ const blocks = requirementBlocks(readText(requirementPath));
103
+ if (blocks.length === 0) {
104
+ errors.push('requirements-as-is.md: must contain at least one ## R-ASIS-### requirement');
105
+ return;
106
+ }
107
+
108
+ const ledgerIds = new Set(uniqueMatches(evidenceText, EVIDENCE_ID_RE));
109
+ for (const block of blocks) {
110
+ if (!/- Type:\s*(Observed|Inferred|Unknown)\b/.test(block.text)) {
111
+ errors.push(`requirements-as-is.md:${block.id}: missing Type`);
112
+ }
113
+ if (!/- Confidence:\s*(High|Medium|Low)\b/.test(block.text)) {
114
+ errors.push(`requirements-as-is.md:${block.id}: missing Confidence`);
115
+ }
116
+ if (!/^- Evidence:\s*$/m.test(block.text)) {
117
+ errors.push(`requirements-as-is.md:${block.id}: missing Evidence section`);
118
+ }
119
+
120
+ const evidenceIds = uniqueMatches(block.text, EVIDENCE_ID_RE);
121
+ if (evidenceIds.length === 0) {
122
+ errors.push(`requirements-as-is.md:${block.id}: must reference evidence IDs`);
123
+ }
124
+ for (const evidenceId of evidenceIds) {
125
+ if (!ledgerIds.has(evidenceId)) {
126
+ errors.push(`requirements-as-is.md:${block.id}: unknown evidence ID ${evidenceId}`);
127
+ }
128
+ }
129
+ }
130
+ }
131
+
132
+ function validateBundle(bundle) {
133
+ const errors = [];
134
+ if (!fs.existsSync(bundle)) return { errors: [`${bundle}: bundle directory does not exist`] };
135
+
136
+ for (const file of REQUIRED_FILES) {
137
+ if (!fs.existsSync(path.join(bundle, file))) errors.push(`${file}: missing`);
138
+ }
139
+ if (errors.length > 0) return { errors };
140
+
141
+ const meta = readJson(path.join(bundle, 'reconstruction.json'), errors);
142
+ if (meta) validateMeta(bundle, meta, errors);
143
+
144
+ const evidence = readText(path.join(bundle, 'evidence-map.md'));
145
+ if (uniqueMatches(evidence, EVIDENCE_ID_RE).length === 0) {
146
+ errors.push('evidence-map.md: must define evidence IDs');
147
+ }
148
+ validateRequirements(bundle, evidence, errors);
149
+
150
+ const overview = readText(path.join(bundle, 'overview.html'));
151
+ if (!overview.includes('data-reconstruct-overview')) {
152
+ errors.push('overview.html: must keep reconstruct overview marker');
153
+ }
154
+
155
+ return { errors };
156
+ }
157
+
158
+ function main() {
159
+ const input = process.argv[2];
160
+ if (!input) {
161
+ usage();
162
+ process.exit(2);
163
+ }
164
+
165
+ const bundle = path.resolve(process.cwd(), input);
166
+ const { errors } = validateBundle(bundle);
167
+ if (errors.length > 0) {
168
+ console.error(`FAIL ${path.relative(process.cwd(), bundle) || bundle}`);
169
+ for (const error of errors) console.error(`- ${error}`);
170
+ process.exit(1);
171
+ }
172
+
173
+ console.log(`PASS ${path.relative(process.cwd(), bundle) || bundle}`);
174
+ }
175
+
176
+ main();
@@ -42,7 +42,8 @@ function checkBrokenLinks(docsDir) {
42
42
  }
43
43
 
44
44
  function main() {
45
- const docsDir = path.resolve(process.cwd(), 'docs');
45
+ const docsArg = process.argv[2] || 'docs';
46
+ const docsDir = path.resolve(process.cwd(), docsArg);
46
47
  console.log(`[Docs Validator] Auditing bounds directory: ${docsDir}`);
47
48
 
48
49
  if (!fs.existsSync(docsDir)) {
@@ -0,0 +1,262 @@
1
+ ---
2
+ name: hapo:docs
3
+ description: "Create, update, summarize, or reconstruct project/system documentation from source code. Use reconstruct mode for as-is documentation of existing or legacy systems with evidence and uncertainty tracking."
4
+ version: 1.0.0
5
+ argument-hint: "[init|update|summarize|reconstruct] [scope]"
6
+ ---
7
+
8
+ # Docs
9
+
10
+ Project documentation workflow for CafeKit.
11
+
12
+ `hapo:docs` covers two related but distinct jobs:
13
+
14
+ 1. **Normal project docs** — create, update, or summarize living project documentation.
15
+ 2. **As-is reconstruction** — rebuild current-state system documentation from source code, especially for existing or legacy systems with missing documents.
16
+
17
+ ## Command Forms
18
+
19
+ ```text
20
+ /hapo:docs
21
+ /hapo:docs init
22
+ /hapo:docs update
23
+ /hapo:docs summarize
24
+ /hapo:docs reconstruct <scope>
25
+ ```
26
+
27
+ ## Default Behavior
28
+
29
+ Parse the user intent before selecting a mode.
30
+
31
+ | Intent signal | Mode |
32
+ |---|---|
33
+ | Existing system, legacy system, source-to-docs, as-is, reverse documentation, or requirement reconstruction | `reconstruct` |
34
+ | Missing docs, initialize docs, bootstrap docs | `init` |
35
+ | Existing docs need refresh after code changes | `update` |
36
+ | Short overview, quick codebase summary, summarize docs | `summarize` |
37
+
38
+ When `/hapo:docs` has no clear mode:
39
+
40
+ 1. Read the docs root from `.claude/runtime.json`.
41
+ 2. If the docs root is missing, choose `init`.
42
+ 3. If the docs root exists and user did not request only a summary, choose `update`.
43
+ 4. Ask one concise clarification only when choosing between normal docs and as-is reconstruction would change the output materially.
44
+
45
+ Do not show a menu when prompt intent is already clear.
46
+
47
+ ## Output Roots
48
+
49
+ Read `.claude/runtime.json` first. Use:
50
+
51
+ ```json
52
+ {
53
+ "paths": {
54
+ "docs": "docs"
55
+ }
56
+ }
57
+ ```
58
+
59
+ Default docs root: `docs/`.
60
+
61
+ Normal docs live directly under the docs root:
62
+
63
+ ```text
64
+ docs/
65
+ ├── project-overview-pdr.md
66
+ ├── codebase-summary.md
67
+ ├── system-architecture.md
68
+ ├── code-standards.md
69
+ ├── design-guidelines.md
70
+ ├── deployment-guide.md
71
+ └── project-roadmap.md
72
+ ```
73
+
74
+ Reconstructed as-is docs live under:
75
+
76
+ ```text
77
+ docs/as-is/<scope-slug>/
78
+ ├── overview.html
79
+ ├── reconstruction.json
80
+ ├── system-overview.md
81
+ ├── requirements-as-is.md
82
+ ├── roles-and-permissions.md
83
+ ├── entities-and-statuses.md
84
+ ├── business-rules.md
85
+ ├── integrations.md
86
+ ├── architecture-c4.md
87
+ ├── constraints-risks-and-decisions.md
88
+ ├── glossary.md
89
+ ├── evidence-map.md
90
+ └── unknowns-and-assumptions.md
91
+ ```
92
+
93
+ ## Subcommands
94
+
95
+ ### `init`
96
+
97
+ Create the standard project docs set from the current source code.
98
+
99
+ Use when:
100
+ - the repository has code but no useful docs
101
+ - the user asks to create project docs
102
+ - SessionStart docs-sync reports missing documentation
103
+
104
+ Load:
105
+ - `references/standard-docs-workflow.md`
106
+ - `references/init-workflow.md`
107
+
108
+ ### `update`
109
+
110
+ Refresh existing docs after code changes.
111
+
112
+ Use when:
113
+ - docs exist and source code changed
114
+ - the user asks to update or refresh docs
115
+ - docs-sync reports stale docs
116
+
117
+ Load:
118
+ - `references/standard-docs-workflow.md`
119
+ - `references/update-workflow.md`
120
+
121
+ ### `summarize`
122
+
123
+ Create or update only `codebase-summary.md`.
124
+
125
+ Use when:
126
+ - the user asks for a quick project summary
127
+ - downstream work needs orientation but not full docs
128
+
129
+ Load:
130
+ - `references/standard-docs-workflow.md`
131
+ - `references/summarize-workflow.md`
132
+
133
+ ### `reconstruct`
134
+
135
+ Rebuild current-state, as-is system documentation from source code.
136
+
137
+ Use when the user asks for:
138
+ - legacy system documentation
139
+ - source-code-to-documentation
140
+ - current system requirements
141
+ - as-is requirements
142
+ - requirement reconstruction
143
+ - reverse documentation
144
+ - Japanese-style legacy system modernization discovery
145
+
146
+ Load:
147
+ - `references/reconstruct-workflow.md`
148
+ - `templates/reconstruction.json`
149
+ - `templates/requirements-as-is.md`
150
+ - `templates/evidence-map.md`
151
+ - `templates/unknowns-and-assumptions.md`
152
+ - `templates/reconstruct-overview.html`
153
+
154
+ ## Reconstruction Is Not Specs
155
+
156
+ `hapo:docs reconstruct` MUST NOT:
157
+
158
+ - design future behavior
159
+ - add new requirements
160
+ - create implementation tasks
161
+ - create `specs/<feature>/`
162
+ - run `/hapo:develop`
163
+ - claim full business intent from code alone
164
+
165
+ Correct handoff:
166
+
167
+ ```text
168
+ /hapo:docs reconstruct <scope>
169
+ -> human review of as-is docs
170
+ -> /hapo:specs <modernization or change request>
171
+ -> /hapo:develop <feature>
172
+ ```
173
+
174
+ ## Reconstruction Evidence Rules
175
+
176
+ Every major finding in reconstructed docs MUST be classified:
177
+
178
+ ```text
179
+ Type: Observed | Inferred | Unknown
180
+ Confidence: High | Medium | Low
181
+ Evidence: file path, symbol, route, schema, test, or config
182
+ ```
183
+
184
+ Definitions:
185
+
186
+ - `Observed`: directly visible in source code, tests, schemas, route definitions, config, or docs.
187
+ - `Inferred`: likely behavior derived from multiple signals, but not directly proven.
188
+ - `Unknown`: cannot be established from available evidence.
189
+
190
+ Do not hide uncertainty. Preserving unknowns is part of the output.
191
+
192
+ ## Scope Discipline
193
+
194
+ Start with the narrowest useful scope.
195
+
196
+ For broad inputs such as `.`, `/`, `whole repo`, or `entire system`:
197
+
198
+ 1. Run a lightweight structure scout first.
199
+ 2. Split the project into modules or bounded contexts.
200
+ 3. Ask the user to pick a module if the first pass cannot safely choose one.
201
+
202
+ Prefer:
203
+
204
+ ```text
205
+ /hapo:docs reconstruct apps/admin
206
+ /hapo:docs reconstruct modules/expense-approval
207
+ /hapo:docs reconstruct src/features/order
208
+ ```
209
+
210
+ Avoid reconstructing a large monolith in one pass unless the user explicitly accepts lower precision.
211
+
212
+ ## Agent And Tool Fit
213
+
214
+ Normal docs workflows reuse the CafeKit docs stack already shipped in the package:
215
+
216
+ - use `hapo:inspect` or targeted reads to scout source scope
217
+ - use `docs-keeper` for evidence-backed docs writing when delegation is available
218
+ - use `.claude/scripts/validate-docs.cjs <docs-root>` after create/update work
219
+ - use `.claude/scripts/validate-docs-reconstruct.cjs <docs-root>/as-is/<scope-slug>` before a reconstructed bundle is handed to human review
220
+
221
+ The upstream Research docs workflow names a `docs-manager` agent. CafeKit ships `docs-keeper` instead; keep the same scouting, size-check, and validation discipline while using the packaged agent contract.
222
+
223
+ `reconstruct` may use the same scout patterns, but it writes a scoped as-is bundle and must keep uncertainty visible.
224
+
225
+ ## Best-Practice Basis
226
+
227
+ Use these documentation principles:
228
+
229
+ - **Docs as Code**: docs live in the repo and are reviewed like code.
230
+ - **C4 Model**: use system context/container/component views when architecture is relevant.
231
+ - **arc42**: capture context, building blocks, runtime behavior, deployment, risks, and decisions when useful.
232
+ - **Diataxis**: separate explanation, reference, and how-to content instead of dumping one long file.
233
+ - **ADR discipline**: if code reveals important architectural decisions, record them as recovered decision notes, not guesses.
234
+
235
+ ## Required Final Report
236
+
237
+ For any `hapo:docs` run, report:
238
+
239
+ - files created or updated
240
+ - scope analyzed
241
+ - evidence quality
242
+ - unresolved questions
243
+ - recommended next command, if any
244
+
245
+ For `reconstruct`, the recommended next command is usually:
246
+
247
+ ```text
248
+ /hapo:specs <change request based on approved as-is docs>
249
+ ```
250
+
251
+ ## References
252
+
253
+ - `references/standard-docs-workflow.md`
254
+ - `references/init-workflow.md`
255
+ - `references/update-workflow.md`
256
+ - `references/summarize-workflow.md`
257
+ - `references/reconstruct-workflow.md`
258
+ - `templates/reconstruction.json`
259
+ - `templates/requirements-as-is.md`
260
+ - `templates/evidence-map.md`
261
+ - `templates/unknowns-and-assumptions.md`
262
+ - `templates/reconstruct-overview.html`
@@ -0,0 +1,132 @@
1
+ # Init Workflow
2
+
3
+ Use with `/hapo:docs init`.
4
+
5
+ ## Goal
6
+
7
+ Create a first evidence-backed documentation baseline for a repository that already has source code but lacks useful project docs.
8
+
9
+ The first run should make future agents faster without presenting guesses as project truth.
10
+
11
+ ## Inputs
12
+
13
+ Resolve the docs root from `.claude/runtime.json` first. Default to `docs/`.
14
+
15
+ Read or scout:
16
+
17
+ - `README.md`, `CLAUDE.md`, `AGENTS.md`, and root instructions that exist
18
+ - package/workspace manifests, lock files, build config, runtime config
19
+ - source directories that actually exist
20
+ - tests, migrations, schemas, routes, CI, deployment config
21
+ - current docs root if it exists but is incomplete
22
+
23
+ Do not hardcode `src/` when a project uses `apps/`, `packages/`, `cmd/`, `internal/`, `modules/`, or another structure.
24
+
25
+ ## Required Baseline
26
+
27
+ Create or update the useful core docs below:
28
+
29
+ | File | Purpose | Creation rule |
30
+ |---|---|---|
31
+ | `README.md` | Entry point and quick commands | Update if needed; keep concise |
32
+ | `<docs-root>/project-overview-pdr.md` | Product purpose, actors, capabilities, constraints | Core |
33
+ | `<docs-root>/codebase-summary.md` | Project structure, tech stack, major runtime paths | Core |
34
+ | `<docs-root>/code-standards.md` | Observed conventions, commands, code quality rules | Core |
35
+ | `<docs-root>/system-architecture.md` | Boundaries, components, runtime/data flow | Core |
36
+ | `<docs-root>/project-roadmap.md` | Current state, milestones, known follow-up areas | Core when evidence exists |
37
+ | `<docs-root>/deployment-guide.md` | Build/deploy/runtime config | Optional when deployment evidence exists |
38
+ | `<docs-root>/design-guidelines.md` | UI/design conventions | Optional when UI evidence exists |
39
+
40
+ Do not create a large document solely to fill the table. If a core file cannot be grounded yet, create the smallest useful shell and put unresolved questions at the end.
41
+
42
+ ## Workflow
43
+
44
+ ### Phase 0: Preflight
45
+
46
+ 1. Read repo instructions and runtime docs root.
47
+ 2. Detect whether docs already exist.
48
+ 3. If user specifically asked `init` and docs exist, preserve existing content:
49
+ - read it first
50
+ - merge or add missing baseline sections
51
+ - do not overwrite human-written docs blind
52
+ 4. Build a no-scan list for ignored, generated, vendor, cache, secret, and credential paths.
53
+
54
+ ### Phase 1: Structure Scout
55
+
56
+ Run a lightweight source scout before deep reading:
57
+
58
+ 1. List top-level directories and key manifests.
59
+ 2. Count file/LOC shape by existing source areas where practical.
60
+ 3. Identify project type:
61
+ - language/framework
62
+ - package manager/build system
63
+ - app/service boundaries
64
+ - UI/API/worker/job/deployment surfaces
65
+ 4. Split large repositories into scoped source areas.
66
+
67
+ Use `hapo:inspect` when source discovery spans multiple directories. Prefer targeted reads when the repo is small.
68
+
69
+ ### Phase 2: Evidence Scout
70
+
71
+ Collect evidence for docs authorship:
72
+
73
+ | Topic | Evidence examples |
74
+ |---|---|
75
+ | Tech stack | package manifests, `go.mod`, `pyproject.toml`, build files |
76
+ | Commands | scripts, Makefiles, CI jobs |
77
+ | Runtime entry points | app bootstrap, routes, controllers, server main files |
78
+ | Data model | schemas, migrations, models, DTOs |
79
+ | Architecture | imports between modules, service boundaries, deploy config |
80
+ | Testing | test commands, test directories, fixtures |
81
+ | UI/design | shared components, tokens, styles, screenshots when present |
82
+
83
+ Merge scout results into a concise context summary. Keep file references with each important claim.
84
+
85
+ ### Phase 3: Docs Authoring
86
+
87
+ Delegate the merged context to `docs-keeper` when available. Otherwise follow its verification discipline in the main context.
88
+
89
+ Authoring rules:
90
+
91
+ 1. Read code before documenting code.
92
+ 2. Verify referenced paths, commands, config keys, endpoints, and symbols before naming them.
93
+ 3. Record observed conventions as observed; do not turn folder guesses into standards.
94
+ 4. Use relative links among docs only after confirming targets exist.
95
+ 5. Add unresolved questions to any doc whose important claim is not yet verifiable.
96
+
97
+ ### Phase 4: Size Discipline
98
+
99
+ After generation:
100
+
101
+ 1. Check markdown LOC in the docs root.
102
+ 2. Use `docs.maxLoc` from session/runtime context when provided; default to 800 lines.
103
+ 3. If a file crosses the limit:
104
+ - split on semantic boundaries
105
+ - make an `index.md` for the topic when a document becomes a folder
106
+ - keep links from the original entry point
107
+ 4. Report any intentionally accepted oversized file.
108
+
109
+ ### Phase 5: Validation And Tracking
110
+
111
+ 1. Run `.claude/scripts/validate-docs.cjs <docs-root>` when available.
112
+ 2. Fix broken internal doc links that can be resolved from evidence.
113
+ 3. If docs-sync uses `<docs-root>/.sync_hash`, update it only after the docs reflect current source state.
114
+
115
+ ## Required Final Report
116
+
117
+ Report:
118
+
119
+ - docs root used
120
+ - source areas scouted
121
+ - files created or updated
122
+ - validation result
123
+ - evidence gaps
124
+ - unresolved questions
125
+
126
+ Recommended next command:
127
+
128
+ ```text
129
+ /hapo:docs update
130
+ ```
131
+
132
+ after meaningful source changes.