Initial project source

这个提交包含在:
apple
2026-11-20 15:32:57 +08:00
当前提交 fb47c07f7c
共修改 8405 个文件,包含 806907 行新增和 0 行删除
+56
查看文件
@@ -0,0 +1,56 @@
#!/usr/bin/env python3
"""Bounded syntax/secret validation; never scans history or invokes runtime."""
import ast
import json
import os
from pathlib import Path
import re
import subprocess
import sys
ROOT = Path(__file__).resolve().parents[2]
SHAPES = re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{50,}|xox[baprs]-[A-Za-z0-9-]{20,}")
def main(paths):
if not paths:
raise ValueError("provide explicit files")
secrets = []
env = ROOT / "script/datagov/.env.datagov"
if env.is_file():
for line in env.read_text().splitlines():
key, sep, value = line.partition("=")
if sep and re.search(r"PASSWORD|TOKEN|JWT_SECRET|IDENTITY_(KEY|VALUE)", key) and len(value.strip("'\"")) >= 12:
secrets.append(value.strip("'\""))
errors = []
for name in dict.fromkeys(paths):
p = ROOT / name
if p.is_symlink() or not p.resolve().is_relative_to(ROOT) or not p.is_file():
errors.append((name, "not a regular project file")); continue
if ".local-backups" in p.parts or p.name == ".env.datagov":
errors.append((name, "private file is not reviewable input")); continue
try:
data = p.read_text()
if SHAPES.search(data) or any(value in data for value in secrets):
errors.append((name, "secret detected; contents withheld")); continue
if p.suffix == ".py":
ast.parse(data, filename=name)
elif p.suffix == ".json":
json.loads(data)
elif p.suffix in {".sh", ".rb"}:
command = ["bash", "-n", str(p)] if p.suffix == ".sh" else ["ruby", "-c", str(p)]
if subprocess.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode:
errors.append((name, "syntax error"))
except (UnicodeError, SyntaxError, ValueError):
errors.append((name, "invalid syntax or text encoding"))
for name, reason in errors:
print(f"{name}: {reason}", file=sys.stderr)
if errors:
return 1
print(f"Explicit file checks passed: {len(set(paths))} files")
return 0
if __name__ == "__main__":
try:
sys.exit(main(sys.argv[1:]))
except ValueError as exc:
print(str(exc), file=sys.stderr)
sys.exit(2)
+63
查看文件
@@ -0,0 +1,63 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
cd "$ROOT"
usage() {
cat <<'HELP'
Usage: check.sh MODE [scope]
--backend MODULES [TEST] Maven tests; optional Surefire class/method pattern
--backend-build MODULES Maven package (including tests), no clean/install
--frontend [PATH...] Lint selected paths relative to aixun-ui, or all src
--frontend-build Frontend production build
--files PATH... Syntax and secret checks for explicit text files
--full Explicit Maven verify + frontend lint/build; no reinstall
--runtime [SERVICE] Target config check; omit service for bootstrap preflight
No default full scan. Include downstream consumers when a shared contract changes.
HELP
}
mode="${1:---help}"; [[ $# -eq 0 ]] || shift
case "$mode" in
--backend|--backend-build)
[[ $# -ge 1 && $# -le 2 && "$1" != -* ]] || { usage >&2; exit 2; }
modules="$1"; shift
goal=test; [[ "$mode" != --backend-build ]] || goal=package
extra=()
if [[ $# -eq 1 ]]; then
[[ "$mode" == --backend && -n "$1" && "$1" != -* ]] || { usage >&2; exit 2; }
extra=("-Dtest=$1" -Dsurefire.failIfNoSpecifiedTests=false)
# Dependency modules may have no matching test. Require a real positive
# Surefire count somewhere in this invocation, so typos cannot pass green.
./mvnw -B -pl "$modules" -am "$goal" "${extra[@]}" | awk '
/Tests run: [1-9][0-9]*/ { ran = 1 }
{ print }
END { if (!ran) { print "No executed tests observed for the selected pattern; not PASS." > "/dev/stderr"; exit 2 } }
'
exit
fi
exec ./mvnw -B -pl "$modules" -am "$goal" ${extra[@]+"${extra[@]}"}
;;
--frontend|--frontend-build)
[[ "$mode" == --frontend || $# -eq 0 ]] || { usage >&2; exit 2; }
source script/toolchain/bootstrap-node.sh
[[ -d aixun-ui/node_modules ]] || { echo 'Missing dependencies: run pnpm --dir aixun-ui install --frozen-lockfile once.' >&2; exit 2; }
if [[ "$mode" == --frontend ]]; then
if [[ $# -eq 0 ]]; then pnpm --dir aixun-ui lint; else pnpm --dir aixun-ui exec oxlint -- "$@"; fi
else
pnpm --dir aixun-ui build:prod
fi
;;
--files) exec python3 script/quality/check-files.py "$@" ;;
--full)
[[ $# -eq 0 ]] || { usage >&2; exit 2; }
./mvnw -B verify
"$0" --frontend
"$0" --frontend-build
;;
--runtime)
[[ $# -le 1 ]] || { usage >&2; exit 2; }
if [[ $# -eq 1 ]]; then exec ./script/datagov/deploy.sh --check-config "$1"; fi
exec ./script/datagov/preflight.sh
;;
--help|-h) usage ;;
*) usage >&2; exit 2 ;;
esac
+148
查看文件
@@ -0,0 +1,148 @@
#!/usr/bin/env bash
set -euo pipefail
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly PROJECT_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"
readonly ENV_FILE="${AIXUN_DATAGOV_ENV_FILE:-${PROJECT_ROOT}/script/datagov/.env.datagov}"
readonly RUNTIME_MODE="${1:-}"
readonly LOCAL_BACKUP_ROOT="${PROJECT_ROOT}/.local-backups"
fail() {
echo "Secret scan failed: $*" >&2
exit 1
}
[[ -z "${RUNTIME_MODE}" || "${RUNTIME_MODE}" == "--runtime" ]] || fail "usage: scan-secrets.sh [--runtime]"
command -v rg >/dev/null 2>&1 && [[ -x "$(command -v rg)" ]] || fail "required executable rg is unavailable"
verify_local_backup_metadata() {
local match status
[[ -e "${LOCAL_BACKUP_ROOT}" || -L "${LOCAL_BACKUP_ROOT}" ]] || return 0
[[ ! -L "${LOCAL_BACKUP_ROOT}" ]] || fail "local backup root must not be a symlink"
[[ -d "${LOCAL_BACKUP_ROOT}" ]] || fail "local backup root must be a directory"
if match="$(find "${LOCAL_BACKUP_ROOT}" -type l -print -quit 2>/dev/null)"; then
:
else
status=$?
fail "local backup symlink metadata check failed (exit ${status})"
fi
[[ -z "${match}" ]] || fail "local backup tree must not contain symlinks"
if match="$(
find "${LOCAL_BACKUP_ROOT}" \( -type d -o -type f \) \
\( -perm -004 -o -perm -002 -o -perm -001 -o \
-perm -040 -o -perm -020 -o -perm -010 \) \
-print -quit 2>/dev/null
)"; then
:
else
status=$?
fail "local backup permission metadata check failed (exit ${status})"
fi
[[ -z "${match}" ]] || fail "local backup directories and files must deny group/other access"
}
verify_local_backup_metadata
cd "${PROJECT_ROOT}"
# A search miss is the only nonzero status that can be accepted as a clean scan.
# Never expose raw diagnostics: they may contain a literal secret search value.
rg_matches() {
local status
if rg "$@" >/dev/null 2>&1; then
return 0
else
status=$?
fi
[[ "${status}" -eq 1 ]] && return 1
fail "rg execution failed (exit ${status})"
}
if workspace_sensitive_files="$(
find "${PROJECT_ROOT}" \
-path "${LOCAL_BACKUP_ROOT}" -prune -o \
-type f \
\( -name '.env' -o -name '.env.*' -o -name '*.pem' -o -name '*.key' -o -name '*.p12' -o -name '*.jks' -o -name '*.keystore' \) \
! -path "${PROJECT_ROOT}/script/datagov/.env.datagov" \
! -path "${PROJECT_ROOT}/script/datagov/runtime/*" \
! -path '*/target/*' \
! -path '*/node_modules/*' \
-print 2>/dev/null | sed "s#^${PROJECT_ROOT}/##" 2>/dev/null | {
if rg -v '(^|/)\.env\.(example|template|development|production|test)$' 2>/dev/null; then
:
else
status=$?
[[ "${status}" -eq 1 ]] || exit "${status}"
fi
}
)"; then
:
else
fail "secret-bearing filename enumeration or filtering failed"
fi
[[ -z "${workspace_sensitive_files}" ]] || fail "reviewable secret-bearing filename detected: ${workspace_sensitive_files}"
readonly SECRET_SHAPES=(
'-----BEGIN (RSA |EC |OPENSSH )?PRIVATE KEY-----'
'AKIA[0-9A-Z]{16}'
'gh[pousr]_[A-Za-z0-9]{30,}'
'github_pat_[A-Za-z0-9_]{50,}'
'xox[baprs]-[A-Za-z0-9-]{20,}'
'AIza[0-9A-Za-z_-]{35}'
'npm_[A-Za-z0-9]{36}'
)
for shape in "${SECRET_SHAPES[@]}"; do
if rg_matches --hidden --no-messages -I -l -e "${shape}" \
-g '!.git/**' -g '!.local-backups/**' -g '!script/datagov/.env.datagov' -g '!script/datagov/runtime/**' \
-g '!**/target/**' -g '!aixun-ui/node_modules/**' . >/dev/null; then
fail "high-confidence live-token/private-key shape detected"
fi
done
secret_count=0
runtime_values=()
if [[ -f "${ENV_FILE}" ]]; then
while IFS= read -r line || [[ -n "${line}" ]]; do
[[ "${line}" =~ ^[A-Z0-9_]+= ]] || continue
name="${line%%=*}"
value="${line#*=}"
case "${name}" in
AIXUN_DATAGOV_DB_PASSWORD|AIXUN_DATAGOV_MYSQL_ROOT_PASSWORD|AIXUN_DATAGOV_REDIS_PASSWORD|AIXUN_DATAGOV_NACOS_PASSWORD|AIXUN_DATAGOV_NACOS_AUTH_TOKEN|AIXUN_DATAGOV_NACOS_IDENTITY_KEY|AIXUN_DATAGOV_NACOS_IDENTITY_VALUE|AIXUN_DATAGOV_JWT_SECRET|AIXUN_DATAGOV_ADMIN_PASSWORD|AIXUN_DATAGOV_UAT_PASSWORD)
[[ ${#value} -ge 12 ]] || fail "local secret ${name} is unexpectedly short"
runtime_values+=("${value}")
if rg_matches --hidden --no-messages -I -l -F \
-g '!.git/**' -g '!.local-backups/**' -g '!script/datagov/.env.datagov' -g '!script/datagov/runtime/**' \
-g '!**/target/**' -g '!aixun-ui/node_modules/**' -- "${value}" . >/dev/null; then
fail "local secret value for ${name} appears in reviewable workspace content"
fi
((secret_count += 1))
;;
esac
done < "${ENV_FILE}"
fi
if [[ "${RUNTIME_MODE}" == "--runtime" ]]; then
[[ ${#runtime_values[@]} -gt 0 ]] || fail "runtime scan requires the local DataGov env file"
temp_dir="$(mktemp -d "${TMPDIR:-/tmp}/aixun-datagov-secret-scan.XXXXXX")"
trap 'rm -rf -- "${temp_dir}"' EXIT
readonly EXPECTED_CONTAINERS=(mysql redis nacos gateway auth system resource integration frontend)
for service_name in "${EXPECTED_CONTAINERS[@]}"; do
container_name="aixun-datagov-${service_name}"
project_label="$(docker inspect "${container_name}" --format '{{index .Config.Labels "com.docker.compose.project"}}' 2>/dev/null)" ||
fail "owned runtime container ${container_name} is unavailable"
owner_label="$(docker inspect "${container_name}" --format '{{index .Config.Labels "com.aixun.project"}}')"
[[ "${project_label}" == "aixun-datagov-local" && "${owner_label}" == "aixun-datagov" ]] ||
fail "refusing to read logs from an unowned container"
docker logs "${container_name}" >"${temp_dir}/${service_name}.log" 2>&1 || fail "owned runtime log input is unavailable"
for value in "${runtime_values[@]}"; do
if rg_matches -F -l -- "${value}" "${temp_dir}/${service_name}.log" >/dev/null; then
fail "known DataGov secret appears in ${container_name} logs"
fi
done
done
fi
echo "Secret scan passed: secret-shaped reviewable files=0, exact local-secret hits=0, local secret references checked=${secret_count}, runtime_mode=${RUNTIME_MODE:---none}."
+54
查看文件
@@ -0,0 +1,54 @@
#!/usr/bin/env python3
"""Read one DataGov session; print timings only, never conversation content."""
import argparse
import json
import math
import pathlib
import sys
def summarize(path, root):
project = None
completed = {}
invalid = 0
for line in path.open(encoding='utf-8'):
try:
row = json.loads(line)
data = row.get('payload', {})
if not isinstance(data, dict):
raise ValueError()
if row.get('type') == 'session_meta':
project = data.get('cwd')
if row.get('type') == 'event_msg' and data.get('type') == 'task_complete':
key = data.get('turn_id')
ms = data.get('duration_ms')
if not isinstance(key, str) or not key or type(ms) not in (int, float) or not math.isfinite(ms) or ms < 0:
raise ValueError()
completed[key] = {'ended_at': row.get('timestamp'), 'duration_seconds': round(ms / 1000, 3)}
except (ValueError, TypeError, AttributeError):
invalid += 1
if project != str(root):
raise ValueError('not a session for this project')
if invalid:
raise ValueError('malformed session records; no partial result emitted')
seconds = sum(item['duration_seconds'] for item in completed.values())
return {'completed_turns': len(completed), 'completed_turn_minutes': round(seconds / 60, 3),
'turns': list(completed.values()),
'limitations': 'Includes tools and waits within completed turns. Excludes unfinished turns and between-turn idle time. Not pure model time or delivery elapsed time; parallel sessions must not be added as elapsed time.'}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('session', type=pathlib.Path, help='one local Codex rollout JSONL file')
args = parser.parse_args()
try:
result = summarize(args.session, pathlib.Path(__file__).resolve().parents[2])
except (OSError, ValueError, UnicodeError):
print('Timing unavailable: unreadable, malformed, or other-project session.', file=sys.stderr)
return 1
print(json.dumps(result, ensure_ascii=False, indent=2, allow_nan=False))
return 0
if __name__ == '__main__':
sys.exit(main())
+167
查看文件
@@ -0,0 +1,167 @@
#!/usr/bin/env ruby
# frozen_string_literal: true
require "pathname"
require "yaml"
require "rexml/document"
require "rexml/xpath"
# 010 grants only these direct Governance test dependencies, not production coupling.
# Resource is not a business unit and remains outside the original four-unit guard.
module BusinessUnitApiDependencies
TEST_TARGETS = %w[dataops dataproduct resource].freeze
MAVEN_NAMESPACE = { "m" => "http://maven.apache.org/POM/4.0.0" }.freeze
def self.test_exception?(source_id, target_id, group_id, scope, direct)
source_id == "governance" && TEST_TARGETS.include?(target_id) &&
group_id == "cn.aixunkeji" && scope == "test" && direct
end
def self.violations(source_id, pom_xml, declared, expected_ids)
document = REXML::Document.new(pom_xml)
raise ArgumentError, "POM DOCTYPE is not allowed" if document.doctype
raise ArgumentError, "invalid Maven project namespace" unless
document.root&.name == "project" && document.root.namespace == MAVEN_NAMESPACE.fetch("m")
direct = REXML::XPath.match(document, "/m:project/m:dependencies/m:dependency", MAVEN_NAMESPACE)
profiles = REXML::XPath.match(document,
"/m:project/m:profiles/m:profile/m:dependencies/m:dependency", MAVEN_NAMESPACE)
(direct.map { |node| [node, true] } + profiles.map { |node| [node, false] }).map do |node, is_direct|
values = %w[groupId artifactId scope].to_h do |field|
elements = REXML::XPath.match(node, "m:#{field}", MAVEN_NAMESPACE)
raise ArgumentError, "duplicate POM dependency field" if elements.length > 1
[field, elements.first&.text&.strip]
end
artifact = values.fetch("artifactId")
target = artifact&.delete_prefix("aixun-api-")
next unless artifact == "aixun-api-#{target}" && (expected_ids - [source_id]).include?(target)
next if test_exception?(source_id, target, values.fetch("groupId"), values.fetch("scope"), is_direct)
next if declared.include?(target)
"#{source_id}->#{target} scope=#{values.fetch('scope') || 'compile(default)'}"
end.compact
end
end
if $PROGRAM_NAME == __FILE__
root = Pathname.new(__dir__).join("../..").realpath
registry_path = root.join("docs/architecture/business-unit-boundaries.yml")
registry = YAML.safe_load(registry_path.read)
units = registry.fetch("units")
expected_ids = %w[integration dataops governance dataproduct]
def fail_check(message)
warn "business-unit verification failed: #{message}"
exit 1
end
contract_paths = %w[m2-golden-chain.yml m5-governance.yml m6-business-extension.yml asset-upgrade.yml].map do |name|
root.join("contracts/datagov", name)
end
contracts = contract_paths.map do |path|
fail_check("missing milestone contract #{path}") unless path.file?
YAML.safe_load(path.read)
end
m2_contract = contracts.first
m6_contract = contracts.fetch(2)
upgrade_contract = contracts.fetch(3)
fail_check("unexpected private Resource API consumers") unless
upgrade_contract.fetch("resourceApiConsumers") == %w[dataproduct governance dataops]
allowed_api_dependencies = {}
contracts.each do |contract|
contract.fetch("crossUnitApiDependencies", {}).each do |source_id, target_ids|
fail_check("unknown contract source unit #{source_id}") unless expected_ids.include?(source_id)
Array(target_ids).each do |target_id|
fail_check("unknown contract target unit #{target_id}") unless expected_ids.include?(target_id)
fail_check("self dependency is forbidden for #{source_id}") if source_id == target_id
allowed_api_dependencies[source_id] ||= []
allowed_api_dependencies[source_id] << target_id unless allowed_api_dependencies[source_id].include?(target_id)
end
end
end
fail_check("registry must contain exactly four units") unless units.map { |unit| unit.fetch("id") } == expected_ids
fail_check("M0 must not enable the business services") unless registry.fetch("runtimeEnabledInM0") == false
fail_check("M0 must not claim external integration") unless registry.fetch("externalComponentsIntegrated") == false
%w[serviceName nacosDataId gatewayPath permissionNamespace packageRoot ownerRole].each do |field|
values = units.map { |unit| unit.fetch(field) }
fail_check("#{field} values must be unique") unless values.uniq.size == units.size
end
units.each do |unit|
id = unit.fetch("id")
module_path = root.join(unit.fetch("module"))
api_path = root.join(unit.fetch("apiModule"))
package_root = unit.fetch("packageRoot")
expected_service = "aixun-#{id}"
fail_check("missing module #{module_path}") unless module_path.directory?
fail_check("missing API module #{api_path}") unless api_path.directory?
fail_check("missing owner file for #{id}") unless module_path.join("OWNERS.md").file?
fail_check("unexpected service name for #{id}") unless unit.fetch("serviceName") == expected_service
fail_check("unexpected Nacos dataId for #{id}") unless unit.fetch("nacosDataId") == "#{expected_service}.yml"
fail_check("unexpected Gateway path for #{id}") unless unit.fetch("gatewayPath") == "/api/#{id}/**"
fail_check("unexpected permission namespace for #{id}") unless unit.fetch("permissionNamespace") == "aixun:#{id}:"
java_files = [module_path, api_path].flat_map { |path| path.glob("src/**/*.java") }
fail_check("#{id} has no Java skeleton") if java_files.empty?
java_files.each do |java_file|
package_line = java_file.each_line.find { |line| line.start_with?("package ") }
fail_check("missing package in #{java_file}") if package_line.nil?
fail_check("wrong package root in #{java_file}") unless package_line.include?(package_root)
end
application = YAML.safe_load(module_path.join("src/main/resources/application.yml").read)
app_name = application.dig("spring", "application", "name")
fail_check("application/Nacos name mismatch for #{id}") unless app_name == expected_service
module_text = module_path.glob("{pom.xml,src/main/**/*}").select(&:file?).map(&:read).join("\n")
fail_check("#{id} contains a Mapper in M0") if module_text.match?(/@Mapper\b|interface\s+\w+Mapper\b/)
fail_check("#{id} contains a database foreign key in M0") if module_text.match?(/\bFOREIGN\s+KEY\b/i)
begin
violations = BusinessUnitApiDependencies.violations(id, module_path.join("pom.xml").read,
Array(allowed_api_dependencies.fetch(id, [])), expected_ids)
fail_check("#{id} depends on another unit API without a declared milestone contract: #{violations.join(', ')}") unless
violations.empty?
# Resource remains outside the four business units. Only the three explicit direct production callers are approved.
xml = REXML::Document.new(module_path.join("pom.xml").read)
REXML::XPath.match(xml, "//m:dependency[m:artifactId='aixun-api-resource']", BusinessUnitApiDependencies::MAVEN_NAMESPACE).each do |node|
scope = node.elements["scope"]&.text || "compile"
group = node.elements["groupId"]&.text
direct = node.parent&.name == "dependencies" && node.parent.parent == xml.root
test_only = BusinessUnitApiDependencies.test_exception?(id, "resource", group, scope, direct)
approved = upgrade_contract.fetch("resourceApiConsumers").include?(id) && group == "cn.aixunkeji" && scope == "compile" && direct
fail_check("#{id} has unapproved Resource API dependency") unless test_only || approved
end
rescue REXML::ParseException, ArgumentError
fail_check("#{id} has invalid dependency XML")
end
end
module_names = root.join("aixun-modules").children.select(&:directory?).map { |path| path.basename.to_s }
fail_check("a fifth adapter deployment module exists") if module_names.any? { |name| name.match?(/adapter/i) }
compose_text = root.join("script/datagov/docker-compose.local.yml").read
enabled_units = m6_contract.dig("scope", "enabledUnits")
forbidden_units = m6_contract.dig("scope", "forbiddenUnits")
fail_check("M6 must statically enable exactly four business units") unless enabled_units == expected_ids
fail_check("M6 must not forbid an approved business unit") unless forbidden_units == []
enabled_units.each do |id|
service_name = units.find { |unit| unit.fetch("id") == id }.fetch("serviceName")
fail_check("#{service_name} must be enabled for the current milestone contract") unless
compose_text.include?(service_name)
end
forbidden_units.each do |id|
service_name = units.find { |unit| unit.fetch("id") == id }.fetch("serviceName")
fail_check("#{service_name} must remain disabled for the current milestone contract") if
compose_text.include?(service_name)
end
puts "Business-unit verification passed: 4 units, declared cross-unit APIs only, M6 static activation includes dataproduct, no fifth adapter service."
end
+359
查看文件
@@ -0,0 +1,359 @@
#!/usr/bin/env ruby
# frozen_string_literal: true
require "digest"
require "pathname"
require "yaml"
require "strscan"
unless ARGV.empty? || ARGV == ["--catalog-only"]
warn "data-contract verification failed: expected no arguments or exactly one --catalog-only"
exit 1
end
catalog_only = ARGV == ["--catalog-only"]
root = Pathname.new(__dir__).join("../..").realpath
rules = YAML.safe_load(root.join("contracts/datagov/data-and-api-rules.yml").read)
catalog = YAML.safe_load(root.join(rules.dig("migrations", "catalog")).read)
sample = YAML.safe_load(root.join("contracts/datagov/samples/integration-contract-probe.yml").read)
def fail_check(message)
warn "data-contract verification failed: #{message}"
exit 1
end
# Bounded SR07 structural grammar, not a MySQL execution substitute.
# Literal tokens are preserved; comments cannot satisfy column or constraint checks.
def sr07_tokens(sql)
scanner = StringScanner.new(sql)
tokens = []
until scanner.eos?
if scanner.scan(/\s+|--[^\n]*(?:\n|\z)|#[^\n]*(?:\n|\z)/)
next
elsif scanner.peek(2) == "/*"
fail_check("SR07 executable/hint comment forbidden") if scanner.peek(3).match?(%r{/\*[!+]})
fail_check("SR07 unterminated comment") unless scanner.scan(%r{/\*.*?\*/}m)
elsif token = scanner.scan(/'(?:[^'\\]|'')*'/)
tokens << token
elsif token = scanner.scan(/\x60[a-zA-Z_][a-zA-Z0-9_]*\x60/)
tokens << token[1...-1].downcase
elsif token = scanner.scan(/[a-zA-Z_][a-zA-Z0-9_]*|\d+|<>|>=|<=|[(),;=<>+*-]/)
tokens << token.downcase
else
fail_check("SR07 unsupported SQL token")
end
end
tokens
end
def sr07_tables(sql)
tokens = sr07_tokens(sql)
tables = {}
suffix = sr07_tokens("ENGINE=InnoDB ROW_FORMAT=DYNAMIC DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin;")
until tokens.empty?
fail_check("SR07 only explicit CREATE TABLE is allowed") unless tokens.shift(2) == %w[create table]
name = tokens.shift
fail_check("SR07 invalid/duplicate table") unless name && name.match?(/\A[a-z][a-z0-9_]*\z/) && !tables.key?(name)
fail_check("SR07 missing table body") unless tokens.shift == "("
parts = []; part = []; depth = 1
until tokens.empty?
token = tokens.shift
depth += 1 if token == "("
depth -= 1 if token == ")"
if depth.zero?
fail_check("SR07 empty definition") if part.empty?
parts << part
break
elsif depth == 1 && token == ","
fail_check("SR07 empty definition") if part.empty?
parts << part; part = []
else
part << token
end
end
fail_check("SR07 unbalanced body") unless depth.zero?
fail_check("SR07 engine/row format/collation drift") unless tokens.shift(suffix.length) == suffix
tables[name] = parts
end
tables
end
sr07_allowed = {
"db/migration/governance/V20260920.158__create_asset_identity_composition.sql" => "20260920.158",
"db/migration/governance/V20260920.159__create_asset_financial_batch.sql" => "20260920.159",
"db/migration/dataproduct/V20260920.160__create_dataset_content.sql" => "20260920.160",
"db/migration/dataproduct/V20260920.161__create_dataset_annotation.sql" => "20260920.161"
}.freeze
sr07_profiles = {}
sr07_table_owners = {}
rules.fetch("sr07MigrationProfiles").each do |profile|
path = profile.fetch("path")
fail_check("unknown/duplicate SR07 migration profile") unless profile.fetch("profile") == "SR07_V1" &&
sr07_allowed[path] == profile.fetch("version") && !sr07_profiles.key?(path)
fail_check("empty SR07 table profile") if profile.fetch("tables").empty?
profile.fetch("tables").each do |table, shape|
fail_check("duplicate SR07 table profile") if sr07_table_owners.key?(table)
fail_check("unknown SR07 shape property") unless shape.keys.sort == %w[checks columns indexes primaryKey].sort
fail_check("empty SR07 columns/constraints") if shape.fetch("columns").empty? || shape.fetch("checks").empty?
fail_check("missing SR07 primary key") unless sr07_tokens(shape.fetch("primaryKey"))[0, 2] == %w[primary key]
sr07_table_owners[table] = path
end
sr07_profiles[path] = profile
end
fail_check("SR07 profiles must exactly cover four approved migrations") unless sr07_profiles.keys.sort == sr07_allowed.keys.sort
def verify_sr07(sql, profile)
actual = sr07_tables(sql)
expected = profile.fetch("tables")
fail_check("SR07 missing/extra table") unless actual.keys.sort == expected.keys.sort
expected.each do |table, shape|
definitions = shape.fetch("columns").map { |column, spec| sr07_tokens("#{column} #{spec}") } +
[sr07_tokens(shape.fetch("primaryKey"))] +
shape.fetch("indexes").map { |index| sr07_tokens(index) } +
shape.fetch("checks").map { |check| sr07_tokens(check) }
fail_check("SR07 structural mismatch in #{table}") unless actual.fetch(table) == definitions
end
end
# Closed domain contracts authorize structure, never a whole-file hash exemption.
# Keep identifiers and literal tokens distinct and consume every statement.
def domain_statements(sql)
tokens = sr07_tokens(sql)
result = []; statement = []; depth = 0
tokens.each do |token|
depth += 1 if token == "("
depth -= 1 if token == ")"
fail_check("domain unbalanced statement") if depth.negative?
if token == ";"
fail_check("domain invalid statement terminator") unless depth.zero? && !statement.empty?
result << statement; statement = []
else
statement << token
end
end
fail_check("domain unterminated statement") unless statement.empty? && depth.zero?
result
end
def domain_table(statement)
fail_check("domain only explicit CREATE TABLE is allowed") unless statement[0, 2] == %w[create table]
name = statement[2]
fail_check("domain invalid table name/body") unless name&.match?(/\A[a-z][a-z0-9_]*\z/) && statement[3] == "("
parts = []; part = []; depth = 1; closing = nil
statement.each_with_index do |token, index|
next if index < 4
depth += 1 if token == "("
depth -= 1 if token == ")"
if depth.zero?
fail_check("domain empty definition") if part.empty?
parts << part; closing = index; break
elsif depth == 1 && token == ","
fail_check("domain empty definition") if part.empty?
parts << part; part = []
else
part << token
end
end
fail_check("domain missing table body end") unless closing
[name, parts, statement[(closing + 1)..]]
end
domain_allowed = {
"db/migration/dataproduct/V20260921.166__create_dataset_input_registration.sql" => ["20260921.166", "dataproduct", %w[svc_dataset_input_registration], []],
"db/migration/governance/V20260921.167__create_asset_compliance_reviews.sql" => ["20260921.167", "governance", %w[sec_compliance_review sec_compliance_revision sec_compliance_evidence sec_compliance_request], []],
"db/migration/dataproduct/V20260921.172__support_dataset_annotation_dispute.sql" => ["20260921.172", "dataproduct", %w[svc_dataset_annotation_dispute], %w[svc_dataset_annotation_history svc_dataset_annotation_request]],
"db/migration/dataops/V20260921.174__create_dataset_preparation_control.sql" => ["20260921.174", "dataops", %w[dev_dataset_preparation_task dev_dataset_preparation_plan_revision dev_dataset_preparation_command dev_dataset_preparation_run dev_dataset_preparation_artifact dev_dataset_preparation_history], []],
"db/migration/governance/V20260921.175__create_asset_identity_source_binding_observation.sql" => ["20260921.175", "governance", %w[asset_identity_source_binding asset_identity_source_observation], []],
"db/migration/governance/V20260921.176__create_financial_draft_input.sql" => ["20260921.176", "governance", %w[asset_financial_input asset_financial_input_revision asset_financial_input_operation asset_financial_input_request asset_financial_input_history], []]
}.freeze
domain_foreign_keys = {
"asset_identity_source_observation" => "CONSTRAINT fk_identity_observation_binding FOREIGN KEY (binding_id) REFERENCES asset_identity_source_binding (binding_id)",
"asset_financial_input_revision" => "CONSTRAINT fk_fin_revision_input FOREIGN KEY (input_id) REFERENCES asset_financial_input (input_id)",
"asset_financial_input_operation" => "CONSTRAINT fk_fin_operation_input FOREIGN KEY (input_id) REFERENCES asset_financial_input (input_id)",
"asset_financial_input_history" => "CONSTRAINT fk_fin_history_input FOREIGN KEY (input_id) REFERENCES asset_financial_input (input_id)"
}.transform_values { |definition| sr07_tokens(definition) }.freeze
domain_profiles = {}; domain_table_owners = {}
rules.fetch("closedDomainMigrationProfiles").each do |profile|
fail_check("domain unknown profile property") unless profile.keys.sort == %w[profile path version ownerUnit tables alters].sort
path = profile.fetch("path"); authority = domain_allowed[path]
fail_check("unknown/duplicate domain migration profile") unless authority && profile.fetch("profile") == "CLOSED_DOMAIN_V1" && !domain_profiles.key?(path)
fail_check("domain profile identity mismatch") unless [profile.fetch("version"), profile.fetch("ownerUnit")] == authority[0, 2]
fail_check("domain profile table set mismatch") unless profile.fetch("tables").keys.sort == authority[2].sort
fail_check("domain profile ALTER target set mismatch") unless profile.fetch("alters").map { |alter| alter.fetch("table") } == authority[3]
profile.fetch("tables").each do |table, shape|
fail_check("domain unknown shape property") unless shape.keys.sort == %w[definitions options]
fail_check("domain empty shape") unless shape.values.all? { |value| value.is_a?(String) && !value.strip.empty? }
domain_table_owners[table] = path
end
profile.fetch("alters").each do |alter|
fail_check("domain unknown ALTER property") unless alter.keys.sort == %w[clauses table]
end
domain_profiles[path] = profile
end
fail_check("domain profiles must exactly cover six approved migrations") unless domain_profiles.keys.sort == domain_allowed.keys.sort
def verify_domain(sql, profile, foreign_keys)
actual = domain_statements(sql)
tables = profile.fetch("tables")
alters = profile.fetch("alters")
fail_check("domain missing/extra statement") unless actual.length == tables.length + alters.length
tables.each_with_index do |(table, shape), index|
name, definitions, options = domain_table(actual[index])
fail_check("domain missing/extra/order table #{table}") unless name == table
expected = domain_statements("CREATE TABLE #{table} (#{shape.fetch('definitions')}) #{shape.fetch('options')};")
fail_check("domain profile injected statement") unless expected.length == 1
_expected_name, expected_definitions, expected_options = domain_table(expected.first)
approved = foreign_keys.key?(table) ? [foreign_keys.fetch(table)] : []
[definitions, expected_definitions].each do |parts|
found = parts.select { |part| part.each_cons(2).any? { |pair| pair == %w[foreign key] } }
fail_check("domain foreign key contract mismatch in #{table}") unless found == approved
end
fail_check("domain structural mismatch in #{table}") unless definitions == expected_definitions && options == expected_options
end
alters.each_with_index do |alter, index|
expected = domain_statements("ALTER TABLE #{alter.fetch('table')} #{alter.fetch('clauses')};")
fail_check("domain profile injected ALTER") unless expected.length == 1
fail_check("domain ALTER mismatch in #{alter.fetch('table')}") unless actual[tables.length + index] == expected.first
end
tables.keys
end
expected_prefixes = {
"dg_" => "integration",
"ing_" => "dataops", "store_" => "dataops", "dev_" => "dataops", "ops_" => "dataops",
"std_" => "governance", "md_" => "governance", "dq_" => "governance",
"da_" => "governance", "wb_" => "governance",
"mdm_" => "governance",
"asset_" => "governance", "sec_" => "governance",
"svc_" => "dataproduct", "metric_" => "dataproduct"
}
prefix_owners = rules.dig("database", "prefixOwners")
fail_check("table prefix registry drifted from the approved M0 set") unless prefix_owners == expected_prefixes
fail_check("V1 must remain single-organization") unless rules.dig("database", "organizationMode") == "SINGLE_ORGANIZATION"
fail_check("migrations must be forward-only") unless rules.dig("migrations", "forwardOnly") == true
migrations = catalog.fetch("migrations")
versions = migrations.map { |migration| migration.fetch("version") }
fail_check("migration versions must be unique and ordered") unless versions == versions.uniq.sort
catalog_paths = migrations.map { |migration| migration.fetch("path") }
fail_check("SR07 catalog entries missing") unless (sr07_profiles.keys - catalog_paths).empty?
fail_check("domain catalog entries missing") unless (domain_profiles.keys - catalog_paths).empty?
actual_paths = root.join("db/migration").glob("*/V*.sql").map { |path| path.relative_path_from(root).to_s }.sort
if catalog_only
fail_check("migration catalog references missing SQL files") unless (catalog_paths - actual_paths).empty?
else
fail_check("migration catalog does not exactly cover SQL files") unless catalog_paths.sort == actual_paths
end
required_columns = rules.dig("database", "requiredColumns")
forbidden_sql = rules.dig("database", "forbiddenSql")
fail_check("domain must retain global SQL prohibitions") unless %w[FOREIGN\ KEY DROP\ TABLE TRUNCATE\ TABLE].all? { |token| forbidden_sql.include?(token) }
# Historical 131 approval: Resource reuses this exact system-owned binding table.
# A catalog checksum update alone must never authorize different SQL bytes.
private_file_binding = {
path: "db/migration/system/V20260921.165__create_private_business_file_binding.sql",
version: "20260921.165",
owner: "system",
table: "sys_oss_business_binding",
sha256: "1fe1101329430fd838d63f1c03118b279d3618c278087264c52723be73c97ca5"
}.freeze
# Resource stores this receipt with the existing RCP6 mailbox in one transaction.
# Keep the exception bound to this table and reviewed SQL, not all system DDL.
workflow_alert_receipt = {
path: "db/migration/system/V20261022.252__create_workflow_alert_receipt.sql",
version: "20261022.252",
owner: "system",
table: "sys_workflow_alert_receipt",
sha256: "155c58f0cd5621736cafb3ba7890978695e8f8ba1be5ff888e8534808a5bb06c"
}.freeze
migrations.each do |migration|
version = migration.fetch("version")
owner = migration.fetch("ownerUnit")
relative_path = migration.fetch("path")
path = root.join(relative_path)
fail_check("invalid migration version #{version}") unless version.match?(/\A\d{8}\.\d{3}\z/)
fail_check("invalid migration owner #{owner}") unless %w[system integration dataops governance dataproduct].include?(owner)
fail_check("migration path escapes the repository") unless path.cleanpath.to_s.start_with?(root.to_s + File::SEPARATOR)
fail_check("invalid migration filename #{relative_path}") unless
path.basename.to_s.match?(/\AV\d{8}\.\d{3}__[a-z0-9_]+\.sql\z/)
filename_version = path.basename.to_s[/\AV(\d{8}\.\d{3})__/, 1]
fail_check("migration version/filename mismatch for #{relative_path}") unless filename_version == version
fail_check("migration #{version} is in the wrong owner directory") unless path.dirname.basename.to_s == owner
actual_sha256 = Digest::SHA256.file(path).hexdigest
fail_check("invalid checksum for #{version}") unless migration.fetch("sha256").match?(/\A[0-9a-f]{64}\z/)
fail_check("checksum mismatch for #{version}") unless migration.fetch("sha256") == actual_sha256
sql = path.read
domain_profile = domain_profiles[relative_path]
forbidden_sql.each do |token|
next if domain_profile && token == "FOREIGN KEY" # Granted only after complete structural proof below.
fail_check("#{relative_path} contains forbidden SQL #{token}") if sql.match?(/\b#{Regexp.escape(token).gsub("\\ ", "\\s+")}\b/i)
end
fail_check("#{relative_path} contains a tenant column") if sql.match?(/\btenant_id\b/i)
created_tables = sql.scan(/CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([a-z0-9_]+)/i).flatten
if domain_profile
fail_check("domain migration identity mismatch") unless [version, owner] == domain_allowed.fetch(relative_path)[0, 2]
created_tables = verify_domain(sql, domain_profile, domain_foreign_keys)
end
approved_private_binding = relative_path == private_file_binding.fetch(:path)
if approved_private_binding
fail_check("private-file binding migration identity mismatch") unless
version == private_file_binding.fetch(:version) && owner == private_file_binding.fetch(:owner)
fail_check("private-file binding migration approved checksum mismatch") unless
actual_sha256 == private_file_binding.fetch(:sha256)
fail_check("private-file binding migration must create exactly the approved table") unless
created_tables == [private_file_binding.fetch(:table)]
end
approved_workflow_receipt = relative_path == workflow_alert_receipt.fetch(:path)
if approved_workflow_receipt
fail_check("workflow mailbox receipt migration identity mismatch") unless
version == workflow_alert_receipt.fetch(:version) && owner == workflow_alert_receipt.fetch(:owner)
fail_check("workflow mailbox receipt migration checksum mismatch") unless
actual_sha256 == workflow_alert_receipt.fetch(:sha256)
fail_check("workflow mailbox receipt must create exactly its owned table") unless
created_tables == [workflow_alert_receipt.fetch(:table)]
end
profile = sr07_profiles[relative_path]
verify_sr07(sql, profile) if profile
created_tables.each do |table|
if domain_table_owners.key?(table) && domain_table_owners[table] != relative_path
fail_check("domain table #{table} is declared by the wrong migration")
end
if sr07_table_owners.key?(table) && sr07_table_owners[table] != relative_path
fail_check("SR07 table #{table} is declared by the wrong migration")
end
next if approved_private_binding && table == private_file_binding.fetch(:table)
next if approved_workflow_receipt && table == workflow_alert_receipt.fetch(:table)
fail_check("system migration cannot create business tables") if owner == "system"
allowed_prefixes = prefix_owners.select { |_prefix, unit| unit == owner }.keys
fail_check("#{table} is not owned by #{owner}") unless allowed_prefixes.any? { |prefix| table.start_with?(prefix) }
next if table == "dg_schema_history"
next if profile # Already checked every real definition against this exact migration/table profile.
next if domain_profile # Complete table, options and ALTER contract proved above.
required_columns.each do |column|
fail_check("#{table} is missing #{column}") unless sql.match?(/\b#{Regexp.escape(column)}\b/i)
end
fail_check("#{table} is missing a primary key") unless sql.match?(/PRIMARY\s+KEY/i)
end
end
fail_check("sample must remain non-business") unless sample.fetch("implementedBusinessFeature") == false
fail_check("sample REST path is invalid") unless sample.fetch("path").match?(%r{\A/api/[a-z][a-z0-9-]*/v1/[a-z0-9-]+\z})
fail_check("sample permission is invalid") unless sample.fetch("permission").match?(/\Aaixun:[a-z0-9-]+:[a-z0-9-]+:[a-z0-9-]+\z/)
fail_check("sample idempotency key is invalid") unless sample.fetch("idempotencyKey").match?(/\A[A-Za-z0-9._:-]{16,128}\z/)
fail_check("sample error code is outside integration range") unless (110_000..119_999).cover?(sample.fetch("sampleBusinessErrorCode"))
fail_check("sample table does not belong to integration") unless sample.fetch("databaseTable").start_with?("dg_")
fail_check("sample must not publish Dubbo") unless sample.fetch("dubboPublished") == false
fail_check("sample must not require an external component") unless sample.fetch("externalComponentRequired") == false
scope = catalog_only ? " (catalog-scoped)" : ""
puts "Data contract verification passed: #{migrations.size} migrations#{scope}, 15 prefixes, REST/permission/error/idempotency sample valid."
+57
查看文件
@@ -0,0 +1,57 @@
#!/usr/bin/env ruby
# frozen_string_literal: true
require "pathname"
root = Pathname.new(__dir__).join("../..").realpath
evidence_root = root.join("evidence/M0")
def fail_check(message)
warn "Evidence verification failed: #{message}"
exit 1
end
required = {
"M0-001" => %w[README.md rollback.md toolchain.md frozen-inputs.sha256],
"M0-002" => %w[README.md rollback.md changed-files.md build-test.md runtime-browser.md],
"M0-003" => %w[README.md rollback.md changed-files.md verification.md boundary-matrix.md],
"M0-004" => %w[README.md rollback.md changed-files.md migration-and-contract-test.md security-and-isolation.md],
"M0-005" => %w[README.md risk-and-rollback.md changed-files.md verification.md],
"M0-006" => %w[README.md rollback.md changed-files.md build-and-gates.md browser-acceptance.md],
"M0-007" => %w[README.md rollback.md changed-files.md java-and-gates.md mysql-concurrency.md],
"M0-008" => %w[README.md rollback.md changed-files.md verification.md codex-config.md],
"M0-009" => %w[README.md rollback.md changed-files.md preflight-negative-tests.md runtime-acceptance.md]
}
actual_dirs = evidence_root.children.select(&:directory?).map { |path| path.basename.to_s }.grep(/^M0-\d{3}$/).sort
fail_check("task directories differ: #{actual_dirs.join(', ')}") unless actual_dirs == required.keys.sort
required.each do |task_id, filenames|
dir = evidence_root.join(task_id)
filenames.each do |filename|
path = dir.join(filename)
fail_check("#{task_id}/#{filename} is missing") unless path.file?
fail_check("#{task_id}/#{filename} is empty") if path.size.zero?
fail_check("#{task_id}/#{filename} is a symlink") if path.symlink?
end
readme = dir.join("README.md").read
statuses = readme.scan(/\b(?:PASS_WITH_LIMITATION|PASS|BLOCKED)\b/).uniq
fail_check("#{task_id}/README.md must contain one terminal result") unless statuses.length == 1
end
pngs = %w[home-1920x1080.png home-1366x768.png]
pngs.each do |filename|
path = evidence_root.join("M0-006/screenshots", filename)
fail_check("M0-006 screenshot #{filename} is missing") unless path.file?
signature = File.binread(path, 8).bytes
png = signature == [137, 80, 78, 71, 13, 10, 26, 10]
jpeg = signature.first(3) == [255, 216, 255]
fail_check("M0-006 screenshot #{filename} is not a PNG/JPEG image") unless png || jpeg
end
forbidden = evidence_root.glob("**/*").select(&:file?).select do |path|
path.basename.to_s.match?(/(?:\.env(?:\.|$)|\.pem$|\.key$|\.p12$|\.jks$|\.keystore$|cookie|session-storage|local-storage)/i)
end
fail_check("secret-bearing evidence filenames found") unless forbidden.empty?
puts "Evidence verification passed: nine M0 task directories, terminal results, required files, and renderable screenshot signatures are present."
+35
查看文件
@@ -0,0 +1,35 @@
#!/usr/bin/env bash
set -euo pipefail
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly PROJECT_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"
readonly MANIFEST="${PROJECT_ROOT}/evidence/M0/M0-001/frozen-inputs.sha256"
fail() {
echo "Frozen-input verification failed: $*" >&2
exit 1
}
[[ -f "${MANIFEST}" ]] || fail "checksum manifest is missing"
[[ "$(wc -l < "${MANIFEST}" | tr -d ' ')" == "4" ]] || fail "manifest must contain exactly four inputs"
while read -r checksum relative_path; do
[[ "${checksum}" =~ ^[0-9a-f]{64}$ ]] || fail "invalid SHA-256 entry"
[[ "${relative_path}" == start-docs/* ]] || fail "input is outside start-docs"
[[ "${relative_path}" != start-docs/数据治理平台需求规格说明书_v1.0/* ]] || fail "derived specification is not a frozen original input"
[[ -f "${PROJECT_ROOT}/${relative_path}" ]] || fail "frozen input is missing"
done < "${MANIFEST}"
(cd "${PROJECT_ROOT}" && shasum -a 256 -c "${MANIFEST}")
expected_license="$(sed -n 's/^upstream\.license\.sha256=//p' "${PROJECT_ROOT}/upstream.lock")"
[[ "${expected_license}" =~ ^[0-9a-f]{64}$ ]] || fail "upstream license lock is missing"
actual_license="$(shasum -a 256 "${PROJECT_ROOT}/LICENSE" | awk '{print $1}')"
[[ "${actual_license}" == "${expected_license}" ]] || fail "upstream MIT LICENSE hash drifted"
upstream_release="$(sed -n 's/^upstream\.release=//p' "${PROJECT_ROOT}/upstream.lock")"
upstream_commit="$(sed -n 's/^upstream\.commit=//p' "${PROJECT_ROOT}/upstream.lock")"
[[ "${upstream_release}" == "v6.0.0" ]] || fail "upstream release lock drifted"
[[ "${upstream_commit}" =~ ^[0-9a-f]{40}$ ]] || fail "upstream commit lock is missing"
echo "Frozen-input verification passed: four original inputs, upstream MIT LICENSE, and source lock are unchanged."
+11
查看文件
@@ -0,0 +1,11 @@
#!/usr/bin/env bash
# Compatibility entry: no historical process gates, no implicit migrations.
set -euo pipefail
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
case "${1:---help}" in
--static|--help) echo 'Historical M0 replay retired. Select affected checks:'; exec "$DIR/check.sh" --help ;;
--full) shift; exec "$DIR/check.sh" --full "$@" ;;
--runtime) shift; exec "$DIR/check.sh" --runtime "$@" ;;
--all) "$DIR/check.sh" --full; exec "$DIR/check.sh" --runtime ;;
*) exec "$DIR/check.sh" "$@" ;;
esac
+66
查看文件
@@ -0,0 +1,66 @@
#!/usr/bin/env ruby
# frozen_string_literal: true
require "pathname"
root = Pathname.new(__dir__).join("../..").realpath
module_root = root.join("aixun-common/aixun-common-maintenance")
java_files = module_root.join("src/main/java").glob("**/*.java")
def fail_check(message)
warn "maintenance-job verification failed: #{message}"
exit 1
end
fail_check("maintenance module is missing") unless module_root.directory?
fail_check("Spring scheduled trigger is missing") unless java_files.any? { |path| path.read.include?("@Scheduled") }
forbidden_imports = /import\s+.*(?:quartz|xxl|dolphinscheduler|seatunnel|kafka|rocketmq)/i
forbidden_web = /@(RestController|Controller|RequestMapping)\b/
java_files.each do |path|
source = path.read
fail_check("#{path.basename} imports a forbidden scheduler/data engine/channel") if source.match?(forbidden_imports)
fail_check("#{path.basename} creates a second maintenance console/API") if source.match?(forbidden_web)
end
kinds = module_root.join(
"src/main/java/cn/aixunkeji/datagov/maintenance/MaintenanceJobKind.java"
).read.scan(/^\s+([A-Z][A-Z_]+),?$/).flatten
approved_kinds = %w[
STATUS_RECONCILIATION
CONNECTION_HEALTH
PROJECTION_REFRESH
RETENTION_CLEANUP
IN_APP_ALERT
]
fail_check("maintenance kind allowlist drifted") unless kinds == approved_kinds
jdbc_source = module_root.join(
"src/main/java/cn/aixunkeji/datagov/maintenance/JdbcMaintenanceLeaseRepository.java"
).read
%w[ON\ DUPLICATE\ KEY lease_until\ \<\= last_idempotency_key last_outcome attempt_no version\ \=\ version\ \+\ 1].each do |token|
fail_check("JDBC lease implementation is missing #{token.gsub('\\', '')}") unless jdbc_source.match?(Regexp.new(token))
end
runner_source = module_root.join(
"src/main/java/cn/aixunkeji/datagov/maintenance/MaintenanceJobRunner.java"
).read
fail_check("maximum execution timeout is missing") unless runner_source.include?("maximumExecutionTime().toMillis()")
fail_check("timed-out runs must retain their lease") unless
runner_source.match?(/MaintenanceRunOutcome\.TIMED_OUT, completedAt, false/)
fail_check("manual compensation entry is missing") unless module_root.join(
"src/main/java/cn/aixunkeji/datagov/maintenance/MaintenanceRunRequest.java"
).read.include?("compensation(")
migration = root.join("db/migration/integration/V20260824.003__create_maintenance_lease.sql").read
%w[lease_until last_idempotency_key last_trigger_type last_compensation_reason last_outcome attempt_no].each do |column|
fail_check("lease migration is missing #{column}") unless migration.match?(/\b#{column}\b/i)
end
fail_check("lease migration contains a foreign key") if migration.match?(/FOREIGN\s+KEY/i)
test_source = module_root.join("src/test/java/cn/aixunkeji/datagov/maintenance/MaintenanceJobRunnerTest.java").read
%w[duplicateTrigger expiredLease maximumDuration manualCompensation failedRun scheduledTrigger].each do |scenario|
fail_check("test suite is missing #{scenario}") unless test_source.include?(scenario)
end
puts "Maintenance-job verification passed: Spring trigger, MySQL lease, idempotency, timeout, retry, compensation, and recovery gates present."
+40
查看文件
@@ -0,0 +1,40 @@
#!/usr/bin/env ruby
# frozen_string_literal: true
require "pathname"
require "yaml"
root = Pathname.new(__dir__).join("../..").realpath
contract = YAML.safe_load(root.join("contracts/datagov/secret-ref.yml").read)
migration = root.join("db/migration/integration/V20260824.002__create_secret_binding.sql").read
def fail_check(message)
warn "secretRef verification failed: #{message}"
exit 1
end
fail_check("business integration was claimed") unless contract.fetch("externalComponentsIntegrated") == false
fail_check("plaintext fallback must be disabled") unless contract.dig("rotation", "plaintextFallback") == false
fail_check("reference version must be mandatory") unless contract.dig("referenceRules", "requiredVersion") == true
columns = migration.scan(/^\s*([a-z][a-z0-9_]*)\s+(?:BIGINT|VARCHAR|CHAR|DATETIME)\b/i).flatten
forbidden_columns = columns.grep(/(?:password|token|credential|secret_(?:value|material)|connection_string)/i)
fail_check("plaintext-like columns found: #{forbidden_columns.join(', ')}") unless forbidden_columns.empty?
%w[secret_ref secret_ref_fingerprint secret_version].each do |required|
fail_check("missing reference metadata column #{required}") unless columns.include?(required)
end
view_source = root.join(
"aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/secret/SecretBindingView.java"
).read
view_code = view_source.gsub(%r{/\*.*?\*/}m, "").gsub(%r{//.*$}, "")
fail_check("safe view exposes a secret reference") if view_code.match?(/SecretRef|secretRef/)
fail_check("safe view exposes material") if view_code.match?(/SecretMaterial|char\[\]|material/i)
java_files = root.join("aixun-modules/aixun-integration/src/main/java").glob("**/*.java")
java_files.each do |path|
source = path.read
fail_check("#{path.basename} logs or prints secret input") if source.match?(/(?:System\.(?:out|err)|log\.(?:trace|debug|info|warn|error))\s*\([^\n]*(?:material|secretRef)/i)
end
puts "secretRef verification passed: reference-only schema, safe view, fail-closed contract, no secret logging calls."
+3
查看文件
@@ -0,0 +1,3 @@
#!/usr/bin/env bash
# Compatibility notice only; ADR-0033 retired manual path/role/runtime leases.
echo 'RETIRED: no Writer lease gate. Coordinate actual file conflicts; use check.sh for affected checks.'
+3
查看文件
@@ -0,0 +1,3 @@
#!/usr/bin/env ruby
# Task packets are optional under ADR-0033; no historical heading/status gate.
puts 'RETIRED: task packets are optional. Record the actual change, checks and recovery once.'
+4
查看文件
@@ -0,0 +1,4 @@
#!/usr/bin/env ruby
# Literal Drawer widths, operation-column widths and evidence wording are not
# development gates. RCP6 behavior is checked on the actual affected page.
puts 'RETIRED: use affected frontend lint/build and interaction checks; preserve the RCP6 UI baseline.'