{"id":"init-deep","name":"init-deep","summary":"(ビルトイン)階層的 AGENTS.md 知識ベースを初期化する","body":"# /init-deep\n\nGenerate hierarchical AGENTS.md files: root + complexity-scored subdirectories, produced by a size-formula-driven dag map-reduce (`quick` scanners -> `unspecified-high` writers) so the main session's context stays flat at any repo size.\n\n## Usage\n\n```\n/init-deep                      # Update mode: modify existing + create new where warranted\n/init-deep --create-new         # Read existing → remove all → regenerate from scratch\n/init-deep --max-depth=2        # Limit directory depth (default: 3)\n```\n\n---\n\n## Workflow (High-Level)\n\n1. **Size & route** (main session) - ONE eval cell measures the repo and computes the node formula.\n2. **Map** (dag) - `quick` scanner nodes extract per-chunk facts into bounded file reports.\n3. **Reduce** (dag) - `unspecified-high` writer nodes own disjoint subtrees: score, write AGENTS.md files, emit digests.\n4. **Root & verify** (dag) - one node writes root AGENTS.md from digests only; one node verifies every file.\n5. **Snapshot & mode** (main session) - snapshot contract unchanged.\n\n<critical>\n**THE ALWAYS-REDUCE RULE.** The main session NEVER reads chunk reports or raw node outputs - only the verify node's verdict and, when a repair needs it, one digest. Context protection is structural (bounded fan-in at every stage), never a runtime \"how much context is left\" guess.\n\n`todo` init the five phases; `start`/`done` each transition in real time.\n</critical>\n\n---\n\n## Phase 1: Size & Route\n\nMeasure and compute in ONE eval cell - code, not mental arithmetic:\n\n```python\n# Measure (tracked files minus vendored/generated: node_modules, .git, dist,\n# build, out, vendor, target, coverage, lockfiles, minified and binary files)\nS        = total source bytes after exclusions\nper_dir  = source bytes per directory            # bin-packing input\ndepth    = max directory depth                   # respect --max-depth (default 3)\nexisting = every AGENTS.md / CLAUDE.md path      # read the ROOT one now\n\n# Formula\nCHUNK   = 400 * 1024          # ~100k tokens of source; a quick worker's usable window\n                              # is ~150k over its fallback chain - leave room for its\n                              # prompt and report\nN_quick = ceil(S / CHUNK)     # bin-pack WHOLE directories into chunks; a directory\n                              # larger than one chunk splits at its children\nN_high  = ceil(N_quick / 12)  # one reducer absorbs ~12 reports (~60k tokens) and\n                              # still has room to spot-check real code\n```\n\nRoute:\n\n- **N_quick < 4** -> inline path below; a dag costs more than it saves.\n- **N_quick > `task.dag.max_nodes_per_run` (default 64)** -> raise the knob in omo config, or run one chained dag per top-level directory (multi-run composition, `mass-ulw` skill).\n- **Otherwise** -> dag path: emit `CHUNKS = [{id, dirs, bytes}]`, assign each writer a directory SUBTREE (disjoint - no two writers own the same directory), and `mkdir -p .omo/init-deep/reports .omo/init-deep/digests`.\n\n`--create-new`: read every existing AGENTS.md FIRST (still-true facts survive as scanner input), then delete all, then regenerate.\n\n### Inline path (N_quick < 4)\n\nSmall repo - skip the dag. Fire 2-4 parallel `explore` agents (structure, entry points, conventions, anti-patterns), for example:\n\n```\ntask(subagent_type=\"explore\", run_in_background=true, prompt=\"Project structure: map real layout via ast-grep structural search (sg/ast_grep MCP) + rg --files -> REPORT deviations from standard patterns\")\n```\n\nRun the LSP/ast-grep code map yourself (`lsp_symbols` outlines + workspace inventory, `lsp_find_references` on top exports, ast-grep import/call shapes; when neither resolves, mark centrality unmeasured). Then score with the matrix below and write every file per the templates yourself. Phase 5 applies unchanged.\n\n---\n\n## Phase 2: Map Wave - `quick` Scanners (dag)\n\nBuild and start the run in one eval JS cell with the dag SDK (`OMO_DAG_SDK_ROOT`); wave doctrine, the node prompt contract, and the failure playbook come from the `mass-ulw` skill's `references/planning.md`. One scanner node per chunk, `category: \"quick\"`, no `load_skills` - scanners stay lean and their prompt is a rigid numbered extraction template. Quick workers extract; they never judge and never write AGENTS.md:\n\n```\nTASK: Extract knowledge-base facts for chunk <id> (<dirs>) of <repo-root>.\nSteps, in order:\n1. Inventory each directory in scope: file count, LOC, languages, entry files.\n2. Public exports/symbols other code imports - lsp_symbols and ast-grep\n   import/call shapes, never file-name guesses.\n3. Conventions that DEVIATE from stack defaults (configs, naming, layout).\n4. Anti-patterns: DO NOT / NEVER / ALWAYS / DEPRECATED comments, forbidden patterns.\n5. Hotspots: files >500 lines, high-reference symbols, complexity concentrations.\n6. Build/test/dev commands touching these dirs.\nDELIVERABLE: EXACTLY ONE file `.omo/init-deep/reports/<id>.md`, <=5k tokens, sections\n`# CHUNK <id>` / `## INVENTORY` / `## EXPORTS` / `## CONVENTIONS` / `## ANTI-PATTERNS`\n/ `## HOTSPOTS` / `## COMMANDS`; an empty section says `none`.\nSCOPE: read only <dirs>; write only your report file. If an AGENTS.md exists in scope,\nquote its still-true claims into the matching sections.\nVERIFY: the report file exists and every section header is present.\nSTOP WHEN: the report is written and verified.\n```\n\n---\n\n## Phase 3: Reduce Wave - `unspecified-high` Writers (same dag)\n\nOne writer node per subtree, `dependsOn` its chunks' scanner ids, `load_skills: [\"init-deep\"]` - every writer carries this file, so the scoring matrix and templates below ARE its instructions:\n\n```\nTASK: Own subtree <path>: produce its AGENTS.md files for the repo knowledge base.\nSteps, in order:\n1. Read your chunk reports: .omo/init-deep/reports/<ids>.md. Reports are claims,\n   not truth - spot-check real code wherever they conflict or look thin.\n2. Score each directory with the init-deep Scoring Matrix; pick locations with the\n   Decision Rules (both are in the init-deep skill content loaded with this task).\n3. Write each AGENTS.md per the templates and the File Writing Rule. 30-80 lines,\n   never repeating parent content.\n4. Write .omo/init-deep/digests/<subtree-slug>.md, <=2k tokens: every location\n   written (score, one-line role) plus cross-subtree facts the root file must know.\nSCOPE: write only inside <path> plus your digest file. Root AGENTS.md is OUT of scope.\nVERIFY: every location chosen in step 2 exists on disk within line limits; digest exists.\nSTOP WHEN: files and digest are written and verified.\n```\n\n---\n\n## Phase 4: Root & Verify (same dag)\n\n- **root-writer** - `category: \"unspecified-high\"`, `load_skills: [\"init-deep\"]`, dependsOn every writer. Reads ONLY `.omo/init-deep/digests/*` plus the existing root AGENTS.md; writes the root file per the template below. Never reads chunk reports.\n- **verify** - `category: \"quick\"`, dependsOn root-writer. Checks: every digest-declared path exists; root is 50-150 lines; subdirectory files 30-80; no child repeats a parent section block. DELIVERABLE: one `PASS` / `FAIL <path>: <reason>` line per file.\n\nThe main session reads the verify node's output and nothing else. Each FAIL line -> `dag send` the owning writer with the named defect (or `retry` it), then re-run verify. Loop until all PASS. Fixing files yourself by reading reports is a defect - repair flows through the dag.\n\n---\n\n## Scoring & Location (each writer applies this to its subtree; the inline path applies it repo-wide)\n\n### Scoring Matrix\n\n| Factor | Weight | High Threshold | Source |\n|--------|--------|----------------|--------|\n| File count | 3x | >20 | bash |\n| Subdir count | 2x | >5 | bash |\n| Code ratio | 2x | >70% | bash |\n| Unique patterns | 1x | Has own config | explore |\n| Module boundary | 2x | Has index.ts/__init__.py | bash |\n| Symbol density | 2x | >30 symbols | LSP/sg |\n| Export count | 2x | >10 exports | LSP/sg |\n| Reference centrality | 3x | >20 refs | LSP/sg |\n\n### Decision Rules\n\n| Score | Action |\n|-------|--------|\n| **Root (.)** | ALWAYS create |\n| **>15** | Create AGENTS.md |\n| **8-15** | Create if distinct domain |\n| **<8** | Skip (parent covers) |\n\n### Output\n```\nAGENTS_LOCATIONS = [\n  { path: \".\", type: \"root\" },\n  { path: \"src/hooks\", score: 18, reason: \"high complexity\" },\n  { path: \"src/api\", score: 12, reason: \"distinct domain\" }\n]\n```\n\n---\n\n## Templates & File Writing Rule\n\n<critical>\n**File Writing Rule**: If AGENTS.md already exists at the target path → use `Edit` tool. If it does NOT exist → use `Write` tool.\nNEVER use Write to overwrite an existing file. ALWAYS check existence first via `Read` or discovery results.\n</critical>\n\n### Root AGENTS.md (Full Treatment)\n\n```markdown\n# PROJECT KNOWLEDGE BASE\n\n**Generated:** {TIMESTAMP}\n**Commit:** {SHORT_SHA}\n**Branch:** {BRANCH}\n\n## OVERVIEW\n{1-2 sentences: what + core stack}\n\n## STRUCTURE\n```\n{root}/\n├── {dir}/    # {non-obvious purpose only}\n└── {entry}\n```\n\n## WHERE TO LOOK\n| Task | Location | Notes |\n|------|----------|-------|\n\n## CODE MAP\n{From LSP/ast-grep - skip only if neither exists or project <10 files}\n\n| Symbol | Type | Location | Refs | Role |\n|--------|------|----------|------|------|\n\n## CONVENTIONS\n{ONLY deviations from standard}\n\n## ANTI-PATTERNS (THIS PROJECT)\n{Explicitly forbidden here}\n\n## UNIQUE STYLES\n{Project-specific}\n\n## COMMANDS\n```bash\n{dev/test/build}\n```\n\n## NOTES\n{Gotchas}\n```\n\n**Quality gates**: 50-150 lines, no generic advice, no obvious info.\n\n### Subdirectory AGENTS.md\n\n30-80 lines max. Sections: OVERVIEW (1 line), STRUCTURE (only if >5 subdirs), WHERE TO LOOK, CONVENTIONS (only if different from parent), ANTI-PATTERNS. NEVER repeat parent content; note why the directory earned its file (score, distinct domain).\n\n---\n\n## Phase 5: Snapshot & Mode\n\nAsk the user: **Local or committed?**\n\nCapture the answer as `USER_MODE_CHOICE`. The explicit answer is authoritative:\n- `local` keeps the generated guidance personal to this checkout.\n- `committed` reruns the change through the `work-with-pr` skill so the generated guidance lands through a reviewed PR.\n- If no explicit answer is available, tracked `AGENTS.md` status is the fallback.\n\nRun these commands after the review is complete:\n\n```bash\n# Snapshot — create complete JSON with all fields, milliseconds timestamp\nmkdir -p .omo\nSHA=$(git rev-parse HEAD)\n# Count tracked files (NUL byte counting, chunk-boundary safe)\nFILES=$(git ls-files -z | node -e 'let c=0;process.stdin.on(\"data\",d=>{for(let i=0;i<d.length;i++)if(d[i]===0)c++});process.stdin.on(\"end\",()=>process.stdout.write(String(c)))')\nLOC=$(git ls-files -z -- '*.ts' '*.tsx' '*.js' '*.jsx' '*.py' '*.go' '*.rs' '*.java' '*.kt' '*.swift' '*.rb' '*.php' '*.c' '*.cpp' '*.cs' '*.scala' '*.lua' '*.ex' '*.exs' '*.zig' '*.dart' | xargs -0 wc -l 2>/dev/null | tail -1 | awk '{print $1}')\nNOW=$(node -e 'console.log(Date.now())')\nUSER_MODE_CHOICE=\"${USER_MODE_CHOICE:-}\" && if [ \"$USER_MODE_CHOICE\" = \"committed\" ]; then MODE=committed; elif [ \"$USER_MODE_CHOICE\" = \"local\" ]; then MODE=local; elif git ls-files --error-unmatch AGENTS.md >/dev/null 2>&1; then MODE=committed; else MODE=local; fi\ncat > .omo/init-deep.json <<EOF\n{\"commitSha\":\"$SHA\",\"fileCount\":$FILES,\"loc\":${LOC:-0},\"timestamp\":$NOW,\"mode\":\"$MODE\"}\nEOF\n# Local mode exclude — managed block (idempotent, never clobbers user lines)\nif [ \"$MODE\" = \"local\" ]; then\n  EXCLUDE=$(git rev-parse --git-path info/exclude)\n  mkdir -p \"$(dirname \"$EXCLUDE\")\"\n  if ! grep -q '# >>> omo-senpi init-deep local (managed)' \"$EXCLUDE\" 2>/dev/null; then\n    cat >> \"$EXCLUDE\" <<'BLOCK'\n# >>> omo-senpi init-deep local (managed)\n# Do not edit this block; rerun init-deep or switch modes.\n/.omo/init-deep.json\nAGENTS.md\n# <<< omo-senpi init-deep local (managed)\nBLOCK\n  fi\nfi\n# Nested AGENTS.md discovery\nfind . -name AGENTS.md -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/dist/*' -not -path '*/build/*'\n```\n\nWhen switching from local mode to committed mode, remove the managed block before rerunning through `work-with-pr`:\n\n```bash\nEXCLUDE=$(git rev-parse --git-path info/exclude) && sed -i.bak \"/# >>> omo-senpi init-deep local (managed)/,/# <<< omo-senpi init-deep local (managed)/d\" \"$EXCLUDE\" && rm -f \"$EXCLUDE.bak\"\n```\n\n`USER_MODE_CHOICE=committed` selects committed mode even when `AGENTS.md` is untracked. `USER_MODE_CHOICE=local` selects local mode even when `AGENTS.md` is tracked. `.git/info/exclude` cannot hide changes to an already tracked file, so explicit local mode on a tracked `AGENTS.md` is informational only and the file remains visible to git.\n\n---\n\n## Cleanup\n\nAfter the snapshot: `rm -rf .omo/init-deep` - reports and digests are ephemeral scaffolding; `.omo/init-deep.json` is the only artifact that stays. Record the removal in the final report.\n\n---\n\n## Final Report\n\n```\n=== init-deep Complete ===\n\nMode: {update | create-new}\nSizing: S={MB} source -> {N_quick} scanners, {N_high} writers ({dag | inline} path)\nCleanup: .omo/init-deep removed\n\nFiles:\n  [OK] ./AGENTS.md (root, {N} lines)\n  [OK] ./src/hooks/AGENTS.md ({N} lines)\n\nDirs Analyzed: {N}\nAGENTS.md Created: {N}\nAGENTS.md Updated: {N}\n\nHierarchy:\n  ./AGENTS.md\n  └── src/hooks/AGENTS.md\n```\n\n---\n\n## Anti-Patterns\n\n- **Main session reading reports or node outputs**: always-reduce is structural - repair via `dag send`, never by pulling scan data into your own context\n- **One node per file or per source**: nodes own BATCHES; the formula sets N\n- **Free-form scanner prompts**: quick workers get numbered extraction steps only\n- **Sequential execution**: MUST parallel (map wave fans out; inline path runs explore + LSP + ast-grep concurrently)\n- **Ignoring existing**: ALWAYS read existing first, even with --create-new\n- **Over-documenting**: Not every dir needs AGENTS.md\n- **Redundancy**: Child never repeats parent\n- **Generic content**: Remove anything that applies to ALL projects\n- **Verbose style**: Telegraphic or die","author":"@code-yeongyu","ownerProfile":null,"authorContacts":null,"sourceUrl":"https://github.com/code-yeongyu/oh-my-openagent/tree/dev/packages/omo-senpi/plugin/skills/init-deep","license":"MIT","category":"writing","lang":"en","tokens":3683,"stars":0,"calls30d":1,"claimed":false,"visibility":"public","origin":"crawler","version":"0.1.0","createdAt":"2026-08-22","updatedAt":"2026-08-22","files":[],"requires":{"mcp":[],"tools":[]},"safety":{"flags":[],"scannedAt":"2026-08-22","hasScripts":false,"networkEndpoints":[]}}