#!/usr/bin/env bash
# OpenLogos Phase Detector — lightweight shell script for Claude Code plugin hooks.
# Reads logos/logos.config.json and scans logos/resources/ to determine current phase.
#
# When called from SessionStart hook: outputs JSON with systemMessage + additionalContext.
# When called directly (e.g. from commands): outputs plain text.
#
# Usage:
#   ./openlogos-phase              → JSON output (for hooks)
#   ./openlogos-phase --plain      → plain text output (for commands / terminal)

set -euo pipefail

# fix-guard-background-record-never-closed：hook（JSON）模式下，在启动任何子进程之前读取一次宿主交来的 SessionStart 输入
# 并保存，之后原样转交事后检查引擎（引擎从中取 session_id，用于超期关闭的当前会话判断）。本脚本不解析、不改写、不落盘
# 该输入。--plain 模式不读取；stdin 是终端、为空或读取失败时保存为空，引擎按空输入处理（本次不做超期关闭）。
# 读取设 2 秒上限：宿主未关闭 stdin 时不让会话启动卡住，超时按空输入处理。
OPENLOGOS_HOOK_INPUT=""
if [ "${1:-}" != "--plain" ] && [ ! -t 0 ]; then
  IFS= read -r -d '' -t 2 OPENLOGOS_HOOK_INPUT || true
fi

has_files() {
  local dir="$1"
  [ -d "$dir" ] && [ -n "$(find "$dir" -maxdepth 3 -type f ! -name '.gitkeep' -print -quit 2>/dev/null)" ]
}

# 从 logos-project.yaml 读取 scenarios[].id 列表，空格分隔
# 若字段不存在或解析失败，返回空字符串
get_scenario_ids() {
  local yaml_file="logos/logos-project.yaml"
  if [ ! -f "$yaml_file" ]; then
    echo ""
    return
  fi
  # node 为主路径（以执行成功为准）；node 不可执行时才用真实可执行的 Python。本函数自包含，
  # 不依赖脚本顶层变量（可按函数边界单独加载）。
  if node - "$yaml_file" 2>/dev/null <<'JSEOF'
const fs = require('fs');
const content = fs.readFileSync(process.argv[1], 'utf-8');
const ids = [];
let inScenarios = false;
for (const line of content.split('\n')) {
  if (/^scenarios\s*:/.test(line)) { inScenarios = true; continue; }
  if (inScenarios) {
    if (/^[a-zA-Z]/.test(line)) break;
    const m = line.match(/\s+-?\s*id\s*:\s*["']?(\S+?)["']?\s*$/);
    if (m) ids.push(m[1]);
  }
}
console.log(ids.join(' '));
JSEOF
  then
    return
  fi
  if declare -F has_python >/dev/null && has_python && run_python - "$yaml_file" 2>/dev/null <<'PYEOF'
import sys, re
path = sys.argv[1]
content = open(path).read()
# 简单解析 scenarios 块中的 id 字段（不依赖 PyYAML）
in_scenarios = False
ids = []
for line in content.splitlines():
    if re.match(r'^scenarios\s*:', line):
        in_scenarios = True
        continue
    if in_scenarios:
        # 遇到新的顶层字段则退出
        if re.match(r'^[a-zA-Z]', line):
            break
        m = re.match(r'\s+-?\s*id\s*:\s*["\']?(\S+?)["\']?\s*$', line)
        if m:
            ids.append(m.group(1))
print(' '.join(ids))
PYEOF
  then
    return
  fi
  echo ""
}

# 检查某个 phase 下所有已声明场景是否都有对应文件
# 参数: $1=目录, $2=文件名 glob 模式(不含SXX前缀), $3=扩展名(如 .md 或 .yaml .yml)
# 返回: 0=全部完成, 1=有缺失; 缺失的 ID 输出到 stdout
#
# 本函数是 per-scenario 覆盖判定的**从属实现**——权威口径是 `cli/src/commands/status.ts`
# （判据键 `<module>-<scenarioId>`）。两处必须在恒等域（目标目录内全部为 <module>-SXX-*
# 规范命名、单模块）上得出相同的 missing 集合；域外差异见场景 S11「已知差异清单」。
#
# 两条约束（fix-merge-prototype-commit-and-phase-module-prefix）：
#  ① 扩展名模式必须以**字面量**到达 find 的 -name。`for pat in $ext_pattern` 的未加引用展开
#     同时触发**文件名展开**：脚本在项目根执行时 `*.md` 会先变成 README.md / AGENTS.md /
#     CLAUDE.md（API 臂的 `*.yaml *.yml` 同理），拼出的是 `-name S76-AGENTS.md`，与场景文件
#     毫无关系。故分词期间关闭 pathname expansion（set -f），结束后按进入时的状态恢复——
#     探测结果不得随 cwd 下有哪些文件而变（INV-SC4）。
#  ② 匹配取两形态之并：`${sid}-${pat}` 命中无前缀历史命名，`*-${sid}-${pat}` 命中
#     `spec/module-naming-convention.md` 规定的 <module>-SXX-* 规范命名。一处修正同时
#     覆盖场景时序 / API / 测试用例三个调用点。放宽匹配不得漏报真实缺失。
check_scenarios_complete() {
  local dir="$1"
  local ext_pattern="$2"   # 例如 "*.md" 或 "*.yaml *.yml"
  local scenario_ids
  scenario_ids=$(get_scenario_ids)

  if [ -z "$scenario_ids" ]; then
    # 无 scenarios 声明，降级为旧逻辑
    echo "__fallback__"
    return 0
  fi

  # 进入时 globbing 已关闭则保持关闭（不擅自改变调用方的 shell 选项）
  local glob_was_off=false
  case "$-" in *f*) glob_was_off=true ;; esac
  set -f

  local missing=""
  for sid in $scenario_ids; do
    local found=false
    for pat in $ext_pattern; do
      if find "$dir" -maxdepth 1 \( -name "${sid}-${pat}" -o -name "*-${sid}-${pat}" \) 2>/dev/null | grep -q .; then
        found=true
        break
      fi
    done
    if [ "$found" = "false" ]; then
      missing="$missing $sid"
    fi
  done

  [ "$glob_was_off" = "true" ] || set +f

  if [ -n "$missing" ]; then
    echo "$missing"
    return 1
  fi
  return 0
}

# ── Runtime probing（fix-windows-platform-compat，架构 §五十二 52.5）────────────────────
# node 是 OpenLogos 运行前提，为全部 JSON / YAML 读取的主路径；node 不可执行时才用 Python。
# Python 候选依次 python3 → python → py -3，以执行 `-c "import sys"` 退出 0 为可用判据，不以 PATH
# 可发现性为准（Windows 上 python3 常为可被发现、运行即失败的商店占位别名）。探测结果在一次调用内复用。
NODE_OK=0
if node -e "" </dev/null >/dev/null 2>&1; then
  NODE_OK=1
fi
OPENLOGOS_PY=""
detect_python() {
  [ -n "${OPENLOGOS_PY:-}" ] && return 0
  OPENLOGOS_PY="none"
  local cand
  for cand in "python3" "python" "py -3"; do
    # shellcheck disable=SC2086
    if $cand -c "import sys" </dev/null >/dev/null 2>&1; then
      OPENLOGOS_PY="$cand"
      return 0
    fi
  done
  return 0
}
has_python() {
  detect_python
  [ "$OPENLOGOS_PY" != "none" ]
}
run_python() {
  # shellcheck disable=SC2086
  $OPENLOGOS_PY "$@"
}
if [ "$NODE_OK" -ne 1 ]; then
  detect_python
fi


MODE="json"
if [ "${1:-}" = "--plain" ]; then
  MODE="plain"
fi

CONFIG="logos/logos.config.json"

if [ ! -f "$CONFIG" ]; then
  if [ "$MODE" = "json" ]; then
    echo '{"systemMessage":"Not an OpenLogos project"}'
  else
    echo "⚠ This is not an OpenLogos project (logos/logos.config.json not found)."
    echo "Run \`openlogos init\` to initialize."
  fi
  exit 0
fi

LOCALE="en"
LIFECYCLE="initial"
PROJECT_NAME=""
STATUS_JSON=""
STATUS_LIFECYCLE=""
STATUS_ACTIVE_CHANGE=""
STATUS_PROPOSAL_STEP=""
STATUS_PLAN_STATE_SUMMARY=""

if [ "$NODE_OK" -eq 1 ]; then
  LOCALE=$(node -e "const d=JSON.parse(require('fs').readFileSync('$CONFIG','utf-8')); console.log(d.locale||'en')" 2>/dev/null || echo "en")
  PROJECT_NAME=$(node -e "const d=JSON.parse(require('fs').readFileSync('$CONFIG','utf-8')); console.log(d.name||'')" 2>/dev/null || echo "")
fi
if [ "$NODE_OK" -ne 1 ] && has_python; then
  LOCALE=$(run_python -c "import json; d=json.load(open('$CONFIG')); print(d.get('locale','en'))" 2>/dev/null || echo "en")
  PROJECT_NAME=$(run_python -c "import json; d=json.load(open('$CONFIG')); print(d.get('name',''))" 2>/dev/null || echo "")
fi

if command -v openlogos &>/dev/null; then
  # 非零退出即视为 status 不可用：丢弃失败前已写到 stdout 的内容（S11 约束 5a-2，code-r1 F1）
  if ! STATUS_JSON=$(openlogos status --format json 2>/dev/null); then
    STATUS_JSON=""
  fi
fi

if [ -n "$STATUS_JSON" ]; then
  if [ "$NODE_OK" -eq 1 ]; then
    STATUS_LIFECYCLE=$(echo "$STATUS_JSON" | node -e "const d=require('fs').readFileSync(0,'utf-8');(()=>{try{const data=(JSON.parse(d).data)||{};console.log(data.lifecycle||'')}catch(e){console.log('')}})()" 2>/dev/null || echo "")
    STATUS_ACTIVE_CHANGE=$(echo "$STATUS_JSON" | node -e "const d=require('fs').readFileSync(0,'utf-8');(()=>{try{const data=(JSON.parse(d).data)||{};const mod=(data.modules||[]).find(m=>m.active_change&&m.active_change.slug);console.log(data.active_change||mod?.active_change?.slug||'')}catch(e){console.log('')}})()" 2>/dev/null || echo "")
    STATUS_PROPOSAL_STEP=$(echo "$STATUS_JSON" | node -e "const d=require('fs').readFileSync(0,'utf-8');(()=>{try{const data=(JSON.parse(d).data)||{};const mod=(data.modules||[]).find(m=>m.active_change&&m.active_change.proposal_step);console.log(data.proposal_step||mod?.active_change?.proposal_step||'')}catch(e){console.log('')}})()" 2>/dev/null || echo "")
    STATUS_PLAN_STATE_SUMMARY=$(echo "$STATUS_JSON" | node -e "const d=require('fs').readFileSync(0,'utf-8');(()=>{try{const data=(JSON.parse(d).data)||{};const active=data.active_change||'';let ps=data.plan_state;for(const m of data.modules||[]){const ac=m.active_change;if(!ac) continue;if(active&&ac.slug!==active) continue;ps=ps||ac.plan_state;break;}console.log(!ps?'':\`plan_ready=\${!!ps.plan_ready}, plan_gate_pending=\${!!ps.plan_gate_pending}, plan_approved=\${!!ps.plan_approved}, tasks_execution=\${ps.tasks_execution_done??0}/\${ps.tasks_execution_total??0} \${ps.tasks_execution_scope||'none'}\`)}catch(e){console.log('')}})()" 2>/dev/null || echo "")
  fi
  if [ "$NODE_OK" -ne 1 ] && has_python; then
    STATUS_LIFECYCLE=$(echo "$STATUS_JSON" | run_python -c "import sys,json; d=json.load(sys.stdin); print(d.get('data',{}).get('lifecycle',''))" 2>/dev/null || echo "")
    STATUS_ACTIVE_CHANGE=$(echo "$STATUS_JSON" | run_python -c "import sys,json; d=json.load(sys.stdin); data=d.get('data',{}); active=data.get('active_change') or ''; mods=data.get('modules') or []; print(active or next((m.get('active_change',{}).get('slug','') for m in mods if isinstance(m.get('active_change'),dict) and m.get('active_change',{}).get('slug')), ''))" 2>/dev/null || echo "")
    STATUS_PROPOSAL_STEP=$(echo "$STATUS_JSON" | run_python -c "import sys,json; d=json.load(sys.stdin); data=d.get('data',{}); step=data.get('proposal_step') or ''; mods=data.get('modules') or []; print(step or next((m.get('active_change',{}).get('proposal_step','') for m in mods if isinstance(m.get('active_change'),dict) and m.get('active_change',{}).get('proposal_step')), ''))" 2>/dev/null || echo "")
    STATUS_PLAN_STATE_SUMMARY=$(echo "$STATUS_JSON" | run_python -c "import sys,json; d=json.load(sys.stdin); data=d.get('data',{}); active=data.get('active_change') or ''; ps=data.get('plan_state'); mods=data.get('modules') or [];
for m in mods:
  ac=m.get('active_change') if isinstance(m.get('active_change'),dict) else None
  if not ac: continue
  if active and ac.get('slug') != active: continue
  ps = ps or ac.get('plan_state'); break
print('' if not isinstance(ps,dict) else 'plan_ready=%s, plan_gate_pending=%s, plan_approved=%s, tasks_execution=%s/%s %s' % (str(bool(ps.get('plan_ready'))).lower(), str(bool(ps.get('plan_gate_pending'))).lower(), str(bool(ps.get('plan_approved'))).lower(), ps.get('tasks_execution_done',0), ps.get('tasks_execution_total',0), ps.get('tasks_execution_scope','none')))" 2>/dev/null || echo "")
  fi
fi

# API 阶段按模块进度判定（S11 约束 5a）：只消费上面那一次可选 status 结果，不新增 CLI 调用。
# STATUS_API_USABLE=1 表示 status 结果可解析、含 data.modules[] 且每个 initial 模块都带 phase_progress；
# STATUS_API_PENDING 为 phase.3-2-api 既未完成也未跳过的 initial 模块 id（升序、空格分隔）。
STATUS_API_USABLE=0
STATUS_API_PENDING=""
if [ -n "$STATUS_JSON" ]; then
  _api_probe=""
  if [ "$NODE_OK" -eq 1 ]; then
    _api_probe=$(echo "$STATUS_JSON" | node -e "const d=require('fs').readFileSync(0,'utf-8');(()=>{try{const data=(JSON.parse(d)||{}).data;if(!data||!Array.isArray(data.modules)){console.log('NA');return}const init=data.modules.filter(m=>m&&m.lifecycle==='initial');if(init.some(m=>!m.phase_progress||typeof m.phase_progress!=='object')){console.log('NA');return}const ids=init.filter(m=>{const p=m.phase_progress['phase.3-2-api'];return p&&p.done!==true&&p.skipped!==true}).map(m=>String(m.id)).sort();console.log(('OK '+ids.join(' ')).trim())}catch(e){console.log('NA')}})()" 2>/dev/null || echo "NA")
  fi
  if [ "$NODE_OK" -ne 1 ] && has_python; then
    _api_probe=$(echo "$STATUS_JSON" | run_python -c "
import sys,json
try:
  data=(json.load(sys.stdin) or {}).get('data')
  mods=data.get('modules') if isinstance(data,dict) else None
  if not isinstance(mods,list): print('NA'); sys.exit(0)
  init=[m for m in mods if isinstance(m,dict) and m.get('lifecycle')=='initial']
  if any(not isinstance(m.get('phase_progress'),dict) for m in init): print('NA'); sys.exit(0)
  ids=sorted(str(m.get('id')) for m in init if isinstance(m['phase_progress'].get('phase.3-2-api'),dict) and m['phase_progress']['phase.3-2-api'].get('done') is not True and m['phase_progress']['phase.3-2-api'].get('skipped') is not True)
  print(('OK '+' '.join(ids)).strip())
except Exception:
  print('NA')
" 2>/dev/null || echo "NA")
  fi
  case "$_api_probe" in
    OK|OK\ *)
      STATUS_API_USABLE=1
      STATUS_API_PENDING="${_api_probe#OK}"
      STATUS_API_PENDING="${STATUS_API_PENDING# }"
      ;;
  esac
fi

# 从 logos-project.yaml 的 modules[].lifecycle 推导项目级 lifecycle
# 任意模块标记为 launched 则项目为 launched
# skip_phases 只读取 lifecycle=initial 的模块，避免多模块时误跳过其他模块的阶段
YAML_FILE="logos/logos-project.yaml"
SKIP_API=false
SKIP_DATABASE=false
SKIP_SCENARIO=false

if [ -f "$YAML_FILE" ]; then
  if grep -q 'lifecycle.*launched' "$YAML_FILE" 2>/dev/null; then
    LIFECYCLE="launched"
  fi

  # 只从 initial 模块读取 skip_phases，用 awk 解析避免 heredoc 语法问题
  _skip_result=""
  if [ "$NODE_OK" -eq 1 ]; then
    _js_script=$(mktemp "${TMPDIR:-/tmp}/openlogos_skip.XXXXXX")
    cat > "$_js_script" << 'JSEOF'
const fs = require('fs');
const content = fs.readFileSync(process.argv[2], 'utf-8');
let inModules = false, curLifecycle = 'initial', curSkip = [], allSkip = [];
for (const line of content.split('\n')) {
  if (/^modules\s*:/.test(line)) { inModules = true; continue; }
  if (inModules) {
    if (/^[a-zA-Z]/.test(line) && !/^\s/.test(line)) break;
    if (/\s+-\s+id\s*:/.test(line)) {
      if (curLifecycle === 'initial') allSkip.push(...curSkip);
      curLifecycle = 'initial'; curSkip = [];
    }
    const lm = line.match(/lifecycle\s*:\s*(\S+)/);
    if (lm) curLifecycle = lm[1].replace(/['"]/g, '');
    const sm = line.match(/skip_phases\s*:\s*\[([^\]]*)\]/);
    if (sm) curSkip = sm[1].split(',').map(s => s.trim().replace(/['"]/g, '')).filter(Boolean);
  }
}
if (curLifecycle === 'initial') allSkip.push(...curSkip);
console.log([...new Set(allSkip)].join(' '));
JSEOF
    _skip_result=$(node "$_js_script" "$YAML_FILE" 2>/dev/null || echo "")
    rm -f "$_js_script"
  fi
  if [ "$NODE_OK" -ne 1 ] && has_python; then
    _py_script=$(mktemp "${TMPDIR:-/tmp}/openlogos_skip.XXXXXX")
    cat > "$_py_script" << 'PYEOF'
import sys, re
path = sys.argv[1]
content = open(path).read()
in_modules = False
current_lifecycle = 'initial'
current_skip = []
all_skip = []
for line in content.splitlines():
    if re.match(r'^modules\s*:', line):
        in_modules = True
        continue
    if in_modules:
        if re.match(r'^[a-zA-Z]', line) and not re.match(r'^\s', line):
            break
        if re.match(r'\s+-\s+id\s*:', line):
            if current_lifecycle == 'initial':
                all_skip.extend(current_skip)
            current_lifecycle = 'initial'
            current_skip = []
        m = re.search(r'lifecycle\s*:\s*(\S+)', line)
        if m:
            current_lifecycle = m.group(1).strip('"\'')
        m = re.search(r'skip_phases\s*:\s*\[([^\]]*)\]', line)
        if m:
            current_skip = [s.strip().strip('"\'') for s in m.group(1).split(',') if s.strip()]
if current_lifecycle == 'initial':
    all_skip.extend(current_skip)
print(' '.join(set(all_skip)))
PYEOF
    _skip_result=$(run_python "$_py_script" "$YAML_FILE" 2>/dev/null || echo "")
    rm -f "$_py_script"
  fi
  if [ "$NODE_OK" -ne 1 ] && ! has_python; then
    # 降级：全文 grep（多模块时可能误判，但总比不跳过好）
    grep 'skip_phases' "$YAML_FILE" 2>/dev/null | grep -q 'api'      && _skip_result="$_skip_result api"
    grep 'skip_phases' "$YAML_FILE" 2>/dev/null | grep -q 'database' && _skip_result="$_skip_result database"
    grep 'skip_phases' "$YAML_FILE" 2>/dev/null | grep -q 'scenario' && _skip_result="$_skip_result scenario"
  fi

  echo "$_skip_result" | grep -q '\bapi\b'      && SKIP_API=true      || true
  echo "$_skip_result" | grep -q '\bdatabase\b' && SKIP_DATABASE=true  || true
  echo "$_skip_result" | grep -q '\bscenario\b' && SKIP_SCENARIO=true  || true
fi

if [ -n "$STATUS_LIFECYCLE" ]; then
  LIFECYCLE="$STATUS_LIFECYCLE"
fi

P1="logos/resources/prd/1-product-requirements"
P2="logos/resources/prd/2-product-design"
P3_ARCH="logos/resources/prd/3-technical-plan/1-architecture"
P3_SCEN="logos/resources/prd/3-technical-plan/2-scenario-implementation"
P_API="logos/resources/api"
P_DATABASE="logos/resources/database"
P_TEST="logos/resources/test"
P_SCENARIO="logos/resources/scenario"
P_VERIFY="logos/resources/verify"

PHASE=""
SKILL=""
SKILL_DESC=""

# 向后看兜底逻辑：后续阶段已有文件时，自动跳过空的 api/database/scenario 目录
# 与 CLI 的 lastDoneIdx 逻辑对应，向后兼容无 skip_phases 的旧项目
if [ "$SKIP_API" = "false" ] && ! has_files "$P_API"; then
  if has_files "$P_TEST" || has_files "$P_SCENARIO" || has_files "$P_VERIFY"; then
    SKIP_API=true
  fi
fi
if [ "$SKIP_DATABASE" = "false" ] && ! has_files "$P_DATABASE"; then
  if has_files "$P_TEST" || has_files "$P_SCENARIO" || has_files "$P_VERIFY"; then
    SKIP_DATABASE=true
  fi
fi
if [ "$SKIP_SCENARIO" = "false" ] && ! has_files "$P_SCENARIO"; then
  if has_files "$P_VERIFY"; then
    SKIP_SCENARIO=true
  fi
fi

if ! has_files "$P1"; then
  PHASE="Phase 1: Product Requirements"
  SKILL="prd-writer"
  SKILL_DESC="Write product requirements documents"
elif ! has_files "$P2"; then
  PHASE="Phase 2: Product Design"
  SKILL="product-designer"
  SKILL_DESC="Create product design specifications"
elif ! has_files "$P3_ARCH"; then
  PHASE="Phase 3 Step 0: Architecture Design"
  SKILL="architecture-designer"
  SKILL_DESC="Design technical architecture"
elif ! has_files "$P3_SCEN"; then
  PHASE="Phase 3 Step 1: Scenario Modeling"
  SKILL="scenario-architect"
  SKILL_DESC="Model business scenarios as sequence diagrams"
else
  # Phase 3-1 目录有文件，进一步检查场景完整性
  _scen_missing=$(check_scenarios_complete "$P3_SCEN" "*.md" || true)
  if [ "$_scen_missing" = "__fallback__" ]; then
    : # 无 scenarios 声明，视为完成，继续向下走
  elif [ -n "$_scen_missing" ]; then
    PHASE="Phase 3 Step 1: Scenario Modeling (incomplete: missing${_scen_missing})"
    SKILL="scenario-architect"
    SKILL_DESC="Complete remaining scenario sequence diagrams"
  fi
fi

# API 阶段（S11 约束 5a）：API 按业务领域分文件、不带场景编号，不做逐场景判定，不输出 missing。
if [ -z "$PHASE" ]; then
  if [ "$STATUS_API_USABLE" -eq 1 ]; then
    # status 路径：按 initial 模块的 phase.3-2-api 判定，结论覆盖 SKIP_API 与向后看兜底
    if [ -n "$STATUS_API_PENDING" ]; then
      PHASE="Phase 3 Step 2: API & Database Design (modules: ${STATUS_API_PENDING})"
      SKILL="api-designer"
      SKILL_DESC="Design OpenAPI specifications (also run db-designer)"
    fi
  elif [ "$SKIP_API" = "true" ]; then
    : # 降级路径：skip api phase
  elif ! has_files "$P_API"; then
    PHASE="Phase 3 Step 2: API & Database Design"
    SKILL="api-designer"
    SKILL_DESC="Design OpenAPI specifications (also run db-designer)"
  fi
fi

if [ -z "$PHASE" ]; then
  if [ "$SKIP_DATABASE" = "true" ]; then
    : # skip database phase
  elif ! has_files "$P_DATABASE"; then
    PHASE="Phase 3 Step 2: Database Design"
    SKILL="db-designer"
    SKILL_DESC="Design database schema (DDL)"
  fi
fi

if [ -z "$PHASE" ]; then
  if ! has_files "$P_TEST"; then
    PHASE="Phase 3 Step 3a: Test Cases"
    SKILL="test-writer"
    SKILL_DESC="Write test case documents"
  else
    # Phase 3-3a 目录有文件，检查场景完整性
    _test_missing=$(check_scenarios_complete "$P_TEST" "*.md" || true)
    if [ "$_test_missing" = "__fallback__" ]; then
      : # 降级，继续
    elif [ -n "$_test_missing" ]; then
      PHASE="Phase 3 Step 3a: Test Cases (incomplete: missing${_test_missing})"
      SKILL="test-writer"
      SKILL_DESC="Complete remaining test case documents"
    fi
  fi
fi

if [ -z "$PHASE" ]; then
  if [ "$SKIP_SCENARIO" = "true" ]; then
    : # skip scenario/orchestration phase
  elif ! has_files "$P_SCENARIO"; then
    PHASE="Phase 3 Step 3b: Orchestration Tests"
    SKILL="test-orchestrator"
    SKILL_DESC="Design API orchestration test scenarios"
  fi
fi

if [ -z "$PHASE" ]; then
  if ! has_files "$P_VERIFY"; then
    PHASE="Phase 3 Step 4-5: Code Generation & Verification"
    SKILL="code-reviewer"
    SKILL_DESC="Generate code and run verification"
  else
    PHASE="All phases complete"
    SKILL=""
  fi
fi

# Build language policy text
if [ "$LOCALE" = "zh" ]; then
  LANG_POLICY="Language Policy: ALL output MUST be in Chinese (中文)."
else
  LANG_POLICY="Language Policy: ALL output MUST be in English."
fi

# GUI UI-first overlay detection: the project instance flow (logos/flow/launched.yaml)
# has the write-ui-prototype node injected only for GUI projects. When present we grant
# a plan-stage exception allowing the page-design prototype delta.
ui_first_exception_text() {
  local active="$1"
  if [ -f "logos/flow/launched.yaml" ] && grep -q 'write-ui-prototype' "logos/flow/launched.yaml" 2>/dev/null; then
    echo " 例外：GUI 项目且本次触及 UI（ui_impact）时，允许在 plan 阶段产出 page-design 原型 delta（logos/changes/$active/deltas/prd/2-product-design/2-page-design/*.html）；其余 delta 仍禁于 plan 阶段。"
  else
    echo ""
  fi
}

change_management_message() {
  local active="$1"
  local step="${2:-}"
  local plan_state="${3:-}"
  local base="Change Management: ACTIVE — guard file detected. Active change proposal: '$active'."
  local confirm="openlogos merge, openlogos verify, openlogos smoke, openlogos archive, deployment, and git push are human confirmation points: AI must not execute them without explicit user authorization."
  local ui_exc
  ui_exc="$(ui_first_exception_text "$active")"
  # make-phase-banner-informational: post-plan branches describe typical work, never an
  # exclusive write scope — the banner has no enforcement power, is a session-start snapshot,
  # and carries no role information. Write enforcement lives in the PreToolUse guard-check.
  local scope_note="This banner is session-start context, not a write allowlist: the actual write scope follows the host's current task assignment, and out-of-bounds writes are blocked by the PreToolUse guard."

  case "$step" in
    writing)
      echo "$base Current proposal step: writing. Allowed files: logos/changes/$active/proposal.md and logos/changes/$active/tasks.md. Do not write deltas or source code yet.${ui_exc} $confirm"
      ;;
    ready-to-delta)
      echo "$base Current proposal step: ready-to-delta. The plan is ready for approval; plan gate is pending and after approval or openlogos next --auto, proceed to delta-writing. ${plan_state:+Plan state: $plan_state. }Tasks execution 0/N means execution has not started, not planning failure. Do not modify source code or logos/resources/** directly.${ui_exc} $confirm"
      ;;
    delta-writing|implementing|in-progress)
      echo "$base Current proposal step: delta-writing. Typical work at this step: produce delta files under logos/changes/$active/deltas/** and check off [delta] tasks in logos/changes/$active/tasks.md; spec changes reach logos/resources/** through deltas plus openlogos merge. $scope_note $confirm"
      ;;
    ready-to-merge)
      echo "$base Current proposal step: ready-to-merge. The [delta] tasks are complete; the next step is merge, which requires the user to explicitly authorize: openlogos merge $active. $scope_note $confirm"
      ;;
    merge-generated)
      echo "$base Current proposal step: merge-generated. Follow logos/changes/$active/MERGE_PROMPT.md to merge specs, then write logos/changes/$active/SPEC_MERGED when done. $confirm"
      ;;
    coding|ready-to-verify|verify-failed)
      echo "$base Current proposal step: $step. Typical work at this step: implement the [code] slices listed in logos/changes/$active/tasks.md, including source code, tests, reporter, and required snapshots; update tasks.md when complete. $scope_note $confirm"
      ;;
    verify-passed|deploy-done|smoke-passed)
      echo "$base Current proposal step: $step. Verification/delivery is complete for this step; ask the user to explicitly authorize openlogos archive $active when appropriate. $confirm"
      ;;
    ready-to-deploy)
      echo "$base Current proposal step: ready-to-deploy. Deployment requires explicit human authorization before any deployment action. $confirm"
      ;;
    ready-to-smoke|smoke-failed)
      echo "$base Current proposal step: $step. Smoke requires explicit human authorization before running openlogos smoke. $confirm"
      ;;
    *)
      echo "$base Current proposal step is unknown. Run openlogos status or openlogos next to confirm the current proposal step. $scope_note $confirm"
      ;;
  esac
}

# Detect guard file for active lifecycle
GUARD_FILE="logos/.openlogos-guard"
GUARD_STATUS=""
ACTIVE_CHANGE="$STATUS_ACTIVE_CHANGE"
PROPOSAL_STEP="$STATUS_PROPOSAL_STEP"

if [ "$LIFECYCLE" = "launched" ] && [ -z "$ACTIVE_CHANGE" ] && [ -f "$GUARD_FILE" ]; then
  if [ "$NODE_OK" -eq 1 ]; then
    ACTIVE_CHANGE=$(node -e "const d=JSON.parse(require('fs').readFileSync('$GUARD_FILE','utf-8')); console.log(d.activeChange||'')" 2>/dev/null || echo "")
  fi
  if [ "$NODE_OK" -ne 1 ] && has_python; then
    ACTIVE_CHANGE=$(run_python -c "import json; d=json.load(open('$GUARD_FILE')); print(d.get('activeChange',''))" 2>/dev/null || echo "")
  fi
fi

# Build change management text
if [ "$LIFECYCLE" = "launched" ]; then
  if [ -n "$ACTIVE_CHANGE" ]; then
    GUARD_STATUS="🔓 Active change: $ACTIVE_CHANGE — modify files within the scope of this proposal only."
    CHANGE_MGMT=$(change_management_message "$ACTIVE_CHANGE" "${PROPOSAL_STEP:-}" "${STATUS_PLAN_STATE_SUMMARY:-}")
  else
    GUARD_STATUS="⛔ NO active change proposal. You MUST run openlogos change <slug> before modifying any code."
    CHANGE_MGMT="Change Management: ACTIVE — ⛔ NO guard file found. Before modifying ANY source code, you MUST first run openlogos change <slug> to create a change proposal. Direct code changes without a proposal are FORBIDDEN."
  fi
else
  CHANGE_MGMT="Change Management: Initial development — follow Phase progression, no change proposals needed."
  if [ "$PHASE" = "All phases complete" ]; then
    CHANGE_MGMT="$CHANGE_MGMT Run openlogos launch to activate change management."
  fi
fi

# Build status line for systemMessage (user-visible, keep short)
if [ -n "$GUARD_STATUS" ]; then
  STATUS_LINE="📊 OpenLogos: $PHASE | $GUARD_STATUS"
elif [ -n "$SKILL" ]; then
  STATUS_LINE="📊 OpenLogos: $PHASE → use $SKILL skill"
else
  STATUS_LINE="📊 OpenLogos: $PHASE"
fi

# proposal-ui-ux-first 切片3：前置能力门 capability surface（读 logos/.session-capabilities.json）。
# 缺失=降级模式（不注入 capabilities 段）；仅用于 plan-exit 前模式选择，plan-exit 后强制语义以 PLAN_APPROVED 为准。
CAPABILITIES=""
CAP_FILE="logos/.session-capabilities.json"
if [ -f "$CAP_FILE" ]; then
  UI_RENDER=""
  if [ "$NODE_OK" -eq 1 ]; then
    UI_RENDER=$(node -e "const d=JSON.parse(require('fs').readFileSync('$CAP_FILE','utf-8'));console.log(d.ui_prototype_render===true?'true':'')" 2>/dev/null || echo "")
  fi
  if [ "$NODE_OK" -ne 1 ] && has_python; then
    UI_RENDER=$(run_python -c "import json;print('true' if json.load(open('$CAP_FILE')).get('ui_prototype_render') is True else '')" 2>/dev/null || echo "")
  fi
  if [ "$UI_RENDER" = "true" ]; then
    CAPABILITIES="Capabilities: ui_prototype_render=true (rendered UI confirmation available; capability 仅用于 plan-exit 前模式选择——就绪→渲染确认模式，plan-exit 后以 PLAN_APPROVED 为准)."
  fi
fi

# guard-versioned-content-scope：SessionStart 调用事后检查引擎 `check --session-start`（与本脚本同目录：托管副本
# .claude/openlogos/bin/guard-post-check.cjs，或插件 bin/），接管未关闭执行记录继续对比、清理墓碑，
# 并把待报告项并入注入上下文。只在 hook（JSON）模式运行；引擎缺失、node 不可用或失败时静默跳过。
GUARD_PENDING=""
if [ "$MODE" = "json" ] && [ "$NODE_OK" -eq 1 ]; then
  _GUARD_ENGINE="$(cd "$(dirname "${BASH_SOURCE[0]}")" 2>/dev/null && pwd)/guard-post-check.cjs"
  if [ -f "$_GUARD_ENGINE" ]; then
    GUARD_PENDING="$(printf '%s' "$OPENLOGOS_HOOK_INPUT" | node "$_GUARD_ENGINE" check --session-start 2>/dev/null || true)"
  fi
fi

# module-lifecycle-guard：混合生命周期项目（同时有 launched 与 initial 模块）按模块追加提示段（spec/pretooluse-guard.md
# 「SessionStart 提示」）。只提供指导，授权以每次 PreToolUse 重读磁盘为准；全部 initial / 全部 launched 项目不输出任何内容。
module_lifecycle_context() {
  [ "${NODE_OK:-0}" -eq 1 ] || return 0
  [ -f "logos/logos-project.yaml" ] || return 0
  local _mlc_js
  _mlc_js=$(mktemp "${TMPDIR:-/tmp}/openlogos_mlc.XXXXXX") || return 0
  cat > "$_mlc_js" << 'JSEOF'
const fs = require('fs');
const zh = process.argv[2] === 'zh';
let text;
try { text = fs.readFileSync('logos/logos-project.yaml', 'utf8'); } catch { process.exit(0); }
const unq = (raw) => {
  const v = raw.trim();
  if (v[0] === '"' || v[0] === "'") { const j = v.indexOf(v[0], 1); return j > 0 ? v.slice(1, j) : ''; }
  const k = v.indexOf(' #');
  return (k >= 0 ? v.slice(0, k) : v).trim();
};
const mods = [];
let inModules = false; let cur = null; let inPaths = false; let dash = -1;
for (const raw of text.split('\n')) {
  const line = raw.replace(/\r$/, '');
  if (/^\s*(#|$)/.test(line)) continue;
  const top = /^([A-Za-z_][\w-]*)\s*:/.exec(line);
  if (top) { inModules = top[1] === 'modules'; cur = null; inPaths = false; dash = -1; continue; }
  if (!inModules) continue;
  const body = line.replace(/^ +/, '');
  const indent = line.length - body.length;
  const item = /^-(?:\s+(.*))?$/.exec(body);
  let kvText = body;
  if (item) {
    if (inPaths && indent > dash) { const v = unq(item[1] || ''); if (v) cur.paths.push(v); continue; }
    if (dash < 0 || indent === dash) {
      dash = indent; inPaths = false; cur = { id: '', lifecycle: '', paths: [] }; mods.push(cur);
      if (!(item[1] || '').trim()) continue;
      kvText = item[1];
    } else continue;
  }
  const kv = /^([A-Za-z_][\w-]*)\s*:(.*)$/.exec(kvText);
  if (!kv || !cur) continue;
  inPaths = false;
  const value = kv[2].trim();
  if (kv[1] === 'id') cur.id = unq(value);
  else if (kv[1] === 'lifecycle') cur.lifecycle = unq(value);
  else if (kv[1] === 'paths') {
    if (value === '' || value[0] === '#') inPaths = true;
    else if (value[0] === '[') { const e = value.indexOf(']'); if (e > 0) cur.paths = value.slice(1, e).split(',').map(unq).filter(Boolean); }
  }
}
const initial = mods.filter(m => m.id && m.lifecycle === 'initial');
const launched = mods.filter(m => m.id && m.lifecycle === 'launched');
if (initial.length === 0 || launched.length === 0) process.exit(0);
const valid = (p) => p && !p.startsWith('/') && !p.split('/').includes('..');
const out = [zh
  ? 'Module Lifecycle（混合生命周期，按模块判定；上方变更管理规则只约束 launched 模块文件、共享配置与未归属文件）：'
  : 'Module Lifecycle (mixed; the change-management rule above applies only to launched module files, shared configuration and unattributed files):'];
for (const m of initial) {
  const paths = m.paths.filter(valid);
  out.push(zh
    ? `- ${m.id}: initial — 按 Phase 推进，无需变更提案；豁免范围：logos/resources/** 下 ${m.id}- 前缀规格；${paths.length ? `代码 paths: ${paths.join(', ')}` : '代码仍需提案（未声明 paths）'}`
    : `- ${m.id}: initial — follow the Phase progression, no change proposal needed; exempt: specs prefixed ${m.id}- under logos/resources/**; ${paths.length ? `code paths: ${paths.join(', ')}` : 'code still requires a proposal (no paths declared)'}`);
}
for (const m of launched) out.push(zh ? `- ${m.id}: launched — 变更须先立案` : `- ${m.id}: launched — changes require a proposal first`);
process.stdout.write(out.join('\n'));
JSEOF
  node "$_mlc_js" "${LOCALE:-en}" 2>/dev/null || true
  rm -f "$_mlc_js"
}
MODULE_LIFECYCLE="$(module_lifecycle_context)"

# Build full context for additionalContext (Claude-visible)
CONTEXT="=== OpenLogos Project Context ===
Project: $PROJECT_NAME
Locale: $LOCALE
Lifecycle: $LIFECYCLE
Current Phase: $PHASE"

if [ -n "$SKILL" ]; then
  CONTEXT="$CONTEXT
Suggested Skill: $SKILL ($SKILL_DESC)"
fi

CONTEXT="$CONTEXT
$LANG_POLICY${CAPABILITIES:+
$CAPABILITIES}
$CHANGE_MGMT${MODULE_LIFECYCLE:+
$MODULE_LIFECYCLE}${GUARD_PENDING:+
$GUARD_PENDING}
=== End OpenLogos Context ==="

if [ "$MODE" = "json" ]; then
  # Escape special characters for JSON
  CONTEXT_ESCAPED=""
  if [ "$NODE_OK" -eq 1 ]; then
    CONTEXT_ESCAPED=$(printf '%s' "$CONTEXT" | node -e "console.log(JSON.stringify(require('fs').readFileSync(0,'utf-8')))" 2>/dev/null || echo "")
  fi
  if [ -z "$CONTEXT_ESCAPED" ] && has_python; then
    CONTEXT_ESCAPED=$(printf '%s' "$CONTEXT" | run_python -c "import sys,json; print(json.dumps(sys.stdin.buffer.read().decode('utf-8')))" 2>/dev/null || echo "")
  fi
  [ -n "$CONTEXT_ESCAPED" ] || CONTEXT_ESCAPED='""'

  cat <<ENDJSON
{
  "systemMessage": "$STATUS_LINE",
  "hookSpecificOutput": {
    "hookEventName": "SessionStart",
    "additionalContext": $CONTEXT_ESCAPED
  }
}
ENDJSON
else
  echo ""
  echo "$CONTEXT"
  echo ""
fi
