取り組みの背景
プロジェクトが成長するにつれ、コードと実際のドキュメントの間に乖離が生まれるのは避けがたい問題です。手動でドキュメントを更新し続けるのは現実的ではなく、やがて「コードが唯一の真実」という状態に陥りがちです。
対象読者は、ある程度TypeScript/JavaScriptの開発経験があり、ドキュメント管理に課題を感じている方です。
前提知識と環境準備
この記事を進めるにあたって、以下の環境が必要です。
- Antigravity IDE(最新版)
- Node.js 20以上
- TypeScript プロジェクト(JSDoc/TSDocが記述されていること)
- GitHub リポジトリ(CI/CD連携を行う場合)
まず、ドキュメント生成に使用するパッケージをインストールします。
# ドキュメント生成ツールのインストール
npm install -D typedoc typedoc-plugin-markdown unified remark-parse remark-stringifyAIエージェントによるコードベース解析
Antigravity のエージェント機能は、プロジェクト全体のコード構造を理解した上で作業を行えるため、単純な正規表現ベースのドキュメント生成ツールよりも文脈を踏まえた出力が可能です。
agents.md でドキュメント生成エージェントを定義する
プロジェクトルートに agents.md を作成し、ドキュメント生成専用のエージェントを定義します。
# Doc Generator Agent
## Role
コードベースを解析し、技術文書を自動生成するエージェント。
## Instructions
1. src/ 配下の全 .ts ファイルを走査する
2. エクスポートされた関数・クラス・型のJSDoc/TSDocコメントを抽出する
3. 以下の形式でMarkdownドキュメントを生成する:
- 関数名・クラス名を見出しとして使用
- パラメータの型と説明を表形式で記載
- 戻り値の型と説明を記載
- 使用例がある場合はコード例として含める
4. 生成したドキュメントを docs/ ディレクトリに配置する
## Context
- TypeScriptプロジェクト
- 出力形式: Markdown
- 既存のドキュメントがある場合は差分のみ更新TypeDoc連携スクリプト
AIエージェントの出力を補完するため、TypeDocを使った構造化された解析も併用します。
// scripts/generate-docs.ts
import { Application, TSConfigReader } from "typedoc";
import * as fs from "fs";
import * as path from "path";
interface DocEntry {
name: string;
kind: string;
description: string;
parameters?: { name: string; type: string; description: string }[];
returnType?: string;
example?: string;
}
async function generateDocs(): Promise<void> {
const app = await Application.bootstrapWithPlugins({
entryPoints: ["src/index.ts"],
plugin: ["typedoc-plugin-markdown"],
tsconfig: "tsconfig.json",
});
app.options.addReader(new TSConfigReader());
const project = await app.convert();
if (!project) {
console.error("TypeDoc conversion failed");
process.exit(1);
}
// Markdown形式で出力
const outputDir = path.resolve("docs/api");
await app.generateDocs(project, outputDir);
console.log(`✅ API documentation generated at ${outputDir}`);
// 生成されたファイル数をレポート
const files = fs.readdirSync(outputDir, { recursive: true });
const mdFiles = (files as string[]).filter((f) => f.endsWith(".md"));
console.log(`📄 Generated ${mdFiles.length} documentation files`);
}
generateDocs().catch(console.error);期待する出力:
✅ API documentation generated at /project/docs/api
📄 Generated 24 documentation files
AIエージェントでREADME・設計書を自動生成する
TypeDocはAPIリファレンスの生成に優れていますが、人間が読むREADMEやアーキテクチャ設計書の生成にはAIの力が必要です。
Antigravity のインラインチャットを活用する
Antigravity の Cmd + I(インラインチャット)で以下のプロンプトを使うと、プロジェクト構造を踏まえたREADMEを生成できます。
このプロジェクトのREADME.mdを生成してください。
以下のセクションを含めてください:
- プロジェクト概要(package.jsonのdescriptionを参照)
- インストール手順
- 使い方(主要なAPIの使用例)
- ディレクトリ構造
- 開発環境のセットアップ
- テストの実行方法
- ライセンス
バッチ処理でディレクトリごとにREADMEを生成
大規模プロジェクトでは、各ディレクトリに個別のREADMEが必要な場合があります。以下のスクリプトでバッチ処理を実現します。
// scripts/generate-module-readmes.ts
import * as fs from "fs";
import * as path from "path";
interface ModuleInfo {
dirPath: string;
files: string[];
exports: string[];
dependencies: string[];
}
function analyzeModule(dirPath: string): ModuleInfo {
const files = fs.readdirSync(dirPath).filter((f) => f.endsWith(".ts"));
const exports: string[] = [];
const dependencies: string[] = [];
for (const file of files) {
const content = fs.readFileSync(path.join(dirPath, file), "utf-8");
// export文を抽出
const exportMatches = content.matchAll(
/export\s+(?:default\s+)?(?:function|class|const|type|interface)\s+(\w+)/g
);
for (const match of exportMatches) {
exports.push(match[1]);
}
// import文から依存関係を抽出
const importMatches = content.matchAll(/from\s+["']([^"']+)["']/g);
for (const match of importMatches) {
if (!match[1].startsWith(".")) {
dependencies.push(match[1]);
}
}
}
return { dirPath, files, exports, dependencies: [...new Set(dependencies)] };
}
function generateReadme(info: ModuleInfo): string {
const moduleName = path.basename(info.dirPath);
return `# ${moduleName}
## Overview
This module contains ${info.files.length} file(s) and exports ${info.exports.length} symbol(s).
## Exports
${info.exports.map((e) => `- \`${e}\``).join("\n")}
## Files
${info.files.map((f) => `- \`${f}\``).join("\n")}
## Dependencies
${info.dependencies.length > 0 ? info.dependencies.map((d) => `- \`${d}\``).join("\n") : "No external dependencies."}
`;
}
// src/ 配下の各ディレクトリを処理
const srcDir = path.resolve("src");
const dirs = fs
.readdirSync(srcDir, { withFileTypes: true })
.filter((d) => d.isDirectory())
.map((d) => path.join(srcDir, d.name));
for (const dir of dirs) {
const info = analyzeModule(dir);
if (info.files.length > 0) {
const readme = generateReadme(info);
fs.writeFileSync(path.join(dir, "README.md"), readme);
console.log(`📝 Generated README for ${path.basename(dir)}`);
}
}CI/CDパイプラインとの統合
ドキュメント生成を手動で実行するのでは、結局は更新漏れが発生します。GitHub Actionsと連携して、コード変更のたびに自動更新する仕組みを構築しましょう。
GitHub Actions ワークフロー
# .github/workflows/docs.yml
name: Generate Documentation
on:
push:
branches: [main]
paths:
- "src/**/*.ts"
- "scripts/generate-docs.ts"
jobs:
generate-docs:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: "20"
- name: Install dependencies
run: npm ci
- name: Generate API documentation
run: npx ts-node scripts/generate-docs.ts
- name: Generate module READMEs
run: npx ts-node scripts/generate-module-readmes.ts
- name: Check for changes
id: check
run: |
git diff --quiet docs/ || echo "changed=true" >> $GITHUB_OUTPUT
- name: Commit and push
if: steps.check.outputs.changed == 'true'
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git add docs/
git commit -m "docs: auto-update documentation"
git push差分検出と通知
ドキュメントが大幅に変更された場合に通知を受けるスクリプトも用意しておくと便利です。
// scripts/check-doc-drift.ts
import { execSync } from "child_process";
// 前回のドキュメント生成からの差分行数を取得
const diff = execSync("git diff --stat docs/").toString();
const lines = diff.split("\n");
const summaryLine = lines[lines.length - 2] || "";
// "N files changed, N insertions(+), N deletions(-)" をパース
const match = summaryLine.match(/(\d+)\s+file.*?(\d+)\s+insertion.*?(\d+)\s+deletion/);
if (match) {
const [, files, insertions, deletions] = match;
const totalChanges = parseInt(insertions) + parseInt(deletions);
console.log(`📊 Documentation drift report:`);
console.log(` Files changed: ${files}`);
console.log(` Lines added: ${insertions}`);
console.log(` Lines removed: ${deletions}`);
// 変更が大きい場合は警告
if (totalChanges > 100) {
console.warn(`⚠️ Large documentation drift detected (${totalChanges} lines)`);
console.warn(` Consider reviewing the generated documentation manually.`);
process.exit(1);
}
}応用:カスタムテンプレートによるドキュメント生成
プロジェクト固有のドキュメント形式がある場合、テンプレートエンジンと組み合わせることで柔軟な出力が可能です。
// scripts/custom-template.ts
interface TemplateContext {
projectName: string;
version: string;
modules: {
name: string;
description: string;
functions: {
name: string;
signature: string;
description: string;
}[];
}[];
}
function renderTemplate(template: string, context: TemplateContext): string {
let result = template;
// 基本変数の置換
result = result.replace(/\{\{projectName\}\}/g, context.projectName);
result = result.replace(/\{\{version\}\}/g, context.version);
// モジュールセクションのレンダリング
const moduleSection = context.modules
.map(
(mod) => `
### ${mod.name}
${mod.description}
| Function | Signature | Description |
|----------|-----------|-------------|
${mod.functions.map((fn) => `| \`${fn.name}\` | \`${fn.signature}\` | ${fn.description} |`).join("\n")}
`
)
.join("\n");
result = result.replace(/\{\{modules\}\}/g, moduleSection);
return result;
}
// 使用例
const context: TemplateContext = {
projectName: "MyProject",
version: "1.0.0",
modules: [
{
name: "auth",
description: "認証モジュール",
functions: [
{
name: "login",
signature: "(email: string, password: string) => Promise<User>",
description: "ユーザーログイン処理",
},
{
name: "logout",
signature: "() => Promise<void>",
description: "セッションの終了",
},
],
},
],
};
const template = `# {{projectName}} v{{version}} API Reference\n\n{{modules}}`;
console.log(renderTemplate(template, context));まとめ
ここではAntigravity のAIエージェントとTypeDocを組み合わせて、コードベースから技術文書を自動生成するパイプラインを構築する方法を解説しました。
重要なポイントは以下の3つです。
- agents.md でドキュメント生成エージェントを定義 — プロジェクトの文脈を理解した上で、人間が読みやすいドキュメントを生成できる
- TypeDocとの併用 — 型情報の正確な抽出はTypeDocに任せ、AIは説明文や使用例の生成に集中させる
- CI/CDとの統合 — GitHub Actionsでコード変更に連動した自動更新を実現し、ドキュメントの陳腐化を防ぐ
ドキュメントの品質はプロジェクトの持続可能性に直結します。自動化によって「書く負担」を減らしつつ、「読む価値」のあるドキュメントを維持していきましょう。