/moai sync
Synchronizes documentation for the implemented code and prepares for release through Git automation. This is the final step of the 3-Phase lifecycle.
InfoSlash command: In Claude Code, type/moai:syncto run this command directly. Typing just/moaishows the list of all available subcommands.
/moai sync is the Phase 3 (Sync) command of the MoAI-ADK workflow. It analyzes the code implemented in Phase 2, auto-generates documentation, and creates Git commits and a PR (Pull Request) to complete release preparation. Internally, the manager-docs agent manages the entire process.
The synchronization result is independently evaluated by sync-auditor — the agent that produced the docs and the agent that inspects them are separated, so the phase closes with verified evidence rather than a “we synced it” claim.
InfoWhy do you need doc synchronization?
Writing documentation separately after writing code is tedious, and code and docs easily drift out of sync.
/moai syncsolves this problem:
- Analyzes the code to auto-generate API documentation
- Auto-updates README and CHANGELOG
- Auto-creates Git commits and PRs
Because code changes and docs stay synchronized, the “the docs are stale” problem disappears.
Run after the Run phase completes:
# Run /clear after the Run phase completes (recommended)
> /clear
# Sync docs and create a PR
> /moai sync| Mode | Description | When to use |
|---|---|---|
auto (default) | Smart sync of changed files only | Daily development |
force | Regenerate all documentation | Error recovery, large refactoring |
status | Read-only status check | Quick health check |
project | Update project-wide documentation | Milestone completion, periodic sync |
The default auto mode syncing only changed files is also a tokenomics design decision — if there is no reason to regenerate every document each time, those tokens are simply not spent.
# Default mode (changed files only)
> /moai sync
# Full regeneration
> /moai sync --mode force
# Status check only
> /moai sync --mode status
# Project-wide update
> /moai sync --mode project| Flag | Description | Example |
|---|---|---|
--pr | Skip the changelog prompt and open a PR automatically (Tier L or when review is needed) | /moai sync --pr |
--skip-mx | Skip the MX tag check | /moai sync --skip-mx |
WarningThe
--mergeand--team/--soloflags have been Deprecated or removed.
--merge: In Hybrid Trunk 1-person OSS operation, Tier S/M push directly to main by default, so PR auto-merge is no longer needed. If a merge is needed after creating a PR at Tier L, rungh pr mergemanually.--team/--solo: The Agent Teams static-orchestration layer has been RETIRED.--teamtriggers aMODE_TEAM_UNAVAILABLEfallback, and since sub-agent mode is the only mode,--solois meaningless too.
Skips the changelog prompt and opens a PR automatically:
> /moai sync --prUse case: when you want to create a PR quickly without entering changelog information manually. The changelog can be added later during PR review.
Whether a PR is created is decided automatically by the SPEC tier (the Hybrid Trunk 1-person OSS default behavior):
| Tier | PR creation | Executor |
|---|---|---|
| Tier S (≤ 300 LOC, < 5 files) | direct push to main (no PR) | manager-develop or orchestrator |
| Tier M (300-1000 LOC, 5-15 files) | direct push to main (no PR) | manager-develop or orchestrator |
| Tier L (> 1000 LOC or constitutional) | PR from a feat/SPEC-XXX branch via manager-git | manager-git |
Explicit --pr (any tier) | PR from a feat/SPEC-XXX branch via manager-git | manager-git |
Tier S/M push directly to main because the CI 4 status checks + pre-push hook guarantee safety. Tier L requires a PR review window and full CI matrix verification due to its broad scope.
Token-efficiency strategies:
- Loads only the SPEC document’s metadata and summary
- Caches and reuses the list of files changed in the previous phase
- Uses document templates to shorten generation time
The full process /moai sync performs internally:
flowchart TD
A["Run command
/moai sync"] --> B["Phase 7
quality verification"]
B --> C["Detect project language"]
C --> D["Run parallel diagnostics"]
subgraph D["Parallel diagnostics"]
D1["Run tests"]
D2["Run linter"]
D3["Type check"]
end
D --> E{"Tests failing?"}
E -->|Yes| F["Ask the user
whether to continue"]
F -->|Abort| G["Exit"]
F -->|Continue| H["Continue to Phase 1"]
E -->|No| H["Phase 11
analysis and planning"]
H --> I["Check preconditions"]
I --> J["Analyze Git changes"]
J --> K["Validate project state"]
K --> L["Invoke manager-docs
build sync plan"]
L --> M{"User approval"}
M -->|No| N["Exit"]
M -->|Yes| O["Phase 12
run doc synchronization"]
O --> P["Create safety backup"]
P --> Q["Invoke manager-docs
generate docs"]
Q --> R["Generate API docs"]
R --> S["Update README"]
S --> T["Sync architecture docs"]
T --> U["Update SPEC status"]
U --> V["Invoke sync-auditor
quality verification"]
V --> W{"Quality criteria?"}
W -->|FAIL| G
W -->|PASS| X["Phase 13
Git operations"]
X --> Y["Invoke manager-git
stage changed files"]
Y --> Z["Create commit"]
Z --> AA{"--merge flag?"}
AA -->|Yes| AB["Check PR status"]
AB --> AC["Auto-merge"]
AB --> AD["Skip merge"]
AC --> AE["Done"]
AD --> AE
AA -->|No| AF{"Team mode?"}
AF -->|Yes| AG["Switch PR to Ready"]
AF -->|No| AE
AG --> AEVerifies project quality before doc synchronization.
Step 1 - Project language detection:
| Language | Marker files |
|---|---|
| Python | pyproject.toml, setup.py, requirements.txt |
| TypeScript | tsconfig.json, package.json (typescript) |
| JavaScript | package.json (no tsconfig) |
| Go | go.mod, go.sum |
| Rust | Cargo.toml, Cargo.lock |
| 11 more languages supported |
Step 2 - Parallel diagnostics:
Three tools run at the same time:
| Diagnostic tool | Purpose | Timeout |
|---|---|---|
| Test runner | Detect test failures | 180 s |
| Linter | Check code style | 120 s |
| Type check | Check for type errors | 120 s |
Step 3 - Handling test failures:
If tests fail, the user is presented with choices:
- Continue: proceed despite failures
- Abort: stop and exit
Step 4 - Code review:
The sync-auditor subagent performs TRUST 5 quality verification and produces a consolidated report.
Step 5 - Quality report generation:
Aggregates the status of test-runner, linter, type-checker, and code-review, and determines the overall status (PASS or WARN).
The manager-docs subagent builds the synchronization strategy.
Output: documents_to_update, specs_requiring_sync, project_improvements_needed, estimated_scope
Step 1 - Create safety backup:
A backup is created before modifications:
- Timestamp generated
- Backup directory:
.moai-backups/sync-{timestamp}/ - Important files copied: README.md, docs/, .moai/specs/
- Backup integrity verified
Step 2 - Doc synchronization:
The manager-docs subagent performs the following:
- Reflects changed code into the Living Documents
- Auto-generates and updates API documentation
- Updates README when needed
- Syncs architecture documents
- Repairs project issues and fixes broken references
- Verifies the SPEC document matches the implementation
- Detects changed domains and generates per-domain updates
- Generates a sync report:
.moai/reports/sync-report-{timestamp}.md
Step 3 - Post-sync quality verification:
The sync-auditor subagent verifies sync quality against the TRUST 5 criteria:
- All project links complete
- Documents well formatted
- All documents consistent
- No credentials exposed
- All SPECs properly linked
Step 4 - SPEC status update (3-Phase close):
manager-docs transitions the frontmatter status of the SPEC artifacts from in-progress → implemented. The final transition to completed is not a separate commit — it is recorded together with this sync commit. That is, a SPEC that entered in-progress in the run phase passes through implemented in the sync phase and is finalized as completed together with the sync commit. manager-docs handles only the frontmatter status transition and does not modify the body of spec.md/plan.md/acceptance.md.
The manager-git subagent performs the Git operations:
Step 1 - Create commit:
- Stage all changed docs, reports, README, and docs/ files
- Create a single commit listing the synced docs, project repairs, and SPEC updates
- Verify the commit with git log
Step 2 - Switch PR to Ready (Team mode only):
- Check the setting in git_strategy.mode
- If Team mode: switch the Draft PR to Ready (gh pr ready)
- Assign reviewers and labels if configured
- If Personal mode: skipped
Step 3 - Auto-merge (with the –merge flag):
- Check CI/CD status with gh pr checks
- Check merge conflicts with gh pr view –json mergeable
- If passing and mergeable: run gh pr merge –squash –delete-branch
- Check out develop, pull, delete the local branch
Standard completion report:
A summary of the following is displayed:
- mode, scope, number of files updated/created
- Project improvements
- Updated documents
- Generated reports
- Backup location
Worktree-mode next steps (auto-detected from git context):
| Option | Description |
|---|---|
| Return to main directory | Leave the worktree and go back to main |
| Continue in the worktree | Keep working in the current worktree |
| Switch to another worktree | Choose a different worktree |
| Remove this worktree | Clean up the worktree |
Branch-mode next steps (auto-detected from git context):
| Option | Description |
|---|---|
| Commit and push changes | Upload changes to the remote |
| Return to the main branch | To develop or main |
| Create PR | Create a Pull Request |
| Continue on the branch | Keep working on the current branch |
Standard next steps:
| Option | Description |
|---|---|
| Create the next SPEC | Run /moai plan |
| Start a new session | Run /clear |
| Review the PR | Team mode: gh pr view |
| Continue development | Personal mode: keep working |
The documents /moai sync automatically generates or updates:
Analyzes API endpoints, function signatures, and class structures in the implemented code to generate documentation.
| Document type | Contents | Generated when |
|---|---|---|
| API reference | Endpoints, request/response schemas | A REST API is included |
| Function docs | Parameters, return values, exceptions | Public functions are included |
| Class docs | Attributes, methods, inheritance | Classes are included |
Updates the project’s README.md as follows:
- Usage section: usage examples for newly added features
- API section: adds the list of new endpoints
- Dependencies section: reflects newly added libraries
Records the change history in the Keep a Changelog format:
## [Unreleased]
### Added
- JWT-based user authentication system (SPEC-AUTH-001)
- POST /api/auth/register - signup
- POST /api/auth/login - login
- POST /api/auth/refresh - token refresh/moai sync performs Git operations automatically after generating docs.
MoAI-ADK follows the Conventional Commits format:
| Prefix | Purpose | Example |
|---|---|---|
feat | New feature | feat(auth): add JWT authentication |
fix | Bug fix | fix(auth): resolve token expiration issue |
docs | Documentation | docs(auth): update API documentation |
refactor | Refactoring | refactor(auth): centralize auth logic |
test | Tests | test(auth): add characterization tests |
After /moai sync creates the PR, the orchestrator observes which required checks failed and hands them off to the auto-fix loop. Instead of a human watching the CI screen after PR creation, the loop receives the result and responds — agentic loop engineering extended into the CI domain.
When the orchestrator hands off a failing required check, MoAI-ADK enters the auto-fix loop.
- Each iteration applies the fix as a new commit (no force-push / amend)
- At most 3 iterations per PR push (not per session)
- At iteration ≥ 4, escalation to the user via a blocking AskUserQuestion
| Failure type | Auto-handled? | Notes |
|---|---|---|
| lint error | Automatic | Items golangci-lint can autofix |
| format drift | Automatic | gofmt / prettier, etc. |
| test syntax error | Automatic | Missing imports / compile errors |
| data race | Human decision | Semantic failure — judging whether the concurrency is intentional |
| deadlock | Human decision | Semantic failure |
| panic | Human decision | Semantic failure |
| test assertion failure | Human decision | A human decides whether the spec or the code is right |
WarningThe auto-fix loop never modifies the following files:
.env,.env.*(environment variables / secrets)- credentials files
- CI workflow definitions and required-check configuration — patching the layer that reports a failure can turn a real failure into a false green
- Auto-fix doctrine SSoT:
.claude/rules/moai/workflow/ci-autofix-protocol.md
The Sync phase’s quality criteria are more documentation-centric than the Run phase’s:
| Item | Criterion | Description |
|---|---|---|
| LSP errors | 0 | The code must be error-free |
| Warnings | up to 10 | Some warnings allowed during doc generation |
| LSP state | Clean | Overall clean state |
WarningIf the quality gate fails, doc generation and PR creation are halted. First go back to/moai runto fix code issues, or use/moai fixto fix errors quickly.
The sync process has two HUMAN GATEs. These gates are not auto-passed, and the chain is halted on a FAIL or INCONCLUSIVE verdict.
| Gate | Name | Timing | Role |
|---|---|---|---|
gate-sync-1 | Pre-Sync Quality | Before entering Phase 3 | Confirm the working tree is clean and all tests pass |
gate-sync-2 | Documentation Scope | Approve the doc generation scope | The user reviews the divergence report and approves the doc regeneration scope |
gate-sync-1 verifies that code quality meets the sync entry conditions — if there are test failures or a dirty working tree, it does not proceed to doc generation. gate-sync-2 is an approval step where the user confirms which documents to regenerate — it prevents automatic generation from making unintended document changes.
WarningIf the sync-auditor verdict is FAIL/INCONCLUSIVE or a gate blocks, the chain is halted. It does not auto-complete without passing the gates.
When run in a worktree environment, auto-merge is the default behavior.
Worktree-context detection:
- Whether the current git directory path contains
/.moai/worktrees/ - Or an active entry for the current SPEC-ID exists in
.moai/worktrees/registry.json
Flag behavior:
In a worktree context, auto-merge is the default behavior with no extra flag. The --merge flag is Deprecated (warning shown); to merge a Tier L PR, run gh pr merge manually after CI passes. The only flags /moai sync supports are --pr / --merge (deprecated) / --skip-mx.
Auto-merge execution conditions:
- All CI/CD checks pass
- No merge conflicts
WarningOn CI failure or conflict, auto-merge is not performed, and the error is reported along with recovery commands.
Automatic cleanup runs after a successful PR merge.
Condition: auto-merge succeeded AND workflow.worktree.auto_cleanup == true
Cleanup items:
- Remove the worktree directory
- Delete the feature branch (
--delete-branch) - Update the worktree registry
InfoCleanup failure does not affect the merge result. On failure: clean up manually withmoai worktree done SPEC-{ID}.
When resuming a multi-step workflow across directory boundaries (e.g. entering an L2 worktree between run and sync), Claude Code 2.1.169+ provides /cd <path> — a command that switches the session’s working directory while preserving the prompt cache, so the accumulated reasoning context is retained instead of being rebuilt on cwd change. This is the cache-preserving alternative to opening a new terminal: /cd keeps the context, a new terminal cold-starts. When entering the sync phase in an L2 worktree while retaining run-phase context, /cd <worktree-path> is the lower-friction path. Since cache hit rate directly translates into token cost, the habit of preserving the prompt cache is also sound tokenomics. See the Statusline guide for how the switch is reflected in the cwd field.
Step 1: Confirm the Run phase is complete
# Check that the Run phase is finished
# manager-develop should have printed a "DONE" or "COMPLETE" markerStep 2: Clean up tokens, then run Sync
> /clear
> /moai syncStep 3: What manager-docs does automatically
The 4 phases the manager-docs agent runs for doc synchronization.
Verifies project state before doc generation.
Phase 7: Quality verification
Project language: Python
Tests: 36/36 pass
Linter: 0 errors
Type check: 0 errors
Coverage: 89%
Overall status: PASSAnalyzes Git changes and builds the sync plan.
Phase 11: Analysis and planning
Git changes: 12 files modified
Sync plan: 1 API doc, README update, CHANGELOG addition
User approval: completeGenerates the needed docs and updates existing ones.
Phase 12: Doc synchronization
Backup created: .moai-backups/sync-20260128-143052/
API docs: docs/api/auth.md (new)
README.md: usage section updated
CHANGELOG.md: v1.1.0 entry added
SPEC-AUTH-001 status: ACTIVE → COMPLETED
Quality verification: all checks passCreates the commit and opens the PR.
Phase 13: Git operations
Commit created: docs(auth): synchronize documentation for SPEC-AUTH-001
PR status: Draft → Ready (Team mode)Step 4: Check the created PR
# View the PR from the terminal
$ gh pr view 42The created PR automatically includes the SPEC requirements, the list of changed files, and the test results.
Set auto_pr: false in git-strategy.yaml and only the commit will be automated. You can create the PR yourself whenever you want.
Currently the Keep a Changelog format is used by default. Custom formats are planned for the future.
Set auto_commit: false in git-strategy.yaml and only doc generation will run. Git operations can be done manually.
There are two options:
# Option 1: quick fix with /moai fix
> /moai fix "fix lint errors"
# Option 2: re-implement with /moai run
> /moai run SPEC-AUTH-001After fixing, run /moai sync again.
/moai sync handles documentation of already-implemented code only. /moai automatically runs the entire workflow from SPEC creation through implementation to documentation.
- /moai run - Previous step: DDD implementation
- TRUST 5 Quality System - Detailed quality gate explanation
- Quick Start - Full workflow tutorial