# Initial Codebase Wiki Construction Algorithm

## Thesis

The first `codealmanac` wiki should be generated by a source-grounded bootstrap
agent that compiles a small set of substantive, interlinked pages from three
evidence strata:

1. the repository's static structure and code graph,
2. existing human-authored docs and configuration,
3. optional historical conversations, PRs, issues, plans, and session logs.

The winning algorithm is not "summarize every file." It is "construct an
orientation graph for future agents": identify stable entities, cross-file
flows, decisions, constraints, operational gotchas, and active work; write only
pages that pass a notability bar; and cite the files or history records that
support each claim. Code documentation generators, DeepWiki-like systems, and
repo-map tools are useful as scaffolding, but `codealmanac` should avoid their
common failure mode: code-shaped pages that restate implementation details
without preserving why the code is shaped that way.

## Source Base

Primary and near-primary sources reviewed:

- DeepWiki-Open generation docs and source prompt: repository analysis, wiki
  structure determination from file tree plus README, then per-page generation
  from relevant files with required source citations and diagrams
  ([DeepWiki page](https://deepwiki.com/mathur-exe/deepwiki-open/5.2-generating-a-wiki),
  [source prompt](https://raw.githubusercontent.com/AsyncFuncAI/deepwiki-open/main/src/app/%5Bowner%5D/%5Brepo%5D/page.tsx)).
- CodeWiki project and paper page: hierarchical decomposition, recursive
  agentic processing, multi-modal synthesis, and repository-level evaluation
  across large multilingual repos
  ([project](https://fsoft-ai4code.github.io/CodeWiki/),
  [GitHub](https://github.com/fsoft-ai4code/CodeWiki),
  [arXiv](https://arxiv.org/abs/2510.24428)).
- RepoAgent: AST-based object extraction, bidirectional invocation
  relationships, Git-change tracking, and generated Markdown documentation
  ([arXiv](https://arxiv.org/abs/2402.16667),
  [GitHub](https://github.com/OpenBMB/RepoAgent)).
- DocAgent: Reader/Searcher/Writer/Verifier/Orchestrator agents, topological
  code processing, and evaluation by completeness/helpfulness/truthfulness
  ([arXiv](https://arxiv.org/abs/2504.08725)).
- Sourcegraph Cody context architecture: BM25-like search, local IDE context,
  global snippet ranking, and multiple retrieval lenses including code graph and
  search indexes
  ([How Cody understands your codebase](https://sourcegraph.com/blog/how-cody-understands-your-codebase),
  [RAG to riches](https://sourcegraph.com/blog/rag-to-riches)).
- aider repo-map: Tree-sitter extraction of definitions/references and ranking
  important identifiers rather than dumping all code
  ([aider repo-map docs](https://git.joshthomas.dev/mirrors/aider/src/commit/3c817e98954d74c308aaf2619b8638dca69a2ba3/docs/repomap.md)).
- Repomix and Gitingest: whole-repo, LLM-friendly packing as a useful digest
  baseline
  ([Repomix docs](https://repomix.com/guide/),
  [Gitingest](https://gitingest.com/)).
- Google Code Wiki: full-codebase scanning, regenerated docs, direct links to
  code files/classes/functions, and generated architecture/class/sequence
  diagrams
  ([Google Developers Blog](https://developers.googleblog.com/introducing-code-wiki-accelerating-your-code-understanding/)).
- Documentation generators: Sphinx autodoc/apidoc, TypeDoc, JSDoc, Doxygen as
  API-reference baselines rather than living-wiki solutions
  ([Sphinx autodoc](https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html),
  [Sphinx apidoc](https://www.sphinx-doc.org/en/master/usage/extensions/apidoc.html),
  [TypeDoc](https://typedoc.org/documents/Overview.html),
  [JSDoc](https://jsdoc.app/about-getting-started),
  [Doxygen](https://github.com/doxygen/doxygen)).
- Code graph systems and papers: Tree-sitter, CodexGraph, GraphCoder,
  Codebase-Memory
  ([Tree-sitter](https://github.com/tree-sitter/tree-sitter),
  [CodexGraph](https://arxiv.org/abs/2408.03910),
  [GraphCoder](https://arxiv.org/abs/2406.07003),
  [Codebase-Memory](https://arxiv.org/abs/2603.27277)).
- History and rationale mining: ADR practice, GitHub pull request discussion
  model, and DRMiner design-rationale mining from issue logs
  ([ADR](https://adr.github.io/),
  [GitHub PR docs](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests),
  [DRMiner](https://arxiv.org/abs/2405.19623)).
- Claude Agent SDK and hooks: subagents with separate context and tool
  restrictions; SessionEnd hooks with transcript paths
  ([SDK subagents](https://platform.claude.com/docs/en/agent-sdk/subagents),
  [hooks reference](https://code.claude.com/docs/en/hooks)).

## Prior Art, Distilled

### DeepWiki Shape-Then-Fill

DeepWiki-Open uses a two-step LLM process:

```text
file tree + README -> wiki structure
wiki page topic + relevant files -> page markdown
```

The structure prompt asks for pages, importance levels, related pages, and
relevant files. The page prompt requires grounding in relevant source files,
file citations, diagrams, tables, and technical accuracy. This produces a
browsable wiki quickly, and the "relevant files first" move is important: a
page is anchored to a bounded evidence set before prose is generated.

What transfers to `codealmanac`:

- first choose the page map, then write pages;
- make every page declare file coverage;
- require source-grounded claims;
- generate diagrams only when they explain cross-file structure.

What does not transfer cleanly:

- XML structure as an orchestration artifact;
- "at least five source files" as a universal rule;
- page templates dominated by API/architecture explanation;
- hosted/cache-driven generated docs as the product shape.

### CodeWiki Hierarchical Atlas

CodeWiki frames repository-level documentation as a hierarchy problem. Large
repos are decomposed into coherent modules, processed recursively by agents, and
assembled into text plus diagrams. Its core contribution is scale: the system
does not ask one model call to understand a 1M LOC repo. It recursively breaks
the repo into modules while preserving architectural context.

What transfers:

- decompose by meaningful modules, not arbitrary chunks;
- let subagents own bounded areas;
- synthesize from module briefs into a top-level wiki;
- keep multiple granularities: overview, subsystem, flow.

What to avoid:

- turning bootstrap into a persistent multi-stage pipeline with formal IRs;
- generating complete documentation coverage when the wiki's purpose is
  non-obvious knowledge.

### RepoAgent Object Graph

RepoAgent extracts code structure with AST analysis, identifies bidirectional
object invocation relationships, and uses Git change tracking to maintain docs.
This is useful evidence for initial wiki generation because it reveals high
fan-in symbols, entrypoints, and call relationships that a plain file tree
misses.

What transfers:

- use AST/import/call evidence to find important anchors;
- rank entities by reference and invocation relationships;
- detect changed/stale areas later through Git.

What to avoid:

- documenting every object or file;
- confusing function-level docs with project memory.

### DocAgent Topological Context Build

DocAgent uses specialized agents and topological code processing. Its key
insight is that documentation quality improves when upstream dependencies are
understood before downstream dependents. It evaluates outputs along
completeness, helpfulness, and truthfulness.

What transfers:

- process dependency roots before leaves;
- use separate reader/searcher/writer/verifier roles;
- give verification an explicit truthfulness mandate.

What to avoid:

- an external Orchestrator state machine for `codealmanac`;
- treating "complete" as "all objects covered."

### Cody Context Lenses

Sourcegraph's Cody chooses context through multiple lenses: search, code
intelligence, local IDE files, snippet ranking, and tuned relevance signals. The
lesson is that codebase understanding is not one retrieval method. BM25-style
search finds lexical matches, code graph finds structural dependencies, and
local context captures current work.

What transfers:

- use multiple context providers during bootstrap;
- rank snippets/files globally before writing;
- combine current repo and local/session context.

What to avoid:

- building semantic search before FTS/code graph evidence proves insufficient;
- relying on raw chunk retrieval as the final memory artifact.

### aider Repo-Map

aider's repo-map uses Tree-sitter to extract definitions and references, then
shows the most important identifiers rather than every class/function. This is
exactly the right bias for bootstrap: a future coding agent needs the anchors
that organize the repo, not a dump.

What transfers:

- use Tree-sitter or language-native tools to extract definitions and refs;
- rank by graph centrality, fan-in/fan-out, and path importance;
- fit the map to a token budget.

What to avoid:

- making the repo-map itself the wiki;
- overfitting to symbols when the wiki also needs decisions and constraints.

### Repo Digest Tools

Repomix and Gitingest package a repository into an AI-friendly text digest.
They are useful for small repos and for debugging prompts. Their limitation is
that they shift the burden to the model's context window and do not decide what
knowledge should persist.

What transfers:

- deterministic ignore rules;
- directory tree plus file content with clear separators;
- optional whole-repo digest for small repos.

What to avoid:

- feeding a large repo wholesale and hoping the model self-organizes;
- writing a wiki that is just a compressed digest.

### Documentation Generators

Sphinx autodoc/apidoc, TypeDoc, JSDoc, and Doxygen prove that API docs can be
kept near source and generated mechanically. They are strongest when code has
docstrings/comments and public APIs. They are weak at decisions, failed
experiments, business constraints, incidents, active migrations, and "why this
weird edge case exists."

For `codealmanac`, generated API documentation is an input signal, not the
output. If a repo already has Doxygen/Sphinx/TypeDoc, bootstrap should read
their config and docs to discover public API boundaries and terminology, but it
should not mirror them into `.almanac/`.

### Conversation and Rationale Mining

ADR practice says a decision record captures a single decision, rationale,
trade-offs, and consequences. GitHub pull requests contain descriptions,
comments, reviews, commits, checks, and file diffs. DRMiner shows that issue
logs can contain latent design rationales and that extracting alternatives and
arguments is a real mining task, not plain summarization.

What transfers:

- past conversations are evidence for why, not a separate wiki namespace;
- mine decisions, rejected alternatives, constraints, incidents, and gotchas;
- attach dates and provenance when the source is historical;
- cross-check historical claims against current code before writing them as
  current facts.

What to avoid:

- treating every conversation as notable;
- importing stale claims without labeling them;
- letting transcript summaries override the repository.

## Named Approaches

### 1. Digest Baseline

Pack the repository into a single prompt-friendly artifact and ask the model to
write a wiki.

```pseudo
digest = build_repo_digest(repo, ignores)
wiki = model("Write a wiki from this repo", digest)
```

Use only for tiny repos or as a sanity-check baseline. It is cheap to explain
but poor at scale and poor at notability.

### 2. Shape-Then-Fill

First ask for a page plan from the file tree and docs; then generate each page
from selected files.

```pseudo
tree = list_files(repo)
docs = read(["README*", "CLAUDE.md", "AGENTS.md", "docs/**", manifests])
page_plan = model("Choose wiki pages and relevant files", tree, docs)

for page in page_plan:
  evidence = read(page.relevant_files)
  write_page(model("Write grounded page", page, evidence))
```

This is the DeepWiki family. Good for fast first output. Needs strong guardrails
against generic architecture pages.

### 3. Hierarchical Atlas

Decompose the repo into modules, let agents summarize modules, then synthesize
pages from module briefs.

```pseudo
modules = partition_repo_by_package_imports_and_dirs(repo)
briefs = parallel_map(modules, module_agent)
atlas = synthesize_global_map(briefs)
pages = write_pages_from_atlas(atlas, briefs)
```

Best for large repos. Good module partitioning matters more than the model.

### 4. Graph-First Bootstrap

Build a symbol/import/file graph and use it to select anchors and flows.

```pseudo
G = build_graph(files, imports, definitions, references, configs)
ranked = rank_nodes(G, centrality + entrypoint_bonus + manifest_bonus)
flows = detect_paths(G, from=entrypoints, to=[db, queue, network, filesystem])
pages = choose_pages(ranked, flows)
```

Excellent at finding what code says. Insufficient for why.

### 5. History-Augmented Bootstrap

Mine conversations, PRs, issues, commits, and existing plans for rationale and
compare the claims to current repo evidence.

```pseudo
history = load_optional_history_sources()
claims = extract_notable_claims(history,
  types=[decision, rejected_alternative, gotcha, incident, migration, invariant])

for claim in claims:
  current_support = search_repo_for_support_or_contradiction(claim)
  if claim.notable and current_support != contradicted:
    add_to_candidate_pages(claim, provenance=history.source)
```

This is the only approach that can recover "what the code cannot say." It must
be paired with current-code verification.

### 6. Agentic Wiki Compilation

Give a writer agent tools and standards, let it read selectively, delegate
bounded investigations, write directly, then invoke a reviewer. This matches
the `codealmanac` design philosophy.

```pseudo
bootstrap_writer(
  repo,
  current_wiki_empty,
  optional_history,
  tools=[Read, Grep, Glob, Bash, Write, Agent],
  agents={reviewer, scouts...}
)
```

The key difference from a pipeline is ownership: deterministic code can prepare
cheap evidence, but the writer owns judgment and page edits.

## Recommended Model: Atlas Bootstrap

`codealmanac bootstrap` should use an "Atlas Bootstrap" model:

```text
deterministic repo census
  -> parallel read-only scout briefs
  -> writer-owned page slate
  -> direct page writes
  -> reviewer critique
  -> writer finalization
```

This gives the quality benefits of CodeWiki/DocAgent without violating
`codealmanac`'s "intelligence in prompts, not pipelines" rule.

### Phase 0: Inputs

Required:

- repo root;
- empty or existing `.almanac/`;
- file tree;
- package/build/deploy manifests;
- existing docs and agent instructions;
- source files selected by the agent.

Optional:

- Claude/Codex/Cursor session transcripts;
- PR descriptions, review comments, issue threads;
- commit messages and release notes;
- plans under `docs/plans/`;
- incidents, postmortems, runbooks, ADRs.

The optional inputs should be explicitly labeled as history. Current repository
state remains the default source of truth for present-tense claims.

### Phase 1: Deterministic Census

This phase can be ordinary TypeScript/shell support, not an AI pipeline:

```pseudo
function census(repo):
  files = git_ls_files_or_walk(repo)
  tree = summarize_tree(files)
  manifests = read_existing([
    "package.json", "pnpm-workspace.yaml", "turbo.json",
    "pyproject.toml", "requirements*.txt", "go.mod", "Cargo.toml",
    "docker-compose*.yml", "Dockerfile*", ".github/workflows/*",
    "README*", "AGENTS.md", "CLAUDE.md", "docs/**"
  ])
  signals = {
    languages,
    test_frameworks,
    runtime_services,
    top_level_dirs,
    likely_entrypoints,
    docs_index,
    generated_docs_configs
  }
  return {files, tree, manifests, signals}
```

The census should not decide page contents. It only gives the agent a factual
starting map and prevents wasted tool calls.

### Phase 2: Parallel Read-Only Scouts

Use subagents when areas are independent and bounded. Each scout returns a
brief, not files. The writer decides what to do with the briefs.

Recommended scouts:

- **Architecture Scout:** entrypoints, process boundaries, packages, major
  subsystems, dependency direction.
- **Data Scout:** schemas, persistence, migrations, queues, caches, file
  storage, external APIs.
- **Flow Scout:** end-to-end flows from UI/CLI/API entrypoints through business
  logic to side effects.
- **Operations Scout:** config, environment variables, deployment, CI, local
  dev, release, observability.
- **History Scout:** optional conversations/PRs/issues/plans; extract decisions,
  rejected alternatives, incidents, gotchas, active migrations.
- **Convention Scout:** coding conventions, test patterns, build tooling,
  generated-code boundaries, "do not touch" areas.

Tool permissions:

```typescript
writer:   Read, Write, Edit, Grep, Glob, Bash, Agent
scouts:   Read, Grep, Glob, Bash
reviewer: Read, Grep, Glob, Bash
```

This matches the Claude SDK model where subagents can have separate context and
restricted tools. Scouts should not write. They should cite paths and line
ranges when possible, identify uncertainty, and stop at evidence.

Scout brief shape, as prompt guidance rather than a schema:

```markdown
# Brief: Data Scout

## Anchors
- `src/db/schema.ts`: defines users, workspaces, captures.

## Candidate Pages
- `capture-storage`: session transcript ingestion, local log files, index refs.

## Evidence
- `src/...`: fact.

## Unknowns
- No migration runner found; verify before writing a deployment page.
```

### Phase 3: Page Slate Selection

The writer should choose a small page slate before writing prose. This can be
internal reasoning or a visible progress log, but it should not be persisted as
a proposal file.

Selection rule:

```pseudo
candidate_score(page) =
  entity_stability
+ cross_file_span
+ future_agent_usefulness
+ non_obviousness
+ source_support
+ history_support
- restates_code_penalty
- shallow_stub_penalty
- stale_history_risk
```

Target first wiki size:

- small repo: 4-8 pages;
- medium repo: 8-14 pages;
- large repo: 12-20 pages plus a conservative README/topic DAG.

Page categories are suggestions, not schemas:

- stable entity pages: framework, service, subsystem, external dependency;
- decision pages: why a pattern or tool is used;
- flow pages: request/capture/bootstrap/release/data flow;
- invariant/gotcha pages: constraints and failure modes future agents must not
  violate;
- operations pages: local dev, deployment, CI, environment contracts when they
  contain non-obvious knowledge.

Avoid one page per top-level directory unless the directory is itself a stable
concept.

### Phase 4: Writing Pages

Each page should be written from evidence, not from the page title. A strong
page has:

- frontmatter with `title`, `topics`, and `files`;
- one clear opening fact: what the page is about and why future agents need it;
- only specific claims;
- inline `[[path]]` or frontmatter `files:` refs for code coverage;
- links to neighboring pages;
- explicit decisions, constraints, gotchas, or flows;
- historical claims labeled with source/date when they come from conversations;
- open questions only when uncertainty matters to future work.

Recommended page skeleton:

```markdown
---
title: Capture Pipeline
topics: [capture, agents, sessions]
files:
  - src/commands/capture.ts
  - prompts/writer.md
  - prompts/reviewer.md
---

# Capture Pipeline

The capture pipeline runs after an agent session and turns notable session
knowledge into `.almanac/pages/` updates.

## Current Flow

...

## Invariants

- Only `capture` and `bootstrap` invoke AI.
- The writer owns edits; reviewer is read-only.

## Gotchas

- Session transcripts may mention plans that were later abandoned; verify
  current code before writing present-tense claims.

## Related

- [[bootstrap-agent]]
- [[src/commands/capture.ts]]
```

### Phase 5: Review

After writing, the writer invokes a reviewer subagent. The reviewer reads the
new pages and adjacent graph context, then critiques:

- factual support;
- stale or speculative claims;
- duplicate pages;
- missing links;
- page cohesion;
- notability;
- writing convention violations;
- topic coverage and DAG sanity.

The reviewer returns text critique. The writer decides what to incorporate and
edits directly. There is no approve/reject state machine.

### Phase 6: Final Index Check

After writes, bootstrap can run deterministic checks:

```pseudo
run("almanac reindex")
run("almanac health")  // when available
```

If health does not exist yet, the bootstrap prompt should still ask the writer
to self-check:

- all `[[page]]` links resolve or are intentionally future-facing;
- file refs point to real normalized paths;
- no empty/stub pages;
- topics exist in `.almanac/topics.yaml` or README guidance, depending on the
  implemented slice;
- no page duplicates another page's center of gravity.

## Incorporating Past Conversations

Past conversations are high-value but dangerous. They contain rationale,
mistakes, and abandoned plans, but they also contain speculation, transient
debugging, and wrong turns.

Recommended history ingestion strategy:

```pseudo
function mine_history(history_sources, repo):
  records = []
  for source in history_sources:
    chunks = split_by_session_or_thread(source)
    for chunk in chunks:
      facts = model_extract(chunk, focus=[
        "decisions",
        "rejected alternatives",
        "constraints",
        "gotchas",
        "incidents",
        "active migrations",
        "files changed or discussed"
      ])
      records.extend(facts)

  for record in records:
    evidence = search_current_repo(record.files_or_terms)
    record.status = classify([
      "current_supported",
      "historical_only",
      "contradicted_by_current_code",
      "unclear"
    ], record, evidence)

  return records
```

Writing rules:

- If history says why current code exists and current code supports the state,
  write it as current knowledge with provenance.
- If history records a rejected path, write it only if the rejection helps
  future agents avoid repeating work.
- If history conflicts with current code, do not silently reconcile it. Either
  omit it, label it as historical, or create a gotcha page only when the
  contradiction itself is useful.
- If history mentions a decision without code support, require stronger
  provenance: PR link, dated transcript, issue, or plan.
- Do not write "the team decided" unless the source really shows a decision.

Good targets from history:

- "We tried SQLite FTS with LIKE and it matched underscores incorrectly; use
  GLOB for path queries."
- "The writer invokes reviewer as a subagent; no JSON approve/revise state."
- "SessionEnd is used instead of Stop to avoid per-turn captures."

Bad targets:

- "Discussed adding semantic search" with no decision.
- "Maybe use embeddings later."
- A transcript summary of code that can be read directly from source.

## High-Quality Page Rubric

A high-quality initial page:

- answers a question a future coding agent will actually ask;
- contains facts that are not obvious from opening one file;
- spans multiple files, docs, sessions, or operational contexts;
- names the current contract and the reason or consequence behind it;
- cites files or provenance tightly enough to verify claims;
- links to related pages and source paths;
- is cohesive as an article, not an append-only notes dump;
- is short enough to read in one agent context but complete enough to prevent
  repeated rediscovery;
- says "unknown" or stays silent where evidence is weak.

A shallow page:

- restates directory names;
- paraphrases README content without adding repo-specific memory;
- lists functions/classes like API docs;
- has generic sentences such as "this module plays an important role";
- has no `files:` coverage or wikilinks;
- contains architecture claims without code or history evidence;
- exists only because a top-level directory exists;
- ends with filler "future enhancements" not present in evidence.

Practical rule:

```text
If deleting the page would not make a future agent more likely to repeat a
mistake, violate an invariant, miss a flow, or misunderstand a decision, the
page is probably not notable.
```

## What Applies To codealmanac

Best-fit ideas:

- **Shape-Then-Fill** for initial page slate, but the page slate lives in the
  writer's working context, not a persisted proposal.
- **Hierarchical Atlas** for medium/large repos: subagents read modules and
  return briefs.
- **Graph-First Bootstrap** for anchor discovery: entrypoints, manifests,
  imports, central files, and cross-file flows.
- **History-Augmented Bootstrap** for the core value: decisions, gotchas,
  incidents, constraints, active migrations.
- **DocAgent-style verification** by reviewer, focused on truthfulness and
  usefulness rather than exhaustive completeness.
- **Cody-style multiple context lenses**: file tree, search, graph, local docs,
  history, current open/session context.
- **aider-style rank-and-fit**: show the model the important symbols/files
  under a budget instead of dumping everything.

Implementation posture:

- prompts do the judgment;
- deterministic code may gather file lists, manifests, and optional transcript
  paths;
- the writer writes `.almanac/README.md`, pages, and topic metadata directly;
- reviewer is read-only;
- no `--dry-run`, no `--apply`, no proposal JSON.

## What codealmanac Should Avoid

- One generated page per source file.
- Full API reference generation.
- A DeepWiki clone that explains code but misses rationale.
- Any bootstrap pipeline that persists intermediate XML/JSON proposals.
- Any apply/review state machine between writer and reviewer.
- Generic architecture diagrams on every page.
- Semantic search or vectors as a prerequisite for bootstrap.
- Whole-repo digesting as the only context strategy for non-trivial repos.
- Importing stale session claims without checking current code.
- Empty "stub pages" as the default. If a page is worth creating, it should
  contain at least one useful fact, invariant, flow, decision, or gotcha.
- Treating topics as rigid page types. Topics organize; they do not constrain
  what a page is allowed to say.

## Algorithm Sketch

End-to-end:

```pseudo
function bootstrap_codealmanac(repo, optional_history):
  assert command == "bootstrap"  // AI/write exception allowed by design

  census = deterministic_census(repo)
  history_index = locate_optional_history(optional_history)

  scouts = {
    architecture: read_only_agent(ARCHITECTURE_PROMPT),
    data:         read_only_agent(DATA_PROMPT),
    flow:         read_only_agent(FLOW_PROMPT),
    operations:   read_only_agent(OPERATIONS_PROMPT),
    history:      read_only_agent(HISTORY_PROMPT),
    conventions:  read_only_agent(CONVENTIONS_PROMPT)
  }

  briefs = parallel_run_relevant_scouts(scouts, census, history_index)

  writer_context = {
    product_thesis: "document what code cannot say",
    non_negotiables,
    census,
    briefs,
    existing_wiki_if_any
  }

  writer:
    read briefs
    inspect supporting files before writing claims
    choose page slate and topic DAG
    write .almanac/README.md
    write substantive pages under .almanac/pages/
    invoke reviewer with paths written
    read critique
    edit pages/topics/readme directly
    run reindex/health if available

  return final_changed_files
```

Candidate page selection:

```pseudo
function choose_pages(census, briefs):
  candidates = []

  candidates += stable_entities(census.manifests, briefs.architecture)
  candidates += cross_file_flows(briefs.flow)
  candidates += non_obvious_constraints(briefs.data, briefs.operations)
  candidates += history_decisions(briefs.history)
  candidates += recurring_gotchas(briefs.history, repo_docs)

  candidates = dedupe_by_center_of_gravity(candidates)
  candidates = remove_if_restates_code(candidates)
  candidates = require_evidence(candidates)

  return top_k(candidates, by=future_agent_value, k=repo_size_budget)
```

Page writing:

```pseudo
function write_page(candidate):
  evidence = read(candidate.files + candidate.history_refs)
  if not enough_evidence(evidence):
    skip_or_record_unknown(candidate)

  page = compose({
    title,
    topics,
    files,
    opening_fact,
    current_state,
    decisions_or_rationale,
    invariants,
    gotchas,
    related_links
  })

  if page_is_shallow(page):
    skip_or_merge(page)
  else:
    write_markdown(slug(candidate.title), page)
```

Reviewer:

```pseudo
function review_bootstrap(written_pages):
  for page in written_pages:
    check_claims_against_files(page)
    check_links(page)
    check_notability(page)
    check_duplicate_center(page, all_pages)
    check_tone_specificity(page)
  return critique
```

## Bootstrap Prompt Requirements

The bootstrap prompt should explicitly say:

- Your goal is a useful first wiki, not broad generated documentation.
- Prefer fewer substantive pages over many stubs.
- Every page must contain non-obvious knowledge useful to a future coding
  agent.
- Read source before writing claims.
- Use optional history for rationale, rejected alternatives, gotchas, and
  active migrations; verify against current code.
- Write directly to `.almanac/`.
- Keep `.almanac/` flat: pages under `.almanac/pages/`, no `.almanac/wiki/`.
- Use unified `[[...]]` syntax for page and file links.
- Do not create proposal files or dry-run outputs.
- Invoke reviewer after substantive writes.

Reviewer prompt additions:

- Reject pages that merely restate code.
- Flag unsupported claims and stale historical claims.
- Flag duplicate pages and missing links.
- Check whether pages have enough factual density to justify their existence.
- Prefer "delete/merge this shallow page" over padding it.

## Final Recommendation

For `codealmanac`, implement initial wiki generation as a single bootstrap
writer agent with read-only scout subagents and a read-only reviewer subagent.
The system should provide deterministic repo census context and optional history
locations, then let the writer decide the page slate and write directly.

The first wiki should contain:

- `.almanac/README.md` with notability bar, conventions, and topic guidance;
- a small topic DAG or topic list, depending on implemented slice;
- 6-14 pages for a typical repo, biased toward entities, decisions, flows,
  invariants, and gotchas;
- each page grounded in current files and, when useful, dated historical
  provenance;
- no shallow stubs unless a stub contains a concrete known fact and exists as an
  intentional anchor for multiple pages.

The algorithm should be:

```text
Atlas Bootstrap =
  deterministic census
+ multi-lens read-only scouting
+ writer-owned synthesis
+ source-grounded direct page writes
+ reviewer critique
+ deterministic reindex/health
```

This model borrows the useful mechanics of DeepWiki, CodeWiki, RepoAgent,
DocAgent, Cody, aider, and history-mining research while preserving
`codealmanac`'s core design: local-only, prompt-owned judgment, no proposal
ceremony, and a wiki that records what code cannot say.
