Todo Skill
Direct execution skill for archiving tasks, updating CHANGE_LOG.md, and suggesting memory harvesting.
Direct execution skill for task archival operations with automated CHANGE_LOG updates and memory harvest suggestions.
Parse arguments, scan for archivable tasks (completed, abandoned, expanded), update states, generate CHANGE_LOG entries, suggest memory harvesting from completed task artifacts.
1. Generate a session ID via `common_session_id` (skill-todo does not source
`command-gate-in.sh` and has no session ID of its own):
```bash
source .claude/scripts/lib/common.sh
todo_session_id="$(common_session_id)"
```
2. Select the same four reconcilable statuses used by the `/task --sync` and `/orchestrate`
triggers (positive-match against the four statuses `reconcile-task-status.sh` knows how
to reconcile -- no `!=`/negation selector needed). CONFIRMED (not assumed): `hold` is
absent from this positive-match list, so this stage can never silently promote a held
task out of its hold -- a hold is lifted only through the explicit
`preflight:unhold` path, never as a side effect of reconciliation:
```bash
reconcile_scan_targets=$(jq -r '
.active_projects[] |
select(.status == "researching" or .status == "planning" or .status == "implementing" or .status == "partial") |
.project_number
' specs/state.json)
```
3. For each candidate, dry-run the script and collect any task whose output reports a
would-promote line into `reconcile_candidates`, keeping each candidate's task number,
current status, the artifact basename found, and the full dry-run output for display in
Stage 8/9:
```bash
reconcile_candidates=()
for task_num in $reconcile_scan_targets; do
recon_out=$(bash .claude/scripts/reconcile-task-status.sh "$task_num" "$todo_session_id" --dry-run 2>&1)
if echo "$recon_out" | grep -q "Would promote"; then
reconcile_candidates+=("$task_num")
# associate $recon_out with $task_num (e.g. via an associative array) for Stage 9's
# AskUserQuestion description text
fi
done
```
4. If `reconcile_scan_targets` is empty, `reconcile_candidates` is `()` -- proceed straight
to Stage 2. This stage is genuinely side-effect-free: `--dry-run` never writes
`state.json` or any other file.
</process>
**VERIFIED, not guarded**: this stage's archive-candidate selection (steps 2-4 above) and
the archive-write jq at Stage 10 both POSITIVE-match only `completed`/`abandoned`/
`expanded`, so a `hold`-status task is excluded from the archive set by construction at
two independent points -- no redundant hold-specific guard is added here. (The task
dispatch that motivated this feature pointed at "Stage 2.5, lines ~164-166" for this
guard; that line range actually belongs to the Stage 2.5 `TopicRevision` selector below, a
different, inverted-select mechanism for topic backfill -- noted here so a future reader
following that line number is not misled.)
**Subtasks-defer guard**: identical semantics to `commands/todo.md`'s Step 3 guard (see that
file's "Prepare Archive List" section, which is the reference implementation this mirrors).
Partition the tasks identified above into `archivable_tasks[]` (proceeds) and
`deferred_expanded[]` (held back for a later `/todo` run) — an expanded parent is deferred
while any task in its `subtasks[]` is still present in `active_projects` with a non-terminal
status. Use a `case` statement for status classification (never `!=`):
```bash
archivable_tasks=()
deferred_expanded=()
deferred_expanded_nums=()
deferred_expanded_detail=() # one entry per deferred parent, naming WHICH subtask(s) block
# it and why (Decision 6 mitigation -- a reporting
# improvement only; the blocking case statement below is
# unchanged, and a held subtask continues to block exactly
# as every other non-terminal status does)
for task in "${candidate_tasks[@]}"; do
status=$(echo "$task" | jq -r '.status')
project_num=$(echo "$task" | jq -r '.project_number')
case "$status" in
expanded)
# A missing, null, or empty subtasks array means nothing is blocking - archive normally.
subtasks=$(echo "$task" | jq -c '.subtasks // []')
subtask_count=$(echo "$subtasks" | jq 'length')
if [ "$subtask_count" -eq 0 ]; then
archivable_tasks+=("$task")
continue
fi
blocking_count=0
for subtask_num in $(echo "$subtasks" | jq -r '.[]'); do
subtask_status=$(jq -r --argjson n "$subtask_num" \
'.active_projects[] | select(.project_number == $n) | .status' \
specs/state.json)
# An empty result means the subtask is already archived - not blocking.
if [ -z "$subtask_status" ]; then
continue
fi
case "$subtask_status" in
completed|abandoned|expanded)
# Terminal - not blocking.
;;
*)
# Any other status blocks.
((blocking_count++))
;;
esac
done
if [ "$blocking_count" -gt 0 ]; then
deferred_expanded+=("$task")
deferred_expanded_nums+=("$project_num")
# Reporting-only detail pass (Decision 6 mitigation): names which subtask(s) are
# blocking and, for a held one specifically, its hold_reason -- so the operator
# reads "subtask 123 is held (reason: ...)" rather than a generic "still active"
# line. This is a SEPARATE pass over the same subtasks[] already resolved above; it
# does not re-decide blocking and does not alter the case statement above.
detail_parts=()
for subtask_num in $(echo "$subtasks" | jq -r '.[]'); do
d_status=$(jq -r --argjson n "$subtask_num" \
'.active_projects[] | select(.project_number == $n) | .status' \
specs/state.json)
[ -z "$d_status" ] && continue
case "$d_status" in
completed|abandoned|expanded) ;;
hold)
d_reason=$(jq -r --argjson n "$subtask_num" \
'.active_projects[] | select(.project_number == $n) | .hold_reason // "no reason recorded"' \
specs/state.json)
detail_parts+=("subtask $subtask_num is held (reason: $d_reason)")
;;
*)
detail_parts+=("subtask $subtask_num is $d_status")
;;
esac
done
deferred_expanded_detail+=("$project_num: $(IFS='; '; echo "${detail_parts[*]}")")
else
archivable_tasks+=("$task")
fi
;;
*)
# Non-expanded tasks pass through untouched.
archivable_tasks+=("$task")
;;
esac
done
```
Track `deferred_expanded[]` and `deferred_count` (`= ${#deferred_expanded[@]}`). Stage 10
(`ArchiveTasks`) consumes `archivable_tasks[]` — never a freshly-recomputed status match —
so a deferred parent's `active_projects` entry survives this run.
</process>
If no tasks need backfill, skip this stage.
For each task needing a topic, follow the topic assignment pattern from
@.claude/context/patterns/topic-assignment-pattern.md (Mode A, per-task backfill).
Use header "Topic Backfill ({i} of {total})".
After each selection:
```bash
bash .claude/scripts/manage-topics.sh set "$task_num" "$topic"
```
</process>
in_active=$(jq -r --arg n "$project_num" \
'.active_projects[] | select(.project_number == ($n | tonumber)) | .project_number' \
specs/state.json 2>/dev/null)
in_archive=$(jq -r --arg n "$project_num" \
'.completed_projects[] | select(.project_number == ($num | tonumber)) | .project_number' \
specs/archive/state.json 2>/dev/null)
if [ -z "$in_active" ] && [ -z "$in_archive" ]; then
orphaned_in_specs+=("$dir")
fi
done
```
2. Scan specs/archive/ for orphaned directories:
```bash
for dir in specs/archive/OC_[0-9]*_*/ specs/archive/[0-9]*_*/; do
[ -d "$dir" ] || continue
basename_dir=$(basename "$dir")
project_num=$(echo "$basename_dir" | sed 's/^OC_//' | cut -d_ -f1)
in_archive=$(jq -r --arg n "$project_num" \
'.completed_projects[] | select(.project_number == ($num | tonumber)) | .project_number' \
specs/archive/state.json 2>/dev/null)
if [ -z "$in_archive" ]; then
orphaned_in_archive+=("$dir")
fi
done
```
3. Scan TODO.md for completed/abandoned tasks not tracked in state.json or archive:
- Parse task headers (`### {N}.` or `### OC_{N}.`) and status lines (`[COMPLETED]`/`[ABANDONED]`)
- Cross-reference each against active_projects and archive completed_projects
- Collect as `todo_md_orphans[]` if: status is completed/abandoned, not in either state file, and has a directory in specs/
</process>
in_active=$(jq -r --arg n "$project_num" \
'.active_projects[] | select(.project_number == ($num | tonumber)) | .project_number' \
specs/state.json 2>/dev/null)
in_archive=$(jq -r --arg n "$project_num" \
'.completed_projects[] | select(.project_number == ($num | tonumber)) | .project_number' \
specs/archive/state.json 2>/dev/null)
if [ -z "$in_active" ] && [ -n "$in_archive" ]; then
misplaced_in_specs+=("$dir")
fi
done
```
</process>
For each task in `archivable_tasks[]` (the guard-filtered list from Stage 2 — never a
freshly-recomputed status match, so deferred expanded parents are excluded):
1. Update specs/archive/state.json:
- `completed` and `expanded` tasks add to completed_projects array (there is no third
array for `expanded`); `abandoned` tasks add to archived_projects array
- Include all task fields
- Add archived timestamp
- Bootstrap if this is the first archive operation (via `--init`), then apply the batch
transform through `state-write.sh`'s `--state-file` flag, matching
`commands/todo.md`'s Step 5A shape:
```bash
[ -f specs/archive/state.json ] || bash .claude/scripts/state-write.sh \
'{ "archived_projects": [], "completed_projects": [] }' \
--init --state-file specs/archive/state.json --session-id "$todo_session_id"
archivable_tasks_json=$(printf '%s\n' "${archivable_tasks[@]}" | jq -s '.')
bash .claude/scripts/state-write.sh \
'.completed_projects = ([$tasks[] | select(.status == "completed" or .status == "expanded") | .archived_at = $ts] + .completed_projects) |
.archived_projects = ([$tasks[] | select(.status == "abandoned") | .archived_at = $ts] + .archived_projects)' \
--state-file specs/archive/state.json \
--session-id "$todo_session_id" \
--arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
--argjson tasks "$archivable_tasks_json"
```
2. Update specs/state.json:
- Remove from active_projects array. As in `commands/todo.md`'s Step 5B, this removal
must exclude any task listed in `deferred_expanded_nums[]` (Stage 2's guard) even
though its status matches — the blanket status match alone would delete a deferred
parent from state.json while its archive-list entry was held back, silently losing the
task. Since Stage 10 iterates `archivable_tasks[]` directly rather than re-deriving a
status match against the full `active_projects` array, deferred parents are naturally
excluded from this removal as long as the removal is driven by the same
`archivable_tasks[]` list — do not re-select by status here.
3. Update specs/TODO.md:
- Remove archived entries (both regular and TODO.md orphans) — the same
`archivable_tasks[]` guard-filtered list from Stage 2; a deferred parent's entry stays
- Pattern to match task entry start:
```lua
-- Match both "### OC_N. " and "### N. " formats
local task_start_pattern = "###%s+(OC_)?(%d+)%.%s+"
```
- For each task to remove:
a. Find entry start (header line)
b. Find entry end (next task header or end of Active Tasks section)
c. Extract complete entry including all lines
d. Validate entry matches expected format before removal
- Use Edit tool to remove validated entries:
```lua
-- Remove the matched section
edit_file("specs/TODO.md", old_entry_content, "")
```
- Note: next_project_number should NOT be decremented when removing orphans
(numbering continues from highest used number)
4. Move project directories to specs/archive/ — again driven by `archivable_tasks[]`; a
deferred parent's directory stays in place until a later `/todo` run archives it. For
each directory moved, append both its old and new path to `moved_paths[]`
(`moved_paths+=("$old_dir" "$new_dir")`), mirroring `commands/todo.md`'s Step 5D
pairing.
5. Track orphaned directories (if approved). For each directory moved from specs/ to
specs/archive/, append both its old and new path to `moved_paths[]`
(`moved_paths+=("$old_dir" "$new_dir")`), mirroring `commands/todo.md`'s Step 5E.1
pairing.
7. Move misplaced directories (if approved). For each directory moved, append both its
old and new path to `moved_paths[]` (`moved_paths+=("$old_dir" "$new_dir")`), mirroring
`commands/todo.md`'s Step 5F pairing.
8. Archive TODO.md orphans:
For each selected orphan in `selected_todo_orphans`:
a. Build archive entry from TODO.md data:
```json
{
"project_number": orphan.project_number,
"project_name": orphan.project_name,
"status": orphan.status, // "completed" or "abandoned"
"created_at": "TODO.md_orphan", // Marker indicating source
"archived_at": "YYYY-MM-DDTHH:MM:SSZ"
}
```
b. Add entry to specs/archive/state.json completed_projects array, matching
`commands/todo.md`'s Step 5E.2 shape (`$orphan` is the same JSON blob shown in
step a):
```bash
bash .claude/scripts/state-write.sh \
'.completed_projects += [{
project_number: $orphan.project_number,
project_name: $orphan.project_name,
status: $orphan.status,
created_at: "TODO.md_orphan",
archived_at: $ts
}]' \
--state-file specs/archive/state.json \
--session-id "$todo_session_id" \
--argjson orphan "$orphan" \
--arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
```
c. Move directory from specs/ to specs/archive/:
```bash
source_dir="specs/OC_${orphan.project_number}_${orphan.project_name}/"
if [ ! -d "$source_dir" ]; then
source_dir="specs/${orphan.project_number}_${orphan.project_name}/"
fi
target_dir="specs/archive/$(basename "$source_dir")"
# specs/archive/ is gitignored: this mv removes every file under the directory from
# version control (still on disk locally, absent from every fresh clone), so any
# guard or probe citing a file by its task-directory path -- a WIRED_REPO reference --
# breaks once the task is archived. No mechanical detector in this repository catches
# this today; the file must be re-pointed, or promoted into specs/evidence/, before
# archival, and that discipline is manual.
mv "$source_dir" "$target_dir"
# Pair both endpoints so `git add` records the source's removal -- see
# context/standards/git-staging-scope.md's "Rename and Directory-Move Staging".
moved_paths+=("$source_dir" "$target_dir")
```
d. Track orphan archival for CHANGE_LOG.md
e. If no directory found, log warning:
```
Warning: TODO.md orphan {N} has no directory in specs/
Archive entry created but no files moved
```
9. **Vault Threshold Check (MANDATORY)**
**CRITICAL: ALWAYS EXECUTE - DO NOT SKIP**
This sub-step MUST be executed unconditionally after archiving tasks.
The bash block below produces output for BOTH vault-needed and vault-not-needed cases.
Execute vault threshold detection:
```bash
# UNCONDITIONAL VAULT CHECK - produces output in all cases
PROJECT_ROOT="${PROJECT_ROOT:-.}"
STATE_FILE="${PROJECT_ROOT}/specs/state.json"
VAULT_THRESHOLD=1000
next_num=$(jq -r '.next_project_number // 0' "$STATE_FILE")
if [[ "$next_num" -gt "$VAULT_THRESHOLD" ]]; then
echo ""
echo "=============================================="
echo " VAULT THRESHOLD EXCEEDED"
echo "=============================================="
echo " next_project_number: $next_num"
echo " threshold: $VAULT_THRESHOLD"
echo " status: VAULT OPERATION REQUIRED"
echo "=============================================="
echo ""
vault_needed=true
else
echo ""
echo "Vault check: next_project_number=$next_num (threshold: $VAULT_THRESHOLD) - OK"
echo ""
vault_needed=false
fi
```
**Decision Logic**:
- If `vault_needed=true`: Proceed to sub-step 9.1 (VaultConfirmation)
- If `vault_needed=false`: Skip sub-steps 9.1-9.4, continue to Stage 12 (UpdateREADME)
9.1. **VaultConfirmation** (if vault_needed=true)
Identify tasks requiring renumbering:
```bash
# Find active tasks with project_number > 1000
tasks_to_renumber=$(jq -r '
.active_projects[] |
select(.project_number > 1000) |
{
old_number: .project_number,
new_number: (.project_number - 1000),
project_name: .project_name,
status: .status
}
' specs/state.json)
# Count tasks to renumber
renumber_count=$(echo "$tasks_to_renumber" | jq -s 'length')
# Build mapping array: [{old: 1001, new: 1}, {old: 1003, new: 3}, ...]
renumber_mappings=$(jq -n --argjson tasks "$tasks_to_renumber" '
[$tasks[] | {old: .old_number, new: .new_number, name: .project_name}]
')
```
Build preview of renumbering:
```bash
# Format preview of task renumbering
renumber_preview=""
for mapping in $(echo "$renumber_mappings" | jq -c '.[]'); do
old=$(echo "$mapping" | jq -r '.old')
new=$(echo "$mapping" | jq -r '.new')
name=$(echo "$mapping" | jq -r '.name')
renumber_preview="${renumber_preview}\n - Task ${old} (${name}) -> Task ${new}"
done
```
Present AskUserQuestion for vault confirmation:
```json
{
"question": "Task numbering has exceeded 1000. Initiate vault archival?",
"header": "Vault Operation",
"description": "Current next_project_number: {next_num}\nActive tasks to renumber: {renumber_count}\n\nRenumbering preview:{renumber_preview}\n\nThis will:\n1. Move specs/archive/ to specs/vault/{NN-vault}/\n2. Renumber tasks > 1000 by subtracting 1000\n3. Reset next_project_number",
"multiSelect": false,
"options": [
{"label": "Yes, proceed with vault operation", "value": "proceed"},
{"label": "No, skip vault this time", "value": "skip"}
]
}
```
Handle user response:
```bash
if [ "$user_response" = "proceed" ]; then
vault_approved=true
# Continue to sub-step 9.2
else
vault_approved=false
# Skip to Stage 12 (UpdateREADME)
fi
```
9.2. **CreateVault** (if vault_approved=true)
Calculate vault number:
```bash
# Get current vault_count (or 0 if not set)
vault_count=$(jq -r '.vault_count // 0' specs/state.json)
new_vault_num=$((vault_count + 1))
vault_dir_name=$(printf "%02d-vault" "$new_vault_num")
vault_path="specs/vault/${vault_dir_name}"
```
Create vault directory structure:
```bash
mkdir -p "$vault_path"
```
Move archive contents to vault:
```bash
# Move archive directory to vault
if [ -d "specs/archive" ]; then
mv "specs/archive" "${vault_path}/archive"
fi
```
Move archive state.json to vault root (a file rename, not a state write -- correctly
outside state-write.sh's remit):
```bash
# Archive state.json becomes vault state.json
if [ -f "${vault_path}/archive/state.json" ]; then
mv "${vault_path}/archive/state.json" "${vault_path}/state.json"
fi
# Pair the rename's exact old and new paths together so `git add` records it rather
# than leaving the old tree's removal unstaged -- mirrors commands/todo.md's identical
# vault-site pairing. See context/standards/git-staging-scope.md's "Rename and
# Directory-Move Staging" section.
moved_paths+=(specs/archive "${vault_path}/")
```
Create vault meta.json:
```bash
# Calculate metadata
current_timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
archived_count=$(jq -r '.completed_projects | length' "${vault_path}/state.json" 2>/dev/null || echo "0")
task_range="1-$((next_num - renumber_count - 1))"
# Create meta.json
jq -n \
--arg vault_num "$new_vault_num" \
--arg created_at "$current_timestamp" \
--arg task_range "$task_range" \
--argjson archived_count "$archived_count" \
--argjson final_task_num "$next_num" \
'{
vault_number: ($vault_num | tonumber),
created_at: $created_at,
task_range: $task_range,
archived_count: $archived_count,
final_task_number: $final_task_num,
description: "Vault containing archived tasks from task numbering cycle"
}' > "${vault_path}/meta.json"
```
Reinitialize empty specs/archive/ with fresh state.json via `state-write.sh`'s `--init`
mode. The timestamp is bound with `--arg`, not shell-interpolated into the filter:
```bash
mkdir -p "specs/archive"
# Create fresh archive state.json
bash .claude/scripts/state-write.sh \
'{
"_comment": "Archive state for completed and abandoned tasks",
"completed_projects": [],
"archived_at": $ts
}' \
--init --state-file specs/archive/state.json --session-id "$todo_session_id" \
--arg ts "$current_timestamp"
```
9.3. **RenumberTasks** (if vault_approved=true)
For each task in renumber_mappings, update state.json:
```bash
# Update each task's project_number and artifact paths
for mapping in $(echo "$renumber_mappings" | jq -c '.[]'); do
old_num=$(echo "$mapping" | jq -r '.old')
new_num=$(echo "$mapping" | jq -r '.new')
task_name=$(echo "$mapping" | jq -r '.name')
# Update project_number
# Update artifact paths (4-digit dir -> 3-digit dir)
old_padded=$(printf "%04d" "$old_num")
new_padded=$(printf "%03d" "$new_num")
# Use state-write.sh to update the task entry
bash .claude/scripts/state-write.sh \
'
.active_projects |= map(
if .project_number == $old then
.project_number = $new |
.artifacts |= (if . then map(
.path |= gsub("specs/\($old_pad)_"; "specs/\($new_pad)_") |
.path |= gsub("specs/\($old)_"; "specs/\($new_pad)_")
) else . end)
else . end
)
' \
--session-id "$todo_session_id" \
--argjson old "$old_num" \
--argjson new "$new_num" \
--arg old_pad "$old_padded" \
--arg new_pad "$new_padded"
done
```
Update dependencies arrays (task numbers > 1000):
```bash
# Build mapping for all renumbered tasks
bash .claude/scripts/state-write.sh \
'
# Create lookup from mappings
($mappings | map({(.old | tostring): .new}) | add) as $lookup |
.active_projects |= map(
.dependencies |= (if . then map(
. as $dep |
if $lookup[$dep | tostring] then
$lookup[$dep | tostring]
else $dep end
) else . end)
)
' \
--session-id "$todo_session_id" \
--argjson mappings "$renumber_mappings"
```
Rename task directories:
```bash
for mapping in $(echo "$renumber_mappings" | jq -c '.[]'); do
old_num=$(echo "$mapping" | jq -r '.old')
new_num=$(echo "$mapping" | jq -r '.new')
task_name=$(echo "$mapping" | jq -r '.name')
old_padded=$(printf "%04d" "$old_num")
new_padded=$(printf "%03d" "$new_num")
# Find source directory (could be 3-digit or 4-digit padded)
source_dir=""
if [ -d "specs/${old_padded}_${task_name}" ]; then
source_dir="specs/${old_padded}_${task_name}"
elif [ -d "specs/${old_num}_${task_name}" ]; then
source_dir="specs/${old_num}_${task_name}"
fi
# Rename to 3-digit padded format
if [ -n "$source_dir" ]; then
target_dir="specs/${new_padded}_${task_name}"
mv "$source_dir" "$target_dir"
# Pair both endpoints so `git add` records the source's removal -- see
# context/standards/git-staging-scope.md's "Rename and Directory-Move Staging".
moved_paths+=("$source_dir" "$target_dir")
fi
done
```
Update TODO.md entries:
```bash
for mapping in $(echo "$renumber_mappings" | jq -c '.[]'); do
old_num=$(echo "$mapping" | jq -r '.old')
new_num=$(echo "$mapping" | jq -r '.new')
old_padded=$(printf "%04d" "$old_num")
new_padded=$(printf "%03d" "$new_num")
# Update task headers: ### 1001. Title -> ### 1. Title
sed -i "s/^### ${old_num}\./### ${new_num}./" specs/TODO.md
# Update artifact links with directory references
sed -i "s|${old_padded}_|${new_padded}_|g" specs/TODO.md
sed -i "s|${old_num}_|${new_padded}_|g" specs/TODO.md
# Update dependency references
sed -i "s|Task #${old_num}|Task #${new_num}|g" specs/TODO.md
done
```
9.4. **ResetState** (if vault_approved=true)
Calculate new next_project_number:
```bash
# Find maximum project_number in active_projects after renumbering
max_active=$(jq -r '[.active_projects[].project_number] | max // 0' specs/state.json)
new_next_num=$((max_active + 1))
```
Update state.json with new next_project_number:
```bash
bash .claude/scripts/state-write.sh \
'.next_project_number = $new_next' \
--session-id "$todo_session_id" \
--argjson new_next "$new_next_num"
```
Increment vault_count:
```bash
bash .claude/scripts/state-write.sh \
'.vault_count = (.vault_count // 0) + 1' \
--session-id "$todo_session_id"
```
Add entry to vault_history:
```bash
current_timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
archived_count=$(jq -r '.completed_projects | length' "${vault_path}/state.json" 2>/dev/null || echo "0")
task_range="1-$((next_num - renumber_count - 1))"
bash .claude/scripts/state-write.sh \
'
.vault_history = (.vault_history // []) + [{
vault_number: $vault_num,
vault_dir: $vault_dir,
created_at: $created,
task_range: $range,
archived_count: $archived,
final_task_number: $final
}]
' \
--session-id "$todo_session_id" \
--arg vault_dir "$vault_path/" \
--argjson vault_num "$new_vault_num" \
--arg created "$current_timestamp" \
--arg range "$task_range" \
--argjson archived "$archived_count" \
--argjson final "$next_num"
```
After sub-step 9.4 completes, continue to Stage 12 (UpdateREADME).
<!-- CHECKPOINT: Stage 10 complete when vault_check output is present AND
(vault_needed=false OR vault operations 9.1-9.4 completed) -->
</process>
<checkpoint>vault_check_complete output present; if vault_needed, sub-steps 9.1-9.4 executed</checkpoint>
1---2name: skill-todo-33description: Archive completed, abandoned, and expanded tasks with CHANGE_LOG.md updates and memory harvest suggestions4allowed-tools: Bash, Edit, Read, Write, Grep, AskUserQuestion5context: direct6metadata:7 source: https://skillmd.com/skills/benbrastmckie/skill-todo-38---910# Todo Skill1112Direct execution skill for archiving tasks, updating CHANGE_LOG.md, and suggesting memory harvesting.1314<context>15 <system_context>OpenCode task archival with changelog tracking and memory suggestions.</system_context>16 <task_context>Archive completed/abandoned/expanded tasks and track changes.</task_context>17</context>1819<role>Direct execution skill for task archival operations with automated CHANGE_LOG updates and memory harvest suggestions.</role>2021<task>Parse arguments, scan for archivable tasks (completed, abandoned, expanded), update states, generate CHANGE_LOG entries, suggest memory harvesting from completed task artifacts.</task>2223<!-- Stage ids 5 and 11 (ScanRoadmap, UpdateRoadmap) were retired along with the roadmap24 integration consumer (see scripts/deprecated/README.md); their ids are deliberately left as25 gaps rather than renumbered, since renumbering would touch every cross-stage reference in26 this file for no behavioral benefit. -->2728<execution>29 <stage id="1" name="ParseArguments">30 <action>Parse command arguments</action>31 <process>32 1. Check for --dry-run flag33 2. Set dry_run = true if present34 3. Validate no other arguments expected35 </process>36 </stage>37 38 <stage id="1.5" name="ReconcileScan">39 <action>Dry-run scan for status-stranded tasks whose artifact for the in-flight phase already40 exists on disk -- these are invisible to Stage 2's literal completed/abandoned match today and41 can never be archived until something promotes them</action>42 <process>43 This stage never auto-repairs status: `/todo` performs the system's most irreversible44 operations (moving directories, rewriting CHANGE_LOG.md), and a silent status promotion45 immediately before a silent archive move would compound two mutations with no visibility.46 Every call this stage makes is `--dry-run`; only a user-approved selection in Stage 9 ever47 calls the script live.4849 1. Generate a session ID via `common_session_id` (skill-todo does not source50 `command-gate-in.sh` and has no session ID of its own):51 ```bash52 source .claude/scripts/lib/common.sh53 todo_session_id="$(common_session_id)"54 ```55 2. Select the same four reconcilable statuses used by the `/task --sync` and `/orchestrate`56 triggers (positive-match against the four statuses `reconcile-task-status.sh` knows how57 to reconcile -- no `!=`/negation selector needed). CONFIRMED (not assumed): `hold` is58 absent from this positive-match list, so this stage can never silently promote a held59 task out of its hold -- a hold is lifted only through the explicit60 `preflight:unhold` path, never as a side effect of reconciliation:61 ```bash62 reconcile_scan_targets=$(jq -r '63 .active_projects[] |64 select(.status == "researching" or .status == "planning" or .status == "implementing" or .status == "partial") |65 .project_number66 ' specs/state.json)67 ```68 3. For each candidate, dry-run the script and collect any task whose output reports a69 would-promote line into `reconcile_candidates`, keeping each candidate's task number,70 current status, the artifact basename found, and the full dry-run output for display in71 Stage 8/9:72 ```bash73 reconcile_candidates=()74 for task_num in $reconcile_scan_targets; do75 recon_out=$(bash .claude/scripts/reconcile-task-status.sh "$task_num" "$todo_session_id" --dry-run 2>&1)76 if echo "$recon_out" | grep -q "Would promote"; then77 reconcile_candidates+=("$task_num")78 # associate $recon_out with $task_num (e.g. via an associative array) for Stage 9's79 # AskUserQuestion description text80 fi81 done82 ```83 4. If `reconcile_scan_targets` is empty, `reconcile_candidates` is `()` -- proceed straight84 to Stage 2. This stage is genuinely side-effect-free: `--dry-run` never writes85 `state.json` or any other file.86 </process>87 </stage>8889 <stage id="2" name="ScanTasks">90 <action>Scan for archivable tasks</action>91 <process>92 1. Read specs/state.json93 2. Identify tasks with status = "completed"94 3. Identify tasks with status = "abandoned"95 4. Identify tasks with status = "expanded"96 5. Read specs/TODO.md and cross-reference (including entries marked [EXPANDED])97 6. Track counts: completed_count, abandoned_count, expanded_count9899 **VERIFIED, not guarded**: this stage's archive-candidate selection (steps 2-4 above) and100 the archive-write jq at Stage 10 both POSITIVE-match only `completed`/`abandoned`/101 `expanded`, so a `hold`-status task is excluded from the archive set by construction at102 two independent points -- no redundant hold-specific guard is added here. (The task103 dispatch that motivated this feature pointed at "Stage 2.5, lines ~164-166" for this104 guard; that line range actually belongs to the Stage 2.5 `TopicRevision` selector below, a105 different, inverted-select mechanism for topic backfill -- noted here so a future reader106 following that line number is not misled.)107108 **Subtasks-defer guard**: identical semantics to `commands/todo.md`'s Step 3 guard (see that109 file's "Prepare Archive List" section, which is the reference implementation this mirrors).110 Partition the tasks identified above into `archivable_tasks[]` (proceeds) and111 `deferred_expanded[]` (held back for a later `/todo` run) — an expanded parent is deferred112 while any task in its `subtasks[]` is still present in `active_projects` with a non-terminal113 status. Use a `case` statement for status classification (never `!=`):114115 ```bash116 archivable_tasks=()117 deferred_expanded=()118 deferred_expanded_nums=()119 deferred_expanded_detail=() # one entry per deferred parent, naming WHICH subtask(s) block120 # it and why (Decision 6 mitigation -- a reporting121 # improvement only; the blocking case statement below is122 # unchanged, and a held subtask continues to block exactly123 # as every other non-terminal status does)124125 for task in "${candidate_tasks[@]}"; do126 status=$(echo "$task" | jq -r '.status')127 project_num=$(echo "$task" | jq -r '.project_number')128129 case "$status" in130 expanded)131 # A missing, null, or empty subtasks array means nothing is blocking - archive normally.132 subtasks=$(echo "$task" | jq -c '.subtasks // []')133 subtask_count=$(echo "$subtasks" | jq 'length')134 if [ "$subtask_count" -eq 0 ]; then135 archivable_tasks+=("$task")136 continue137 fi138139 blocking_count=0140 for subtask_num in $(echo "$subtasks" | jq -r '.[]'); do141 subtask_status=$(jq -r --argjson n "$subtask_num" \142 '.active_projects[] | select(.project_number == $n) | .status' \143 specs/state.json)144145 # An empty result means the subtask is already archived - not blocking.146 if [ -z "$subtask_status" ]; then147 continue148 fi149150 case "$subtask_status" in151 completed|abandoned|expanded)152 # Terminal - not blocking.153 ;;154 *)155 # Any other status blocks.156 ((blocking_count++))157 ;;158 esac159 done160161 if [ "$blocking_count" -gt 0 ]; then162 deferred_expanded+=("$task")163 deferred_expanded_nums+=("$project_num")164 # Reporting-only detail pass (Decision 6 mitigation): names which subtask(s) are165 # blocking and, for a held one specifically, its hold_reason -- so the operator166 # reads "subtask 123 is held (reason: ...)" rather than a generic "still active"167 # line. This is a SEPARATE pass over the same subtasks[] already resolved above; it168 # does not re-decide blocking and does not alter the case statement above.169 detail_parts=()170 for subtask_num in $(echo "$subtasks" | jq -r '.[]'); do171 d_status=$(jq -r --argjson n "$subtask_num" \172 '.active_projects[] | select(.project_number == $n) | .status' \173 specs/state.json)174 [ -z "$d_status" ] && continue175 case "$d_status" in176 completed|abandoned|expanded) ;;177 hold)178 d_reason=$(jq -r --argjson n "$subtask_num" \179 '.active_projects[] | select(.project_number == $n) | .hold_reason // "no reason recorded"' \180 specs/state.json)181 detail_parts+=("subtask $subtask_num is held (reason: $d_reason)")182 ;;183 *)184 detail_parts+=("subtask $subtask_num is $d_status")185 ;;186 esac187 done188 deferred_expanded_detail+=("$project_num: $(IFS='; '; echo "${detail_parts[*]}")")189 else190 archivable_tasks+=("$task")191 fi192 ;;193 *)194 # Non-expanded tasks pass through untouched.195 archivable_tasks+=("$task")196 ;;197 esac198 done199 ```200201 Track `deferred_expanded[]` and `deferred_count` (`= ${#deferred_expanded[@]}`). Stage 10202 (`ArchiveTasks`) consumes `archivable_tasks[]` — never a freshly-recomputed status match —203 so a deferred parent's `active_projects` entry survives this run.204 </process>205 </stage>206 207 <stage id="2.5" name="TopicRevision">208 <action>Optional: backfill topics on active tasks missing the topic field</action>209 <process>210 Detect active tasks without a topic:211 ```bash212 missing=$(jq -r '.active_projects[] |213 select(.status == "completed" | not) |214 select(.status == "abandoned" | not) |215 select(.status == "expanded" | not) |216 select(.topic == null or .topic == "") |217 "\(.project_number)|\(.project_name)"' specs/state.json)218 ```219220 If no tasks need backfill, skip this stage.221222 For each task needing a topic, follow the topic assignment pattern from223 @.claude/context/patterns/topic-assignment-pattern.md (Mode A, per-task backfill).224 Use header "Topic Backfill ({i} of {total})".225226 After each selection:227 ```bash228 bash .claude/scripts/manage-topics.sh set "$task_num" "$topic"229 ```230 </process>231 </stage>232233 <stage id="3" name="DetectOrphans">234 <action>Detect orphaned directories and TODO.md orphans</action>235 <process>236 1. Scan specs/ for directories not tracked in state files:237 ```bash238 for dir in specs/OC_[0-9]*_*/ specs/[0-9]*_*/; do239 [ -d "$dir" ] || continue240 basename_dir=$(basename "$dir")241 project_num=$(echo "$basename_dir" | sed 's/^OC_//' | cut -d_ -f1)242243 in_active=$(jq -r --arg n "$project_num" \244 '.active_projects[] | select(.project_number == ($n | tonumber)) | .project_number' \245 specs/state.json 2>/dev/null)246247 in_archive=$(jq -r --arg n "$project_num" \248 '.completed_projects[] | select(.project_number == ($num | tonumber)) | .project_number' \249 specs/archive/state.json 2>/dev/null)250251 if [ -z "$in_active" ] && [ -z "$in_archive" ]; then252 orphaned_in_specs+=("$dir")253 fi254 done255 ```256257 2. Scan specs/archive/ for orphaned directories:258 ```bash259 for dir in specs/archive/OC_[0-9]*_*/ specs/archive/[0-9]*_*/; do260 [ -d "$dir" ] || continue261 basename_dir=$(basename "$dir")262 project_num=$(echo "$basename_dir" | sed 's/^OC_//' | cut -d_ -f1)263264 in_archive=$(jq -r --arg n "$project_num" \265 '.completed_projects[] | select(.project_number == ($num | tonumber)) | .project_number' \266 specs/archive/state.json 2>/dev/null)267268 if [ -z "$in_archive" ]; then269 orphaned_in_archive+=("$dir")270 fi271 done272 ```273274 3. Scan TODO.md for completed/abandoned tasks not tracked in state.json or archive:275 - Parse task headers (`### {N}.` or `### OC_{N}.`) and status lines (`[COMPLETED]`/`[ABANDONED]`)276 - Cross-reference each against active_projects and archive completed_projects277 - Collect as `todo_md_orphans[]` if: status is completed/abandoned, not in either state file, and has a directory in specs/278 </process>279 </stage>280 281 <stage id="4" name="DetectMisplaced">282 <action>Detect misplaced directories</action>283 <process>284 1. Scan specs/ for directories tracked in archive state:285 ```bash286 for dir in specs/OC_[0-9]*_*/ specs/[0-9]*_*/; do287 [ -d "$dir" ] || continue288 basename_dir=$(basename "$dir")289 project_num=$(echo "$basename_dir" | sed 's/^OC_//' | cut -d_ -f1)290 291 in_active=$(jq -r --arg n "$project_num" \292 '.active_projects[] | select(.project_number == ($num | tonumber)) | .project_number' \293 specs/state.json 2>/dev/null)294 295 in_archive=$(jq -r --arg n "$project_num" \296 '.completed_projects[] | select(.project_number == ($num | tonumber)) | .project_number' \297 specs/archive/state.json 2>/dev/null)298 299 if [ -z "$in_active" ] && [ -n "$in_archive" ]; then300 misplaced_in_specs+=("$dir")301 fi302 done303 ```304 </process>305 </stage>306307 <stage id="6" name="ScanMetaSuggestions">308 <action>Scan meta tasks for README.md suggestions</action>309 <process>310 1. For each archived meta task:311 - Check completion_data.readme_suggestions312 - Filter out "none" values313 - Track actionable suggestions by type:314 * Add: Insert new content315 * Update: Replace existing content316 * Remove: Delete content317 </process>318 </stage>319 320 <stage id="8" name="DryRunOutput">321 <action>Display dry run preview if requested</action>322 <process>323 If dry_run = true:324 1. Display comprehensive preview:325 - Tasks to archive (completed/abandoned/expanded counts)326 - Deferred: one summary line from `deferred_expanded[]` (Stage 2's subtasks-defer guard)327 - Format: `Deferred: {N} expanded parent(s) held back (subtasks still active)`328 - If `deferred_expanded[]` is empty: `Deferred: none` (mirrors the neighbouring329 memory-candidate and status-reconciliation dry-run lines)330 - Follow with one indented line per `deferred_expanded_detail[]` entry (Decision 6331 mitigation), so a hold specifically is named rather than folded into the generic332 "subtasks still active" summary, e.g. ` - 42: subtask 123 is held (reason: Awaiting333 upstream API decision)`334 - Orphaned directories count335 - Misplaced directories count336 - README.md suggestions count337 - Status reconciliation: one summary line from `reconcile_candidates` (Stage 1.5)338 - Format: `Status reconciliation: {N} task(s) stranded with artifacts on disk`339 - If `reconcile_candidates` is empty: `Status reconciliation: none`340 2. Exit after display341 </process>342 </stage>343 344 <stage id="9" name="InteractivePrompts">345 <action>Handle interactive prompts</action>346 <process>347 Present AskUserQuestion prompts for each detected condition:348 1. **Orphaned directories**: track/skip options per directory349 2. **Misplaced directories**: move/skip options per directory350 3. **TODO.md orphans**: multiSelect list of completed/abandoned tasks not in state.json; store as `selected_todo_orphans`351 4. **Status reconciliation candidates** (from `reconcile_candidates`, Stage 1.5):352 - If `reconcile_candidates` is empty, skip this sub-step entirely353 - Build a multiSelect option list, one option per candidate, showing the task number, its354 current status, the artifact found, and the promotion that would result:355 `Task {N}: status={current_status}, artifact={artifact_basename} -- would promote to356 {target_status}`357 - Present AskUserQuestion with multiSelect (nothing pre-selected -- this stage never358 auto-repairs; every promotion here is an explicit opt-in)359 - Store user-approved candidates as `approved_reconciliations`360 - Only for `approved_reconciliations`: re-run `bash .claude/scripts/reconcile-task-status.sh361 "$task_num" "$todo_session_id"` **without** `--dry-run` to apply the promotion, echoing362 its `[reconcile]` output verbatim. Unselected candidates are left stranded and simply are363 not archived this run -- the correct conservative outcome, since a status promotion364 immediately before a directory move must never be inferred rather than chosen.365 </process>366 </stage>367 368 <stage id="10" name="ArchiveTasks" checkpoint="vault_check_complete">369 <action>Archive tasks to completed_projects (includes mandatory vault check)</action>370 <process>371 Declare a `moved_paths[]` accumulator before any move below runs — the same convention as372 `commands/todo.md`'s `stage_paths[]`: every directory `mv` this stage performs appends373 BOTH its old and new path (old first), together, so Stage 15's `git add` can stage each374 vacated source's removal rather than leaving it unstaged. See375 `context/standards/git-staging-scope.md`'s "Rename and Directory-Move Staging" section.376 ```bash377 moved_paths=()378 ```379380 For each task in `archivable_tasks[]` (the guard-filtered list from Stage 2 — never a381 freshly-recomputed status match, so deferred expanded parents are excluded):382 1. Update specs/archive/state.json:383 - `completed` and `expanded` tasks add to completed_projects array (there is no third384 array for `expanded`); `abandoned` tasks add to archived_projects array385 - Include all task fields386 - Add archived timestamp387 - Bootstrap if this is the first archive operation (via `--init`), then apply the batch388 transform through `state-write.sh`'s `--state-file` flag, matching389 `commands/todo.md`'s Step 5A shape:390 ```bash391 [ -f specs/archive/state.json ] || bash .claude/scripts/state-write.sh \392 '{ "archived_projects": [], "completed_projects": [] }' \393 --init --state-file specs/archive/state.json --session-id "$todo_session_id"394395 archivable_tasks_json=$(printf '%s\n' "${archivable_tasks[@]}" | jq -s '.')396 bash .claude/scripts/state-write.sh \397 '.completed_projects = ([$tasks[] | select(.status == "completed" or .status == "expanded") | .archived_at = $ts] + .completed_projects) |398 .archived_projects = ([$tasks[] | select(.status == "abandoned") | .archived_at = $ts] + .archived_projects)' \399 --state-file specs/archive/state.json \400 --session-id "$todo_session_id" \401 --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \402 --argjson tasks "$archivable_tasks_json"403 ```404405 2. Update specs/state.json:406 - Remove from active_projects array. As in `commands/todo.md`'s Step 5B, this removal407 must exclude any task listed in `deferred_expanded_nums[]` (Stage 2's guard) even408 though its status matches — the blanket status match alone would delete a deferred409 parent from state.json while its archive-list entry was held back, silently losing the410 task. Since Stage 10 iterates `archivable_tasks[]` directly rather than re-deriving a411 status match against the full `active_projects` array, deferred parents are naturally412 excluded from this removal as long as the removal is driven by the same413 `archivable_tasks[]` list — do not re-select by status here.414415 3. Update specs/TODO.md:416 - Remove archived entries (both regular and TODO.md orphans) — the same417 `archivable_tasks[]` guard-filtered list from Stage 2; a deferred parent's entry stays418 - Pattern to match task entry start:419 ```lua420 -- Match both "### OC_N. " and "### N. " formats421 local task_start_pattern = "###%s+(OC_)?(%d+)%.%s+"422 ```423 - For each task to remove:424 a. Find entry start (header line)425 b. Find entry end (next task header or end of Active Tasks section)426 c. Extract complete entry including all lines427 d. Validate entry matches expected format before removal428 - Use Edit tool to remove validated entries:429 ```lua430 -- Remove the matched section431 edit_file("specs/TODO.md", old_entry_content, "")432 ```433 - Note: next_project_number should NOT be decremented when removing orphans434 (numbering continues from highest used number)435436 4. Move project directories to specs/archive/ — again driven by `archivable_tasks[]`; a437 deferred parent's directory stays in place until a later `/todo` run archives it. For438 each directory moved, append both its old and new path to `moved_paths[]`439 (`moved_paths+=("$old_dir" "$new_dir")`), mirroring `commands/todo.md`'s Step 5D440 pairing.441442 5. Track orphaned directories (if approved). For each directory moved from specs/ to443 specs/archive/, append both its old and new path to `moved_paths[]`444 (`moved_paths+=("$old_dir" "$new_dir")`), mirroring `commands/todo.md`'s Step 5E.1445 pairing.446447 7. Move misplaced directories (if approved). For each directory moved, append both its448 old and new path to `moved_paths[]` (`moved_paths+=("$old_dir" "$new_dir")`), mirroring449 `commands/todo.md`'s Step 5F pairing.450451 8. Archive TODO.md orphans:452 For each selected orphan in `selected_todo_orphans`:453 a. Build archive entry from TODO.md data:454 ```json455 {456 "project_number": orphan.project_number,457 "project_name": orphan.project_name,458 "status": orphan.status, // "completed" or "abandoned"459 "created_at": "TODO.md_orphan", // Marker indicating source460 "archived_at": "YYYY-MM-DDTHH:MM:SSZ"461 }462 ```463 b. Add entry to specs/archive/state.json completed_projects array, matching464 `commands/todo.md`'s Step 5E.2 shape (`$orphan` is the same JSON blob shown in465 step a):466 ```bash467 bash .claude/scripts/state-write.sh \468 '.completed_projects += [{469 project_number: $orphan.project_number,470 project_name: $orphan.project_name,471 status: $orphan.status,472 created_at: "TODO.md_orphan",473 archived_at: $ts474 }]' \475 --state-file specs/archive/state.json \476 --session-id "$todo_session_id" \477 --argjson orphan "$orphan" \478 --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)"479 ```480 c. Move directory from specs/ to specs/archive/:481 ```bash482 source_dir="specs/OC_${orphan.project_number}_${orphan.project_name}/"483 if [ ! -d "$source_dir" ]; then484 source_dir="specs/${orphan.project_number}_${orphan.project_name}/"485 fi486 target_dir="specs/archive/$(basename "$source_dir")"487 # specs/archive/ is gitignored: this mv removes every file under the directory from488 # version control (still on disk locally, absent from every fresh clone), so any489 # guard or probe citing a file by its task-directory path -- a WIRED_REPO reference --490 # breaks once the task is archived. No mechanical detector in this repository catches491 # this today; the file must be re-pointed, or promoted into specs/evidence/, before492 # archival, and that discipline is manual.493 mv "$source_dir" "$target_dir"494 # Pair both endpoints so `git add` records the source's removal -- see495 # context/standards/git-staging-scope.md's "Rename and Directory-Move Staging".496 moved_paths+=("$source_dir" "$target_dir")497 ```498 d. Track orphan archival for CHANGE_LOG.md499 e. If no directory found, log warning:500 ```501 Warning: TODO.md orphan {N} has no directory in specs/502 Archive entry created but no files moved503 ```504505 9. **Vault Threshold Check (MANDATORY)**506507 **CRITICAL: ALWAYS EXECUTE - DO NOT SKIP**508509 This sub-step MUST be executed unconditionally after archiving tasks.510 The bash block below produces output for BOTH vault-needed and vault-not-needed cases.511512 Execute vault threshold detection:513 ```bash514 # UNCONDITIONAL VAULT CHECK - produces output in all cases515 PROJECT_ROOT="${PROJECT_ROOT:-.}"516 STATE_FILE="${PROJECT_ROOT}/specs/state.json"517 VAULT_THRESHOLD=1000518519 next_num=$(jq -r '.next_project_number // 0' "$STATE_FILE")520521 if [[ "$next_num" -gt "$VAULT_THRESHOLD" ]]; then522 echo ""523 echo "=============================================="524 echo " VAULT THRESHOLD EXCEEDED"525 echo "=============================================="526 echo " next_project_number: $next_num"527 echo " threshold: $VAULT_THRESHOLD"528 echo " status: VAULT OPERATION REQUIRED"529 echo "=============================================="530 echo ""531 vault_needed=true532 else533 echo ""534 echo "Vault check: next_project_number=$next_num (threshold: $VAULT_THRESHOLD) - OK"535 echo ""536 vault_needed=false537 fi538 ```539540 **Decision Logic**:541 - If `vault_needed=true`: Proceed to sub-step 9.1 (VaultConfirmation)542 - If `vault_needed=false`: Skip sub-steps 9.1-9.4, continue to Stage 12 (UpdateREADME)543544 9.1. **VaultConfirmation** (if vault_needed=true)545546 Identify tasks requiring renumbering:547 ```bash548 # Find active tasks with project_number > 1000549 tasks_to_renumber=$(jq -r '550 .active_projects[] |551 select(.project_number > 1000) |552 {553 old_number: .project_number,554 new_number: (.project_number - 1000),555 project_name: .project_name,556 status: .status557 }558 ' specs/state.json)559560 # Count tasks to renumber561 renumber_count=$(echo "$tasks_to_renumber" | jq -s 'length')562563 # Build mapping array: [{old: 1001, new: 1}, {old: 1003, new: 3}, ...]564 renumber_mappings=$(jq -n --argjson tasks "$tasks_to_renumber" '565 [$tasks[] | {old: .old_number, new: .new_number, name: .project_name}]566 ')567 ```568569 Build preview of renumbering:570 ```bash571 # Format preview of task renumbering572 renumber_preview=""573 for mapping in $(echo "$renumber_mappings" | jq -c '.[]'); do574 old=$(echo "$mapping" | jq -r '.old')575 new=$(echo "$mapping" | jq -r '.new')576 name=$(echo "$mapping" | jq -r '.name')577 renumber_preview="${renumber_preview}\n - Task ${old} (${name}) -> Task ${new}"578 done579 ```580581 Present AskUserQuestion for vault confirmation:582 ```json583 {584 "question": "Task numbering has exceeded 1000. Initiate vault archival?",585 "header": "Vault Operation",586 "description": "Current next_project_number: {next_num}\nActive tasks to renumber: {renumber_count}\n\nRenumbering preview:{renumber_preview}\n\nThis will:\n1. Move specs/archive/ to specs/vault/{NN-vault}/\n2. Renumber tasks > 1000 by subtracting 1000\n3. Reset next_project_number",587 "multiSelect": false,588 "options": [589 {"label": "Yes, proceed with vault operation", "value": "proceed"},590 {"label": "No, skip vault this time", "value": "skip"}591 ]592 }593 ```594595 Handle user response:596 ```bash597 if [ "$user_response" = "proceed" ]; then598 vault_approved=true599 # Continue to sub-step 9.2600 else601 vault_approved=false602 # Skip to Stage 12 (UpdateREADME)603 fi604 ```605606 9.2. **CreateVault** (if vault_approved=true)607608 Calculate vault number:609 ```bash610 # Get current vault_count (or 0 if not set)611 vault_count=$(jq -r '.vault_count // 0' specs/state.json)612 new_vault_num=$((vault_count + 1))613 vault_dir_name=$(printf "%02d-vault" "$new_vault_num")614 vault_path="specs/vault/${vault_dir_name}"615 ```616617 Create vault directory structure:618 ```bash619 mkdir -p "$vault_path"620 ```621622 Move archive contents to vault:623 ```bash624 # Move archive directory to vault625 if [ -d "specs/archive" ]; then626 mv "specs/archive" "${vault_path}/archive"627 fi628 ```629630 Move archive state.json to vault root (a file rename, not a state write -- correctly631 outside state-write.sh's remit):632 ```bash633 # Archive state.json becomes vault state.json634 if [ -f "${vault_path}/archive/state.json" ]; then635 mv "${vault_path}/archive/state.json" "${vault_path}/state.json"636 fi637638 # Pair the rename's exact old and new paths together so `git add` records it rather639 # than leaving the old tree's removal unstaged -- mirrors commands/todo.md's identical640 # vault-site pairing. See context/standards/git-staging-scope.md's "Rename and641 # Directory-Move Staging" section.642 moved_paths+=(specs/archive "${vault_path}/")643 ```644645 Create vault meta.json:646 ```bash647 # Calculate metadata648 current_timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ")649 archived_count=$(jq -r '.completed_projects | length' "${vault_path}/state.json" 2>/dev/null || echo "0")650 task_range="1-$((next_num - renumber_count - 1))"651652 # Create meta.json653 jq -n \654 --arg vault_num "$new_vault_num" \655 --arg created_at "$current_timestamp" \656 --arg task_range "$task_range" \657 --argjson archived_count "$archived_count" \658 --argjson final_task_num "$next_num" \659 '{660 vault_number: ($vault_num | tonumber),661 created_at: $created_at,662 task_range: $task_range,663 archived_count: $archived_count,664 final_task_number: $final_task_num,665 description: "Vault containing archived tasks from task numbering cycle"666 }' > "${vault_path}/meta.json"667 ```668669 Reinitialize empty specs/archive/ with fresh state.json via `state-write.sh`'s `--init`670 mode. The timestamp is bound with `--arg`, not shell-interpolated into the filter:671 ```bash672 mkdir -p "specs/archive"673674 # Create fresh archive state.json675 bash .claude/scripts/state-write.sh \676 '{677 "_comment": "Archive state for completed and abandoned tasks",678 "completed_projects": [],679 "archived_at": $ts680 }' \681 --init --state-file specs/archive/state.json --session-id "$todo_session_id" \682 --arg ts "$current_timestamp"683 ```684685 9.3. **RenumberTasks** (if vault_approved=true)686687 For each task in renumber_mappings, update state.json:688 ```bash689 # Update each task's project_number and artifact paths690 for mapping in $(echo "$renumber_mappings" | jq -c '.[]'); do691 old_num=$(echo "$mapping" | jq -r '.old')692 new_num=$(echo "$mapping" | jq -r '.new')693 task_name=$(echo "$mapping" | jq -r '.name')694695 # Update project_number696 # Update artifact paths (4-digit dir -> 3-digit dir)697 old_padded=$(printf "%04d" "$old_num")698 new_padded=$(printf "%03d" "$new_num")699700 # Use state-write.sh to update the task entry701 bash .claude/scripts/state-write.sh \702 '703 .active_projects |= map(704 if .project_number == $old then705 .project_number = $new |706 .artifacts |= (if . then map(707 .path |= gsub("specs/\($old_pad)_"; "specs/\($new_pad)_") |708 .path |= gsub("specs/\($old)_"; "specs/\($new_pad)_")709 ) else . end)710 else . end711 )712 ' \713 --session-id "$todo_session_id" \714 --argjson old "$old_num" \715 --argjson new "$new_num" \716 --arg old_pad "$old_padded" \717 --arg new_pad "$new_padded"718 done719 ```720721 Update dependencies arrays (task numbers > 1000):722 ```bash723 # Build mapping for all renumbered tasks724 bash .claude/scripts/state-write.sh \725 '726 # Create lookup from mappings727 ($mappings | map({(.old | tostring): .new}) | add) as $lookup |728 .active_projects |= map(729 .dependencies |= (if . then map(730 . as $dep |731 if $lookup[$dep | tostring] then732 $lookup[$dep | tostring]733 else $dep end734 ) else . end)735 )736 ' \737 --session-id "$todo_session_id" \738 --argjson mappings "$renumber_mappings"739 ```740741 Rename task directories:742 ```bash743 for mapping in $(echo "$renumber_mappings" | jq -c '.[]'); do744 old_num=$(echo "$mapping" | jq -r '.old')745 new_num=$(echo "$mapping" | jq -r '.new')746 task_name=$(echo "$mapping" | jq -r '.name')747748 old_padded=$(printf "%04d" "$old_num")749 new_padded=$(printf "%03d" "$new_num")750751 # Find source directory (could be 3-digit or 4-digit padded)752 source_dir=""753 if [ -d "specs/${old_padded}_${task_name}" ]; then754 source_dir="specs/${old_padded}_${task_name}"755 elif [ -d "specs/${old_num}_${task_name}" ]; then756 source_dir="specs/${old_num}_${task_name}"757 fi758759 # Rename to 3-digit padded format760 if [ -n "$source_dir" ]; then761 target_dir="specs/${new_padded}_${task_name}"762 mv "$source_dir" "$target_dir"763 # Pair both endpoints so `git add` records the source's removal -- see764 # context/standards/git-staging-scope.md's "Rename and Directory-Move Staging".765 moved_paths+=("$source_dir" "$target_dir")766 fi767 done768 ```769770 Update TODO.md entries:771 ```bash772 for mapping in $(echo "$renumber_mappings" | jq -c '.[]'); do773 old_num=$(echo "$mapping" | jq -r '.old')774 new_num=$(echo "$mapping" | jq -r '.new')775776 old_padded=$(printf "%04d" "$old_num")777 new_padded=$(printf "%03d" "$new_num")778779 # Update task headers: ### 1001. Title -> ### 1. Title780 sed -i "s/^### ${old_num}\./### ${new_num}./" specs/TODO.md781782 # Update artifact links with directory references783 sed -i "s|${old_padded}_|${new_padded}_|g" specs/TODO.md784 sed -i "s|${old_num}_|${new_padded}_|g" specs/TODO.md785786 # Update dependency references787 sed -i "s|Task #${old_num}|Task #${new_num}|g" specs/TODO.md788 done789 ```790791 9.4. **ResetState** (if vault_approved=true)792793 Calculate new next_project_number:794 ```bash795 # Find maximum project_number in active_projects after renumbering796 max_active=$(jq -r '[.active_projects[].project_number] | max // 0' specs/state.json)797 new_next_num=$((max_active + 1))798 ```799800 Update state.json with new next_project_number:801 ```bash802 bash .claude/scripts/state-write.sh \803 '.next_project_number = $new_next' \804 --session-id "$todo_session_id" \805 --argjson new_next "$new_next_num"806 ```807808 Increment vault_count:809 ```bash810 bash .claude/scripts/state-write.sh \811 '.vault_count = (.vault_count // 0) + 1' \812 --session-id "$todo_session_id"813 ```814815 Add entry to vault_history:816 ```bash817 current_timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ")818 archived_count=$(jq -r '.completed_projects | length' "${vault_path}/state.json" 2>/dev/null || echo "0")819 task_range="1-$((next_num - renumber_count - 1))"820821 bash .claude/scripts/state-write.sh \822 '823 .vault_history = (.vault_history // []) + [{824 vault_number: $vault_num,825 vault_dir: $vault_dir,826 created_at: $created,827 task_range: $range,828 archived_count: $archived,829 final_task_number: $final830 }]831 ' \832 --session-id "$todo_session_id" \833 --arg vault_dir "$vault_path/" \834 --argjson vault_num "$new_vault_num" \835 --arg created "$current_timestamp" \836 --arg range "$task_range" \837 --argjson archived "$archived_count" \838 --argjson final "$next_num"839 ```840841 After sub-step 9.4 completes, continue to Stage 12 (UpdateREADME).842843 <!-- CHECKPOINT: Stage 10 complete when vault_check output is present AND844 (vault_needed=false OR vault operations 9.1-9.4 completed) -->845 </process>846 <checkpoint>vault_check_complete output present; if vault_needed, sub-steps 9.1-9.4 executed</checkpoint>847 </stage>848849 <stage id="12" name="UpdateREADME">850 <action>Apply README.md suggestions</action>851 <process>852 1. Filter suggestions where action != "none"853 2. Present AskUserQuestion with multiSelect for review854 3. Apply selected suggestions via Edit tool855 4. Display results (applied/failed/skipped)856 5. Acknowledge "none" action tasks857 </process>858 </stage>859 860 <stage id="13" name="UpdateChangelog">861 <action>Update CHANGE_LOG.md with archive entries</action>862 <process>863 1. Create specs/CHANGE_LOG.md if not exists (header + format description)864 2. For each archived task, append dated entry with: task number/name, status, type, completion_summary, artifact list865 - `status` here already flows straight through from the task's state.json entry, so an866 `expanded` entry is recorded exactly as `completed`/`abandoned` entries are — expanded867 is a valid archived status in CHANGE_LOG entries, no separate handling needed868 </process>869 </stage>870871 <!-- No CreateMemories stage here. A task's recorded `memory_candidates` are harvested by872 `/distill --learn`'s retroactive sweep across already-archived tasks, which is bounded873 per invocation and gated interactively, rather than at archival time, where one `/todo`874 run can archive many tasks at once and would otherwise write permanent, unreviewed875 knowledge objects in bulk. `memory_candidates` is still recorded on each task entry and is876 still implicitly cleaned when the entry moves to archive during Stage 10 -- nothing is877 lost by not harvesting here, since `/878879…(truncated)