KB-2E3A

RS3C-02 — Source Mirror and Hash Record — 2026-06-21

16 min read Revision 1
rs3csource-mirrorsha256registrarcatalog-sync2026-06-21

RS3C-02 — Source Mirror and Hash Record — 2026-06-21

Macro: RS3C (Mục tiêu A, Method 2 mirror of the Method-3 recovered source) Deliverable: 02 of 13 · Faithful line-level source mirror + hash record Date: 2026-06-21 · read-only · 0 mutations

This file admits a faithful, line-level KB mirror of the two recovered source files, each stamped with its sha256 and proven byte-identical to the currently-deployed OPERATIONAL VPS file (see RS3C-01 §4). Behavior reconstruction in RS3C-03/04 cites line numbers against this mirror.

Security note: the registrar embeds infra identifiers verbatim (a VPS IP and an SSH key path). They are reproduced faithfully because fidelity is the purpose of a source mirror; the hardcoded-credential exposure is itself flagged as a finding in RS3C-03 §3.

1. Hash record

Source file Origin path (operator workstation) Deployed VPS path Size Lines sha256 Deployed status KB mirror Read status
registrar /Users/nmhuyen/tmp/fix21-docs/dot-dot-register /opt/incomex/dot/bin/dot-dot-register 5813 B 193 31d5cf1508c7950cc30a2a6abb46d7cee868e1cbf951a6095ff0aee7ba48583f OPERATIONAL this file §2 FULL_READ
catalog-sync /Users/nmhuyen/Documents/Manual Deploy/web-test/dot/bin/dot-catalog-sync /opt/incomex/dot/bin/dot-catalog-sync 7134 B 264 7dd84cda6d1e220fc7f54419bf40ec9ad05a952b6a402360df73f0af3fa355cd OPERATIONAL this file §3 FULL_READ

Provenance notes:

  • registrar: recovered from a non-git working folder …/tmp/fix21-docs/; fidelity is established not by git lineage but by exact sha256 match to the live OPERATIONAL snapshot row (id 6022). Internal header declares VERSION 1.0.0, v1.0.0 (2026-03-31).
  • catalog-sync: recovered from git repo …/web-test (remote github.com/Huyen1974/web-test.git, branch main, HEAD 5b9eb23 2026-05-16), file unmodified vs index; sha256 matches the live OPERATIONAL snapshot row (id 5963, mapped DOT-015). Internal header declares VERSION 1.0.0.
  • The web-test copy of the registrar (9c594efd…) matches only the deployed backup dot-dot-register.bak-s164c (NOISE_BACKUP) and was rejected as the operational source.

2. Mirror — dot-dot-register (registrar, sha256 31d5cf15…, 193 lines)

#!/usr/bin/env bash
# =============================================================================
# dot-dot-register — Auto-register new DOT files (Cấp B, on-deploy)
# =============================================================================
# VERSION: 1.0.0
# CHANGELOG:
#   v1.0.0 (2026-03-31): Scan bin/dot-* → register missing in dot_tools
#
# Usage:
#   dot-dot-register [--cloud|--local] [--dry-run]
# =============================================================================

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/../config/environment.sh"

VERSION="1.0.0"

VPS_HOST="38.242.240.89"
VPS_KEY="${HOME}/.ssh/contabo_vps"
PG_CONTAINER="${PG_CONTAINER:-postgres}"
PG_USER="${PG_USER:-directus}"
PG_DB="${PG_DB:-directus}"
DOT_BIN_DIR="/opt/incomex/dot/bin"

DRY_RUN=false

log_info() { echo "[INFO] $1"; }
log_ok()   { echo "[OK]   $1"; }
log_warn() { echo "[WARN] $1"; }
log_err()  { echo "[ERR]  $1" >&2; }

show_help() {
  cat << EOF
dot-dot-register v${VERSION} — Auto-register DOT files (Cấp B)

Scans ${DOT_BIN_DIR}/dot-* on VPS, registers untracked files in dot_tools.

Usage:
  dot-dot-register [--cloud|--local] [--dry-run]
EOF
  show_environment_help
}

run_pg() {
  local SQL="$1"
  if command -v docker &>/dev/null && docker ps --format '{{.Names}}' 2>/dev/null | grep -q "^${PG_CONTAINER}$"; then
    docker exec -i ${PG_CONTAINER} psql -U ${PG_USER} -d ${PG_DB} -t -A <<< "$SQL" 2>/dev/null
  else
    ssh -i "$VPS_KEY" -o ConnectTimeout=10 -o StrictHostKeyChecking=no "root@${VPS_HOST}" \
      "docker exec -i ${PG_CONTAINER} psql -U ${PG_USER} -d ${PG_DB} -t -A" <<< "$SQL" 2>/dev/null
  fi
}

run_remote() {
  local CMD="$1"
  if command -v docker &>/dev/null && docker ps --format '{{.Names}}' 2>/dev/null | grep -q "^${PG_CONTAINER}$"; then
    eval "$CMD"
  else
    ssh -i "$VPS_KEY" -o ConnectTimeout=10 -o StrictHostKeyChecking=no "root@${VPS_HOST}" "$CMD" 2>/dev/null
  fi
}

classify_tier() {
  local NAME="$1"
  case "$NAME" in
    *-health*|*-scan*|*-report*|*-audit*|*-check*|*-verify*|*-integrity*|*-coverage*)
      echo "A" ;;
    *)
      echo "B" ;;
  esac
}

classify_domain() {
  local NAME="$1"
  case "$NAME" in
    *-schema-*|*-collection-*|*-field-*)   echo "collection" ;;
    *-knowledge-*|*-content-*)             echo "knowledge" ;;
    *-auth*|*-permission*|*-token*)        echo "auth" ;;
    *-flow-*|*-hook-*)                     echo "flow" ;;
    *-registry-*|*-catalog-*)              echo "registry" ;;
    *-apr-*|*-approval-*)                  echo "apr" ;;
    *-dot-*)                               echo "dot" ;;
    *-agent-*|*-ai-*|*-mcp-*)             echo "agent" ;;
    *-backup-*|*-env-*|*-ops-*)            echo "ops" ;;
    *-species-*|*-label-*|*-taxonomy-*)    echo "taxonomy" ;;
    *-birth-*|*-seed-*)                    echo "lifecycle" ;;
    *-sync-*|*-migration-*)               echo "sync" ;;
    *)                                     echo "general" ;;
  esac
}

main() {
  for arg in "$@"; do
    case "$arg" in
      --help|-h) show_help; exit 0 ;;
      --dry-run) DRY_RUN=true ;;
    esac
  done

  init_environment "$@"
  local BASE_URL="$DIRECTUS_URL"

  echo "========================================="
  echo "DOT Tool: Register v${VERSION}"
  echo "Cấp B — on-deploy"
  [[ "$DRY_RUN" == true ]] && echo "MODE: DRY RUN"
  echo "========================================="
  print_environment_banner "$@"

  if [[ -z "${DOT_TOKEN:-}" ]]; then
    source "${SCRIPT_DIR}/dot-auth" "$@"
  fi
  if [[ -z "${DOT_TOKEN:-}" ]]; then
    log_err "Authentication failed"; exit 1
  fi

  # Get disk files
  local DISK_FILES
  DISK_FILES=$(run_remote "ls -1 ${DOT_BIN_DIR}/dot-* 2>/dev/null" || true)
  local DISK_COUNT
  DISK_COUNT=$(echo "$DISK_FILES" | grep -c '.' || true)
  log_info "Found ${DISK_COUNT} dot-* files on disk"

  # Get registered file_paths
  local REGISTERED
  REGISTERED=$(run_pg "SELECT file_path FROM dot_tools WHERE file_path IS NOT NULL;")

  local NEW=0 SKIPPED=0
  while IFS= read -r filepath; do
    [[ -z "$filepath" ]] && continue

    # Check if already registered
    if echo "$REGISTERED" | grep -qF "$filepath"; then
      SKIPPED=$((SKIPPED + 1))
      continue
    fi

    local BASENAME
    BASENAME=$(basename "$filepath")
    local CODE
    CODE=$(echo "$BASENAME" | tr '[:lower:]' '[:upper:]' | tr '-' '_')
    local TIER
    TIER=$(classify_tier "$BASENAME")
    local DOMAIN
    DOMAIN=$(classify_domain "$BASENAME")
    local PAIRED=""
    if [[ "$TIER" == "B" ]]; then
      PAIRED="DOT-HEALTH-DOT"
    fi

    log_info "NEW: $BASENAME (tier=$TIER, domain=$DOMAIN)"

    if [[ "$DRY_RUN" == false ]]; then
      curl -sS --globoff -k -X POST \
        "${BASE_URL}/items/dot_tools" \
        -H "Authorization: Bearer $DOT_TOKEN" \
        -H "Content-Type: application/json" \
        -d "$(jq -n \
          --arg code "$CODE" \
          --arg name "$BASENAME" \
          --arg fp "$filepath" \
          --arg tier "$TIER" \
          --arg domain "$DOMAIN" \
          --arg paired "$PAIRED" \
          '{
            code: $code,
            name: $name,
            file_path: $fp,
            tier: $tier,
            domain: $domain,
            status: "active"
          } + (if $paired != "" then {paired_dot: $paired} else {} end)')" > /dev/null 2>&1

      if [[ $? -eq 0 ]]; then
        log_ok "  Registered: $CODE"
      else
        log_warn "  Failed to register: $CODE"
      fi
    fi

    NEW=$((NEW + 1))
  done <<< "$DISK_FILES"

  echo ""
  echo "========================================="
  log_ok "Done: ${NEW} new, ${SKIPPED} already registered"
  [[ "$DRY_RUN" == true ]] && log_info "(dry-run — no changes made)"
  echo "========================================="
}

main "$@"

3. Mirror — dot-catalog-sync (sha256 7dd84cda…, 264 lines)

#!/usr/bin/env bash
# =============================================================================
# dot-catalog-sync — Scan external sources and report catalog discrepancies
# =============================================================================
# CHECKED-NO-DUPLICATE: [searched dot/bin/dot-catalog* — no existing tool]
# VERSION: 1.0.0
#
# Scans Model B sources (filesystem, APIs) and compares with meta_catalog.
# Reports missing/orphaned items. Updates record_count in meta_catalog.
#
# Usage:
#   dot-catalog-sync --type=dot_tools [--cloud]
#   dot-catalog-sync --type=pages [--cloud]
#   dot-catalog-sync --type=collections [--cloud]
#   dot-catalog-sync --all [--cloud]
# =============================================================================

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DOT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
PROJECT_ROOT="$(cd "$DOT_ROOT/.." && pwd)"

source "${SCRIPT_DIR}/../config/environment.sh"

VERSION="1.0.0"

log_info() { echo "[INFO] $1"; }
log_ok()   { echo "[OK]   $1"; }
log_warn() { echo "[WARN] $1"; }
log_err()  { echo "[ERR]  $1" >&2; }

api_request() {
  local method="$1" url="$2" data="${3-}"
  if [[ -n "${data-}" ]]; then
    curl -sS --globoff -X "$method" "$url" \
      -H "Authorization: Bearer $DOT_TOKEN" \
      -H "Content-Type: application/json" \
      -d "$data" -w "\n%{http_code}"
  else
    curl -sS --globoff -X "$method" "$url" \
      -H "Authorization: Bearer $DOT_TOKEN" \
      -w "\n%{http_code}"
  fi
}

update_record_count() {
  local cat_code="$1" count="$2"
  local resp code

  # Find the meta_catalog item by code
  resp=$(api_request GET "${BASE_URL}/items/meta_catalog?filter[code][_eq]=${cat_code}&fields=id")
  local body="${resp%$'\n'*}"
  code="${resp##*$'\n'}"

  if [[ "$code" != "200" ]]; then
    log_warn "Could not find meta_catalog entry for ${cat_code}"
    return
  fi

  local item_id
  item_id=$(echo "$body" | jq -r '.data[0].id // empty')
  if [[ -z "$item_id" ]]; then
    log_warn "No meta_catalog entry for ${cat_code}"
    return
  fi

  resp=$(api_request PATCH "${BASE_URL}/items/meta_catalog/${item_id}" "{\"record_count\":${count}}")
  code="${resp##*$'\n'}"
  if [[ "$code" == "200" ]]; then
    log_ok "Updated ${cat_code} record_count = ${count}"
  else
    log_warn "Failed to update ${cat_code} record_count"
  fi
}

scan_dot_tools() {
  echo ""
  echo "--- Scanning DOT Tools (CAT-006) ---"

  local tools=()
  while IFS= read -r f; do
    [[ -n "$f" ]] && tools+=("$(basename "$f")")
  done < <(find "${DOT_ROOT}/bin" -name "dot-*" -type f -perm +111 2>/dev/null | sort)

  local count=${#tools[@]}
  log_info "Found ${count} DOT tools in dot/bin/"

  update_record_count "CAT-006" "$count"

  echo ""
  echo "DOT Tools (${count}):"
  if [[ $count -gt 0 ]]; then
    for t in "${tools[@]}"; do
      echo "  - ${t}"
    done
  fi
}

scan_pages() {
  echo ""
  echo "--- Scanning Pages (CAT-007) ---"

  local pages=()
  while IFS= read -r f; do
    [[ -n "$f" ]] || continue
    local rel
    rel="${f#${PROJECT_ROOT}/web/pages/}"
    pages+=("$rel")
  done < <(find "${PROJECT_ROOT}/web/pages" -name "*.vue" -type f 2>/dev/null | sort)

  local count=${#pages[@]}
  log_info "Found ${count} Vue pages in web/pages/"

  update_record_count "CAT-007" "$count"

  echo ""
  echo "Pages (${count}):"
  if [[ $count -gt 0 ]]; then
    for p in "${pages[@]}"; do
      echo "  - ${p}"
    done
  fi
}

scan_collections() {
  echo ""
  echo "--- Scanning Collections (CAT-008) ---"

  local resp body code
  resp=$(api_request GET "${BASE_URL}/collections?limit=-1")
  body="${resp%$'\n'*}"
  code="${resp##*$'\n'}"

  if [[ "$code" != "200" ]]; then
    log_err "Failed to fetch collections (HTTP $code)"
    return
  fi

  local count
  count=$(echo "$body" | jq '[.data[] | select(.collection | startswith("directus_") | not)] | length')
  log_info "Found ${count} user collections in Directus"

  update_record_count "CAT-008" "$count"

  echo ""
  echo "Collections (${count}):"
  echo "$body" | jq -r '.data[] | select(.collection | startswith("directus_") | not) | "  - \(.collection)"' | sort | head -50
}

update_model_a_counts() {
  echo ""
  echo "--- Updating Model A record counts ---"

  local entries='[
    {"code":"CAT-000","collection":"meta_catalog"},
    {"code":"CAT-001","collection":"table_registry"},
    {"code":"CAT-003","collection":"workflows"},
    {"code":"CAT-004","collection":"workflow_steps"},
    {"code":"CAT-005","collection":"workflow_change_requests"},
    {"code":"CAT-009","collection":"tasks"}
  ]'

  local len
  len=$(echo "$entries" | jq 'length')

  for i in $(seq 0 $((len - 1))); do
    local cat_code collection
    cat_code=$(echo "$entries" | jq -r ".[$i].code")
    collection=$(echo "$entries" | jq -r ".[$i].collection")

    local resp body code count
    resp=$(api_request GET "${BASE_URL}/items/${collection}?aggregate[countDistinct]=id")
    body="${resp%$'\n'*}"
    code="${resp##*$'\n'}"

    if [[ "$code" == "200" ]]; then
      count=$(echo "$body" | jq -r '.data[0].countDistinct.id // 0')
      update_record_count "$cat_code" "$count"
    else
      log_warn "Could not count ${collection} (HTTP $code)"
    fi
  done
}

show_help() {
  cat << EOF
dot-catalog-sync v${VERSION} — Scan and report catalog discrepancies

Usage:
  dot-catalog-sync --type=dot_tools [--cloud]   Scan DOT tools
  dot-catalog-sync --type=pages [--cloud]        Scan Vue pages
  dot-catalog-sync --type=collections [--cloud]  Scan Directus collections
  dot-catalog-sync --all [--cloud]               Scan everything

Options:
  --local     Use local Directus
  --cloud     Use cloud Directus (default)
  --help, -h  Show help

EOF
  show_environment_help
}

main() {
  local SCAN_TYPE="" SCAN_ALL=false

  for arg in "$@"; do
    case "$arg" in
      --type=*) SCAN_TYPE="${arg#--type=}" ;;
      --all) SCAN_ALL=true ;;
      --help|-h) show_help; exit 0 ;;
    esac
  done

  if [[ -z "$SCAN_TYPE" && "$SCAN_ALL" == "false" ]]; then
    log_err "Specify --type=<dot_tools|pages|collections> or --all"
    exit 1
  fi

  init_environment "$@"
  BASE_URL="$DIRECTUS_URL"

  echo "========================================="
  echo "DOT Tool: Catalog Sync v${VERSION}"
  echo "========================================="
  print_environment_banner "$@"

  # Auth
  if [[ -z "${DOT_TOKEN:-}" ]]; then
    local dot_auth="${SCRIPT_DIR}/dot-auth"
    if [[ -f "$dot_auth" ]]; then
      source "$dot_auth" "$@"
    fi
  fi

  if [[ -z "${DOT_TOKEN:-}" ]]; then
    log_err "Authentication failed"
    exit 1
  fi

  if [[ "$SCAN_ALL" == "true" || "$SCAN_TYPE" == "dot_tools" ]]; then
    scan_dot_tools
  fi

  if [[ "$SCAN_ALL" == "true" || "$SCAN_TYPE" == "pages" ]]; then
    scan_pages
  fi

  if [[ "$SCAN_ALL" == "true" || "$SCAN_TYPE" == "collections" ]]; then
    scan_collections
  fi

  if [[ "$SCAN_ALL" == "true" ]]; then
    update_model_a_counts
  fi

  echo ""
  echo "========================================="
  echo "DOT Tool: Catalog Sync - COMPLETE"
  echo "========================================="
}

main "$@"

4. Status

  • Both mirrors are byte-identical to the deployed OPERATIONAL VPS files (RS3C-01 §4).
  • SOURCE_MIRROR_HASH_MATCH for both files; no SOURCE_MIRROR_HASH_MISMATCH.
  • These mirrors are the citable source-of-record for RS3C-03/04 line references.