Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7fe0927a31 | ||
|
|
6d338f25d8 | ||
|
|
2b64d8ab9f | ||
|
|
52872d1af2 | ||
|
|
5eb96cfa74 | ||
|
|
80c2d36fd2 | ||
|
|
c34ffc855e |
@@ -44,7 +44,21 @@ jobs:
|
||||
git init .
|
||||
git remote remove origin 2>/dev/null || true
|
||||
git remote add origin https://git.copse.top/root/Jyotisha.git
|
||||
git fetch --no-tags origin "$GITEA_SHA"
|
||||
# BUG-2391: take the exact SHA from the runner's bare mirror when it already has it (the staging
|
||||
# gate keeps it current); otherwise a bounded shallow fetch. A full-history fetch took 11-12 minutes.
|
||||
if git -C /root/.cache/jyotisha-mirror.git cat-file -e "$GITEA_SHA^{commit}" 2>/dev/null \
|
||||
&& timeout 300 git fetch --no-tags /root/.cache/jyotisha-mirror.git "$GITEA_SHA"; then
|
||||
echo "fetched $GITEA_SHA from the runner mirror"
|
||||
else
|
||||
for attempt in 1 2 3; do
|
||||
if timeout 300 git -c http.connectTimeout=15 -c http.lowSpeedLimit=1 -c http.lowSpeedTime=60 \
|
||||
fetch --depth=1 --no-tags origin "$GITEA_SHA"; then
|
||||
break
|
||||
fi
|
||||
[ "$attempt" -lt 3 ] || { echo "exact checkout of $GITEA_SHA failed after 3 bounded attempts" >&2; exit 1; }
|
||||
sleep $((attempt * 10))
|
||||
done
|
||||
fi
|
||||
git checkout --detach --force "$GITEA_SHA"
|
||||
REQUESTED_SHA="$DEPLOY_SHA" CHECK_RELEASE_GATE=true bash deploy/resolve-release-revision.sh >>"$GITHUB_OUTPUT"
|
||||
release_sha="$(awk -F= '$1 == "release_sha" { print $2 }' "$GITHUB_OUTPUT" | tail -n 1)"
|
||||
@@ -67,7 +81,21 @@ jobs:
|
||||
git init .
|
||||
git remote remove origin 2>/dev/null || true
|
||||
git remote add origin https://git.copse.top/root/Jyotisha.git
|
||||
git fetch --no-tags origin "$DEPLOY_SHA"
|
||||
# BUG-2391: take the exact SHA from the runner's bare mirror when it already has it (the staging
|
||||
# gate keeps it current); otherwise a bounded shallow fetch. A full-history fetch took 11-12 minutes.
|
||||
if git -C /root/.cache/jyotisha-mirror.git cat-file -e "$DEPLOY_SHA^{commit}" 2>/dev/null \
|
||||
&& timeout 300 git fetch --no-tags /root/.cache/jyotisha-mirror.git "$DEPLOY_SHA"; then
|
||||
echo "fetched $DEPLOY_SHA from the runner mirror"
|
||||
else
|
||||
for attempt in 1 2 3; do
|
||||
if timeout 300 git -c http.connectTimeout=15 -c http.lowSpeedLimit=1 -c http.lowSpeedTime=60 \
|
||||
fetch --depth=1 --no-tags origin "$DEPLOY_SHA"; then
|
||||
break
|
||||
fi
|
||||
[ "$attempt" -lt 3 ] || { echo "exact checkout of $DEPLOY_SHA failed after 3 bounded attempts" >&2; exit 1; }
|
||||
sleep $((attempt * 10))
|
||||
done
|
||||
fi
|
||||
git checkout --detach --force "$DEPLOY_SHA"
|
||||
[[ "$(git rev-parse HEAD)" == "$DEPLOY_SHA" ]]
|
||||
|
||||
|
||||
@@ -69,7 +69,21 @@ jobs:
|
||||
git init .
|
||||
git remote remove origin 2>/dev/null || true
|
||||
git remote add origin https://git.copse.top/root/Jyotisha.git
|
||||
git fetch --no-tags origin "$GITEA_SHA"
|
||||
# BUG-2391: take the exact SHA from the runner's bare mirror when it already has it (the staging
|
||||
# gate keeps it current); otherwise a bounded shallow fetch. A full-history fetch took 11-12 minutes.
|
||||
if git -C /root/.cache/jyotisha-mirror.git cat-file -e "$GITEA_SHA^{commit}" 2>/dev/null \
|
||||
&& timeout 300 git fetch --no-tags /root/.cache/jyotisha-mirror.git "$GITEA_SHA"; then
|
||||
echo "fetched $GITEA_SHA from the runner mirror"
|
||||
else
|
||||
for attempt in 1 2 3; do
|
||||
if timeout 300 git -c http.connectTimeout=15 -c http.lowSpeedLimit=1 -c http.lowSpeedTime=60 \
|
||||
fetch --depth=1 --no-tags origin "$GITEA_SHA"; then
|
||||
break
|
||||
fi
|
||||
[ "$attempt" -lt 3 ] || { echo "exact checkout of $GITEA_SHA failed after 3 bounded attempts" >&2; exit 1; }
|
||||
sleep $((attempt * 10))
|
||||
done
|
||||
fi
|
||||
git checkout --detach --force "$GITEA_SHA"
|
||||
if [[ "$allow_rollback" == false ]]; then
|
||||
CHECK_RELEASE_GATE=true bash deploy/resolve-release-revision.sh >>"$GITHUB_OUTPUT"
|
||||
|
||||
@@ -19,7 +19,8 @@ on:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
# BUG-2390: actions: write so the deploy can queue the full release checks for its SHA.
|
||||
actions: write
|
||||
|
||||
concurrency:
|
||||
group: staging-mutation
|
||||
@@ -390,3 +391,24 @@ jobs:
|
||||
printf '%s' "$REGISTRY_PASSWORD" | ssh "${ssh_options[@]}" "$remote" "sudo -n docker --config '$incoming/.docker' login '$REGISTRY_HOST' --username '$REGISTRY_USERNAME' --password-stdin"
|
||||
ssh "${ssh_options[@]}" "$remote" "sudo -n env INCOMING_PATH='$incoming' DEPLOY_PATH='$DEPLOY_PATH' API_IMAGE='$API_IMAGE' WEB_IMAGE='$WEB_IMAGE' DEPLOY_SHA='$DEPLOY_SHA' EXPECTED_PREVIOUS_SHA='$previous_sha' ALLOW_ROLLBACK='$ALLOW_ROLLBACK' FORWARD_REVISION_VERIFIED='$forward_verified' DOCKER_CONFIG='$incoming/.docker' DOCKER_BIN='docker' STAGING_URL='$STAGING_URL' bash '$incoming/deploy/run-staging-deploy.sh'"
|
||||
require_current_staging_head
|
||||
|
||||
# BUG-2390 (owner 2026-11-25): queue the full release checks for exactly this SHA now,
|
||||
# so the production release does not rerun them later. Staging itself never waits on
|
||||
# it or fails because of it; a newer staging deploy cancels an older queued run.
|
||||
- name: Queue the full release checks for this SHA
|
||||
if: steps.revision.outputs.allow_rollback != 'true'
|
||||
env:
|
||||
DEPLOY_SHA: ${{ steps.revision.outputs.sha }}
|
||||
run: |
|
||||
set -uo pipefail
|
||||
payload='{"ref":"refs/heads/staging"}'
|
||||
if curl --fail --silent --show-error --connect-timeout 15 --max-time 60 --retry 3 --retry-all-errors \
|
||||
--request POST \
|
||||
--header "Authorization: token $GITEA_TOKEN" \
|
||||
--header "Content-Type: application/json" \
|
||||
--data "$payload" \
|
||||
"$GITEA_API_URL/repos/$GITEA_REPOSITORY/actions/workflows/release-quality-gate.yml/dispatches" >/dev/null; then
|
||||
echo "queued the full release checks for $DEPLOY_SHA"
|
||||
else
|
||||
echo "::warning::could not queue the full release checks for $DEPLOY_SHA; dispatch Jyotish Release Quality Gate from main before releasing"
|
||||
fi
|
||||
|
||||
@@ -88,7 +88,21 @@ jobs:
|
||||
git init .
|
||||
git remote remove origin 2>/dev/null || true
|
||||
git remote add origin https://git.copse.top/root/Jyotisha.git
|
||||
git fetch --no-tags origin "$GITEA_SHA"
|
||||
# BUG-2391: take the exact SHA from the runner's bare mirror when it already has it (the staging
|
||||
# gate keeps it current); otherwise a bounded shallow fetch. A full-history fetch took 11-12 minutes.
|
||||
if git -C /root/.cache/jyotisha-mirror.git cat-file -e "$GITEA_SHA^{commit}" 2>/dev/null \
|
||||
&& timeout 300 git fetch --no-tags /root/.cache/jyotisha-mirror.git "$GITEA_SHA"; then
|
||||
echo "fetched $GITEA_SHA from the runner mirror"
|
||||
else
|
||||
for attempt in 1 2 3; do
|
||||
if timeout 300 git -c http.connectTimeout=15 -c http.lowSpeedLimit=1 -c http.lowSpeedTime=60 \
|
||||
fetch --depth=1 --no-tags origin "$GITEA_SHA"; then
|
||||
break
|
||||
fi
|
||||
[ "$attempt" -lt 3 ] || { echo "exact checkout of $GITEA_SHA failed after 3 bounded attempts" >&2; exit 1; }
|
||||
sleep $((attempt * 10))
|
||||
done
|
||||
fi
|
||||
git checkout --detach --force "$GITEA_SHA"
|
||||
REQUESTED_SHA="$DEPLOY_SHA" CHECK_RELEASE_GATE=true bash deploy/resolve-release-revision.sh >>"$GITHUB_OUTPUT"
|
||||
release_sha="$(awk -F= '$1 == "release_sha" { print $2 }' "$GITHUB_OUTPUT" | tail -n 1)"
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
name: Monitor Public Health
|
||||
|
||||
# BUG-2348: availability probe from outside the production server. Every 5
|
||||
# BUG-2348: availability probe from outside the production server. Every 10
|
||||
# minutes the runner opens the public health URL three times, 20 seconds apart.
|
||||
# BUG-2389: it used to check out the whole repository (a shallow fetch of the
|
||||
# ~105 MB tree takes 4-8 minutes from this runner), so every run hit the 5-minute
|
||||
# limit and was cancelled with exit code -1 while holding the runner. It now
|
||||
# reads only its two scripts, has a 3-minute budget (worst case about 2 minutes), and a newer run replaces an
|
||||
# older one, so it can never queue up behind or in front of a release.
|
||||
# Three failures in a row send one alert (Feishu and/or email); the first good
|
||||
# probe afterwards sends one recovery. State lives under the runner user's home
|
||||
# so an outage alerts once, not every run.
|
||||
@@ -13,7 +18,7 @@ name: Monitor Public Health
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "*/5 * * * *"
|
||||
- cron: "*/10 * * * *"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -21,16 +26,19 @@ permissions:
|
||||
|
||||
concurrency:
|
||||
group: monitor-public-health
|
||||
cancel-in-progress: false
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
probe:
|
||||
if: gitea.ref == 'refs/heads/main'
|
||||
runs-on: xiaoxin
|
||||
timeout-minutes: 5
|
||||
timeout-minutes: 3
|
||||
env:
|
||||
GITEA_SHA: ${{ gitea.sha }}
|
||||
GITEA_REF: ${{ gitea.ref }}
|
||||
GITEA_API_URL: ${{ gitea.api_url }}
|
||||
GITEA_REPOSITORY: ${{ gitea.repository }}
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
steps:
|
||||
- name: Probe https://jyotisha.chat/api/health
|
||||
env:
|
||||
@@ -44,11 +52,18 @@ jobs:
|
||||
set +x
|
||||
[[ "$GITEA_REF" == "refs/heads/main" ]]
|
||||
[[ "$GITEA_SHA" =~ ^[0-9a-f]{40}$ ]]
|
||||
git init -q .
|
||||
git remote remove origin 2>/dev/null || true
|
||||
git remote add origin https://git.copse.top/root/Jyotisha.git
|
||||
git fetch -q --no-tags --depth 1 origin "$GITEA_SHA"
|
||||
git checkout -q --detach --force "$GITEA_SHA"
|
||||
# Only the two monitor scripts are needed: from the runner's bare mirror when it
|
||||
# has this SHA, otherwise from the Gitea raw API, each request capped at 20 seconds.
|
||||
install -d deploy/monitor
|
||||
for script in healthcheck-alert.sh notify-feishu.sh; do
|
||||
path="deploy/monitor/$script"
|
||||
if ! timeout 20 git --git-dir=/root/.cache/jyotisha-mirror.git show "$GITEA_SHA:$path" >"$path" 2>/dev/null; then
|
||||
curl --fail --silent --show-error --connect-timeout 10 --max-time 20 \
|
||||
--header "Authorization: token $GITEA_TOKEN" \
|
||||
"$GITEA_API_URL/repos/$GITEA_REPOSITORY/raw/$path?ref=$GITEA_SHA" --output "$path"
|
||||
fi
|
||||
test -s "$path"
|
||||
done
|
||||
work="${RUNNER_TEMP}/monitor-public-health"
|
||||
install -m 700 -d "$work"
|
||||
env_file="$work/monitor.env"
|
||||
|
||||
@@ -1,8 +1,18 @@
|
||||
name: Jyotish Release Quality Gate (manual only)
|
||||
name: Jyotish Release Quality Gate (after staging deploy, or manual)
|
||||
|
||||
# BUG-2390 (owner 2026-11-25): the full release checks run once per SHA. Deploy staging
|
||||
# dispatches this workflow on refs/heads/staging right after a successful deploy, so the
|
||||
# result already exists when the owner approves the release; production workflows accept
|
||||
# that run for the exact SHA. A manual dispatch from main stays as the fallback (for
|
||||
# example when a newer staging push cancelled the automatic run).
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
# A newer staging deploy supersedes an older automatic run; manual runs from main use their own group.
|
||||
concurrency:
|
||||
group: release-quality-${{ gitea.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
release-quality-gate:
|
||||
runs-on: xiaoxin
|
||||
@@ -19,22 +29,63 @@ jobs:
|
||||
git init .
|
||||
git remote remove origin 2>/dev/null || true
|
||||
git remote add origin https://git.copse.top/root/Jyotisha.git
|
||||
git fetch --no-tags origin "$GITEA_SHA"
|
||||
# BUG-2391: take the exact SHA from the runner's bare mirror when it already has it (the staging
|
||||
# gate keeps it current); otherwise a bounded shallow fetch. A full-history fetch took 11-12 minutes.
|
||||
if git -C /root/.cache/jyotisha-mirror.git cat-file -e "$GITEA_SHA^{commit}" 2>/dev/null \
|
||||
&& timeout 300 git fetch --no-tags /root/.cache/jyotisha-mirror.git "$GITEA_SHA"; then
|
||||
echo "fetched $GITEA_SHA from the runner mirror"
|
||||
else
|
||||
for attempt in 1 2 3; do
|
||||
if timeout 300 git -c http.connectTimeout=15 -c http.lowSpeedLimit=1 -c http.lowSpeedTime=60 \
|
||||
fetch --depth=1 --no-tags origin "$GITEA_SHA"; then
|
||||
break
|
||||
fi
|
||||
[ "$attempt" -lt 3 ] || { echo "exact checkout of $GITEA_SHA failed after 3 bounded attempts" >&2; exit 1; }
|
||||
sleep $((attempt * 10))
|
||||
done
|
||||
fi
|
||||
git checkout --detach --force "$GITEA_SHA"
|
||||
- name: Record whether main is docs-only ahead of the last staging gate
|
||||
- name: Record which revision this run attests
|
||||
env:
|
||||
GITEA_API_URL: ${{ gitea.api_url }}
|
||||
GITEA_REPOSITORY: ${{ gitea.repository }}
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
GITEA_REF: ${{ gitea.ref }}
|
||||
RESOLVE_MODE: discover
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ "$GITEA_REF" == refs/heads/staging ]]; then
|
||||
# BUG-2390: automatic run after a staging deploy. It attests exactly the SHA that
|
||||
# passed the staging gate and is the current staging head; a superseded SHA stops here.
|
||||
api() {
|
||||
curl --fail --silent --show-error --connect-timeout 15 --max-time 60 --retry 3 --retry-all-errors \
|
||||
--header "Authorization: token $GITEA_TOKEN" "$GITEA_API_URL/repos/$GITEA_REPOSITORY/$1"
|
||||
}
|
||||
staging_head="$(api git/refs/heads/staging | jq -er 'select(type == "array" and length == 1) | .[0] |
|
||||
select(.ref == "refs/heads/staging") | .object.sha | select(test("^[0-9a-f]{40}$"))')"
|
||||
if [[ "$staging_head" != "$GITEA_SHA" ]] && ! bash deploy/is-docs-only-range.sh --api "$GITEA_SHA" "$staging_head"; then
|
||||
echo "staging moved on to $staging_head; this automatic release gate is superseded" >&2
|
||||
exit 1
|
||||
fi
|
||||
api "actions/runs?head_sha=$GITEA_SHA&branch=staging&event=push&status=success&limit=100" | jq -e --arg sha "$GITEA_SHA" '
|
||||
any(.workflow_runs[]?;
|
||||
(.path | split("@")[0] | endswith("backend-quality-gate.yml")) and
|
||||
.head_sha == $sha and .head_branch == "staging" and .event == "push" and .conclusion == "success")
|
||||
' >/dev/null || { echo "no successful staging quality gate for $GITEA_SHA" >&2; exit 1; }
|
||||
{
|
||||
echo "### Release revision"
|
||||
echo "- trigger: automatic, after the staging deploy"
|
||||
echo "- release_sha: ${GITEA_SHA}"
|
||||
} >>"$GITHUB_STEP_SUMMARY"
|
||||
exit 0
|
||||
fi
|
||||
bash deploy/resolve-release-revision.sh | tee "$RUNNER_TEMP/release-revision.env"
|
||||
release_sha="$(awk -F= '$1 == "release_sha" { print $2 }' "$RUNNER_TEMP/release-revision.env")"
|
||||
head_sha="$(awk -F= '$1 == "head_sha" { print $2 }' "$RUNNER_TEMP/release-revision.env")"
|
||||
[[ "$GITEA_SHA" == "$head_sha" ]] || { echo "dispatch the release gate from current main" >&2; exit 1; }
|
||||
{
|
||||
echo "### Release revision"
|
||||
echo "- trigger: manual, from main"
|
||||
echo "- head_sha: ${head_sha}"
|
||||
echo "- release_sha: ${release_sha}"
|
||||
echo "- H relative to R is docs-only (is-docs-only-range.sh exited 0)"
|
||||
|
||||
+1
-1
@@ -144,7 +144,7 @@ It fails while `frontend/src/lib/legal-entity.ts` still holds placeholder operat
|
||||
|
||||
## Manual production deployment with Gitea Actions
|
||||
|
||||
GitHub production deployment is retired. Production changes are released only by manually dispatching `.gitea/workflows/deploy-production.yml`. `main` must be a fast-forward to the current staging head `H`. The deployed SHA is `R`, the latest successful staging push of `backend-quality-gate`, and `deploy/is-docs-only-range.sh R H` must exit 0 (exit 1 or 2 both refuse). Controller artifacts and image digests come from `R`. Public staging health must report `R`. The manual release gate may record `H` when `H` is docs-only ahead of `R`. Rollback still requires an explicit confirmation, a gate run, and ancestry inside reviewed `main` history. The workflow deploys immutable registry digests and never builds application images on the production host.
|
||||
GitHub production deployment is retired. Production changes are released only by manually dispatching `.gitea/workflows/deploy-production.yml`. `main` must be a fast-forward to the current staging head `H`. The deployed SHA is `R`, the latest successful staging push of `backend-quality-gate`, and `deploy/is-docs-only-range.sh R H` must exit 0 (exit 1 or 2 both refuse). Controller artifacts and image digests come from `R`. Public staging health must report `R`. The full release gate (`release-quality-gate.yml`) must have succeeded for `R` or `H`. Since BUG-2390 (owner 2026-11-25) Deploy staging queues it automatically on `refs/heads/staging` after every successful staging deploy, so it normally exists before the owner approves a release and is not rerun from `main`; a newer staging deploy cancels an older queued run. If that run was cancelled or failed for an environment reason, dispatch the workflow manually from `main` (it may record `H` when `H` is docs-only ahead of `R`). Rollback still requires an explicit confirmation, a gate run, and ancestry inside reviewed `main` history. The workflow deploys immutable registry digests and never builds application images on the production host.
|
||||
|
||||
The `internal` verification mode is for pre-DNS checks on the new host. The `public` mode is for the same SHA after authoritative DNS and Caddy TLS converge. Neither mode imports data, applies pending migrations, or changes DNS.
|
||||
|
||||
|
||||
@@ -7,7 +7,8 @@
|
||||
# Discover mode (RESOLVE_MODE=discover): R is the newest such push whose range
|
||||
# to H is docs-only.
|
||||
# CHECK_RELEASE_GATE=true also requires a successful release-quality-gate
|
||||
# dispatch whose head is R or H.
|
||||
# dispatch whose head is R or H: the automatic run Deploy staging queues after
|
||||
# each staging deploy, or a manual run from main (BUG-2390).
|
||||
#
|
||||
# stdout is three KEY=VALUE lines: release_sha, gate_run_id, head_sha.
|
||||
# Exit 0 accepted, 1 refused, 2 when the Gitea API cannot be read.
|
||||
@@ -191,7 +192,7 @@ PY
|
||||
fi
|
||||
done
|
||||
if [ "$found" != true ]; then
|
||||
echo "no successful manual release quality gate found for the release SHA or current main" >&2
|
||||
echo "no successful full release quality gate found for the release SHA or current main (it runs after each staging deploy; dispatch it from main if that run was cancelled)" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -32439,3 +32439,75 @@
|
||||
- **防复发**:`tests/test_parivartana_classes_2388.py`、`frontend/tests/chart-yoga-parivartana-2388.test.ts`。
|
||||
- **关联记录**:BUG-2387(同一张盘的落陷卡)、BUG-1572(王者互换此前从未触发)、BUG-1975 / BUG-2218(规则级主题映射冻结)。
|
||||
- **修复版本**:1.4(staging)。
|
||||
|
||||
## BUG-2392 | 占星师 2026-11-25 九项复核第四至八项:Raja 结构满足仍显示候选、互换不按实际宫位召回领域、示意图冒充本盘实际图
|
||||
|
||||
- **状态**:resolved(本地提交,staging 待推)
|
||||
- **现象**:负责人转来占星师对九项的复核(`/workspace/eval-read-1116/astrologer-replies/yoga-kp-9items-20261125.md`)。①角宫主与三方宫主互换等 Raja 结构在盘上满足,引擎一律给 `candidate`(`source_definition_not_reviewed`),星盘页不显示、问答卡读作候选;②三类互换没有领域归属(主题表 unmapped),问答按领域召回不到;③约 90 条自定义规则不记录参与星,星盘页按规则句子推断出的图看起来像本盘实际成立的配置;④她担心月亮自身落陷时的有效缓解被当成自我参照排除。
|
||||
- **触发条件**:任一盘上 kendra–trikona 宫主关系的 Raja 规则命中;问婚恋/事业/财富等领域时盘上有互换;自定义规则命中而无参与星。
|
||||
- **根因**:①`assess_yoga_formation` 只有带审过定义的规则才能 `formed_under_source`,Raja 结构类规则没有合同;②领域召回只有关键词主题表,互换没有按交换宫位的检索规则;③自定义表达式命中后不写 `participants_expr` 时引擎不记参与星,前端用 BUG-2387 的推断画图,未标明是示意;④核查后引擎本身已按她的定义处理(只有见证星与参照点都是月亮才算 `self_reference`),月亮落天蝎、火星在月亮起第四宫是有效缓解——没有排除,补回归测试锁住。
|
||||
- **修复**:
|
||||
- `scripts/yoga_engine.py`(冻结文件,负责人 2026-11-25 逐项批准第四、五、六、八项):新增 `RAJA_STRUCTURAL_RULES`(11 条角宫主/三方宫主结构规则)的产品成立合同 `kendra_trikona_lord_structure`:D1、几何一致、`lord_structure`(参与星各管至少一个角宫或三方宫)满足即 `formed_under_source`;参与宫主兼管第 6/8/12 宫写进 `formation_modifiers` 与 `formation_note_zh`(「实际作用有利有弊:木星同时管第 6 宫,土星同时管第 8 宫。」),不降级、不写待核。`_assess_product_contract` 允许合同以规则自身的执行定义为定义(`definition: None`)。
|
||||
- `references/yoga_rules.json`:dhana_yoga、grahi_dhana、vipreet_pairs、bvr_bahu_sthree_yoga 加 `participants_expr`,写明实际命中分支的参与星。
|
||||
- 星盘页 `chart-yoga-groups.ts`:成立卡读 `formation_note_zh` 接在条件句后;引擎没给参与星、靠规则句子推断出的图,图注前加「示意:」,引擎给了参与星的画本盘实际配置(整盘类分布图、宫主链不加)。
|
||||
- 问答卡 `consultation-evidence-card.ts`:新召回理由 `exchange_houses`——按实际交换的两宫召回领域(事业 10 + 6/7/2/11;财富 2、11 + 8/12;婚恋 5、7 + 2/8;健康 1/6/8/12;家庭 4、3;父母 4;学业 5/9;迁移 9/12;一宫是核心宫或两宫都在核心+辅助宫内),是检索规则不是结论;同一对互换星的第二条规则标 `same_exchange_as`,不算多一份支持;模型可见的选取说明补了这两项。
|
||||
- **验证**:Python 新测 `tests/test_yoga_review_2392.py` 5 条;yoga/neecha/parivartana/formation 全部 Python 测试 667 通过;2324 英文泄漏测试 3 条通过;前端新测 `frontend/tests/yoga-review-2392.test.ts` 5 条;consult/chart/yoga/evidence 前端测试 1399 通过;tsc 无错;改动文件 ESLint 0 错。
|
||||
- **防复发**:`test_yoga_instances_gana_2075` 参与星规则计数 32 → 36(原值/新值/原因已注);新测试锁住 Raja 成立与修正句、月亮落陷缓解不被排除、只有月亮自参照才算恒真、互换按两宫召回且同一互换只算一份、示意图标注。
|
||||
- **未做(如实)**:其余约 140 条自定义规则仍没有 `participants_expr`,它们的图继续按句子推断并标「示意」;报告端(jyotisha-10)未读 `formation_note_zh`,需要报告窗口决定是否展示。
|
||||
- **关联记录**:BUG-2387、BUG-2388、BUG-2353/2354(第九项,问答窗口)、BUG-2027、BUG-2301。
|
||||
|
||||
## BUG-2390 | 发布前在同一个 SHA 上把完整检查再跑一遍,正式发布多等约 25 分钟
|
||||
|
||||
- **状态**:resolved(分支 `claude/ci-speed-2390`,待推)
|
||||
- **现象**:staging 每次推送只跑快速检查;正式发布前还要从 main 手动触发 Release Quality Gate,在同一个 SHA 上跑完整 release 档 + run_all(约 29 分钟,单台 runner),正式发布总共约 45 分钟。
|
||||
- **触发条件**:每一次正式发布。
|
||||
- **根因**:完整检查只能在批准发布之后、从 main 手动触发;而 staging 部署成功时那个 SHA 已经确定,可以提前跑。
|
||||
- **修复**:Deploy staging 成功(非回滚)后自动在 `refs/heads/staging` 上触发 `release-quality-gate.yml`,不阻塞 staging、触发失败只记 warning。发布检查的自动运行只认当前 staging 头(或纯文档前进)且该 SHA 的 staging 门禁已成功,否则以「superseded」退出;`concurrency: release-quality-${{ gitea.ref }}` + `cancel-in-progress` 让新的 staging 部署取消旧的排队运行。生产四个工作流沿用 `CHECK_RELEASE_GATE=true`:按 `head_sha` 找成功的 release-quality-gate 运行,自动运行与手动运行都算;从 main 手动触发保留为兜底。其余安全条件(main == staging、公网 staging 报同一 SHA、只用门禁产物里的镜像摘要)不变。
|
||||
- **验证**:staging-backend-workflows 合同测试按原值/新值/原因更新(本机 43 过,3 条因缺 yaml 模块 / rsync 失败,与改动前相同);所有工作流 YAML 用 venv 里的 PyYAML 解析通过;tests/test_resolve_release_revision.py、tests/test_beta_safety_net.py 通过。
|
||||
- **防复发**:合同测试钉住自动触发步骤、并发组、superseded 检查和 staging 门禁校验。
|
||||
- **关联记录**:BUG-2000、BUG-1998(发布检查内容)、AGENTS.md §0 第 6 条。
|
||||
- **修复版本**:1.5(待发)。
|
||||
|
||||
## BUG-2391 | 正式部署约 13 分钟里 11–12 分钟花在拉完整 git 历史
|
||||
|
||||
- **状态**:resolved(分支 `claude/ci-speed-2390`,待推)
|
||||
- **现象**:deploy-production 运行 8573、8583 各约 13 分钟;日志里 `git init` 之后到 `From https://git.copse.top/...` 之间分别空等 682 秒、711 秒。发布检查 8582 同一步空等 654 秒,恢复点和生产迁移工作流也是同样的取法(恢复点里取两次)。
|
||||
- **触发条件**:每次运行这四个工作流:deploy-production、release-quality-gate、create-production-recovery、migrate-production-database。
|
||||
- **根因**:这几个工作流用 `git fetch --no-tags origin "$SHA"` 不带 `--depth`,在空仓库里会拉下整个历史;staging 门禁早已改成先读 runner 上的裸镜像、再有时限浅取,这几个没有跟上。它们只用到被检出的那一个提交(是否纯文档前进走 Gitea compare API)。
|
||||
- **修复**:五处取提交都改为:runner 上的裸镜像 `/root/.cache/jyotisha-mirror.git` 已有该 SHA 就从镜像取,否则做最多 3 次、每次 300 秒上限的 `--depth=1` 浅取。所有校验(SHA、门禁、公网 staging、镜像摘要、健康检查)不变。
|
||||
- **验证**:所有工作流 YAML 用 PyYAML 解析通过;新合同测试钉住这四个工作流不再出现不带 depth 的完整取法;staging-backend-workflows 本机 44 过、3 条环境失败与改动前相同;tests/test_resolve_release_revision.py、tests/test_beta_safety_net.py 通过。
|
||||
- **预计效果**:正式部署约 13 分钟 → 约 1.5–2 分钟;发布检查少约 11 分钟;恢复点和迁移各少约 10 分钟以上。
|
||||
- **关联记录**:BUG-2390;staging 门禁的镜像取法(backend-quality-gate.yml「Checkout exact Gitea revision」)。
|
||||
- **修复版本**:1.5(待发)。
|
||||
|
||||
## BUG-2389 | 站外可用性检查每次都跑满 5 分钟被取消(exit code -1),还占着发布用的 runner
|
||||
|
||||
- **状态**:resolved(分支 `claude/ci-speed-2390`,待推;工作流已在 Gitea 手动停用,修复上线后再启用)
|
||||
- **现象**:BUG-2348 加的 monitor-public-health.yml 上线后,运行 8689–8692 全部失败,日志在脚本开始后空等到 5 分钟上限,负责人看到「Error: this step has been cancelled: Process completed with exit code -1」。它每 5 分钟一次、每次占满 5 分钟,和 1.4 的发布检查抢同一台 runner。
|
||||
- **触发条件**:main 上每 5 分钟的定时运行。
|
||||
- **根因**:探针先 `git fetch --depth 1` 整个仓库再检出;在这台 runner 上整棵树浅取要 4–8 分钟(staging 门禁注释里早有记录),超过 5 分钟上限。健康检查脚本本身每个请求都有 10–15 秒上限,不是它卡住。
|
||||
- **修复**:只取两个监控脚本(runner 裸镜像里有该 SHA 就 `git show`,否则 Gitea raw API,每次请求 20 秒上限);`timeout-minutes` 5 → 3;cron 每 5 分钟 → 每 10 分钟;`cancel-in-progress: true`,新运行取代旧运行,不会排队压住发布。
|
||||
- **验证**:tests/test_monitor_alerts_2348.py 按原值/新值/原因更新并通过;工作流 YAML 解析通过;raw API 取脚本实测 1.8 秒。
|
||||
- **防复发**:测试钉住不再出现 `git fetch`、3 分钟上限、10 分钟间隔和取消旧运行。
|
||||
- **关联记录**:BUG-2348、BUG-2391(同样是整库取代码拖慢工作流)。
|
||||
- **修复版本**:1.5(待发);上线后在 Gitea 重新启用该工作流。
|
||||
|
||||
- **BUG-2390 跟进(2026-11-25)**:staging 52872d1af 部署后自动排队完整检查失败,dispatch 返回 403(「could not queue the full release checks」)。原因:`deploy-staging.yml` 的 `permissions.actions` 是 `read`,没有排队其他工作流的权限。改为 `actions: write`,`staging-backend-workflows` 加一条测试钉住。
|
||||
|
||||
## BUG-2393 | 问答回答里一条编号小标题被删,留下字面 `** `:「一、……」后面直接是「** 你的长处是……」,再接「三、……」
|
||||
|
||||
- 状态:fixed-pending-verify(分支 `claude/markdown-2393`,未推送;staging 真机未看)
|
||||
- 首次发现 / 最近更新:2026-11-25(负责人反馈「什么样的工作方式适合我」一问的回答)/ 2026-11-25
|
||||
- 影响面:问答回答的落库文本、复制内容与渲染(所有走 `remarkCjkStrong` 的视图:行首 / 行尾落单的 `**` 不再显示)。报告与报告追问不经过问答清理,正文不变。
|
||||
- 现象:第二条的加粗小标题连同「二、」一起不见,段首露出 `** `,正文从「你的长处是……」开始,后面仍是「三、」。
|
||||
- 触发条件:事业题(证据卡含 career)、用户没问台前 / 幕后,而编号小标题本身写了「幕后 / 台前 / 曝光度……」这类词,小标题里又有句号(`**二、……幕后……。** 正文……`)。同类:小标题含「回答里 / 不写成」等写法句时的 `dropMetaClauses`。
|
||||
- 根因(离线复现,未读任何账户或数据库数据):`frontend/src/lib/chat-answer-checks.ts` `dropNoteAndStageSentences`(BUG-1621 / BUG-2285 的台前幕后清理)按 。!? 切句,不看 Markdown:`**二、在幕后把事做好,不必抢台前。` 是一「句」,收尾的 `**` 被分到下一句开头;这一句被删后剩 `** 你的长处是……`。`isProtectedRemoval` 只保护结论句和不让一节变空,不管小标题。随后 `balanceStrongMarkers`(BUG-2248)本应删掉落单标记,但 `strong-markers.ts` `strayStrongIsText` 把「行首 / 行尾」算作空白,行首 `** ` 被当成作者有意写的文字保留,渲染层同样原样显示。`dropMetaClauses` 有同样的切法(复现:`**二、回答里不写成“反复”。** 戊己。` → `** 戊己。`);`dropRepeats` 同样切法,重复的加粗小标题会被删。
|
||||
- 修复:
|
||||
- 根因:`strong-markers.ts` 新增 `markdownSentences`:切句时加粗是一个整体,加粗里的 。!? 不断句,紧贴收尾 `**` 的句号把收尾一起带走;一行开头的编号加粗小标题(`**二、……**`、`- **……**`、`二、**……**`)和 `#` 标题标为 heading。`dropNoteAndStageSentences`、`dropRepeats`、`dropMetaClauses` 改用它:小标题从不被内容清理删掉——台前幕后词在小标题里时保留并交给补写调用(`stageRepair`),正文里的那句照删;重复的小标题不删;写法子句只删不含落单 `**` 的子句。`chat-answer-direct-reply.ts` `isProtectedRemoval` 加 `cutsBoldHeading`:删除会拿掉编号小标题却留下这一行其余文字时视为受保护(事实核对改按卡更正或保留,补漏层修复不删),整行删除仍允许。
|
||||
- `strayStrongIsText`:只有两边都是真空白(` ** `)或 ASCII 词内(`2**3`)才算文字;行首、行尾落单的 `**` 删掉、不显示(落库清理与渲染共用)。
|
||||
- 最后一道检查:新增 `frontend/src/lib/answer-markdown-sanity.ts` `sanitizeAnswerMarkdown`,在 `stream-agent-response.ts` 所有后处理(事实核对、清理、补漏层、西洋整形、依据补全、`keepWrittenReply`)之后、`acceptAnswer` 与落库之前运行:空加粗(`** **`、单独的 `****`)去掉标记;每行 `**` 成对;行首「一、二、三」编号按列表从首个数字起连续(`#` 标题或新的「一、」开始新列表),跳号补齐。确定性、无模型调用、幂等;有修改时记 `answer-markdown-sanity` 运行步骤与 `answerChecks.markdown.repairs`。
|
||||
- 验证:`frontend/tests/chat-markdown-heading-2393.test.tsx` 7 条(负责人那段的离线复现走 `cleanChatAnswer`;切句不切开加粗且拼回原文;写法子句与重复句清理保留小标题;事实核对删到小标题时保留、整行删除照常;行首 / 行尾落单 `**` 删掉且渲染无星号;最后检查修落单、空加粗、跳号且幂等、不碰两个列表 / 代码块 / `2**3`;流式顺序合同)。修复前该文件失败。改动文件相关的前端测试逐个跑;`tsc --noEmit`、`npx eslint .` 0 错误;sentence-split(无 lookbehind)与 no-middle-dot 守卫通过;quick gate。
|
||||
- 防复发:删句 / 改写的步骤一律用 `markdownSentences` 切句,不再自己按 。!? 切;小标题不属于内容清理的删除范围;最后一道 Markdown 检查兜住任何步骤留下的落单标记与跳号。
|
||||
- 关联记录:BUG-2248(落单 `**`;本次是其复发)、BUG-1621 / BUG-2285(台前幕后清理)、BUG-2241(写法子句清理)、BUG-2239 / BUG-1789(事实核对单元)、BUG-1610(CJK 加粗配对)。
|
||||
- 复发自:BUG-2248。其测试只覆盖删句后落单 `**` 在行中、两边不是空白的情形,并把「行首 / 行尾」当空白写进落单判定(本意是保留 ` ** `),没有「加粗小标题里有句号、整句被删、收尾标记后接空格」这一形状;台前幕后清理的测试也没有加粗小标题的样例。
|
||||
- 修复版本:分支 `claude/markdown-2393`(待父会话推送)。
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* BUG-2393: the last markdown check on a chat answer, after every post-processing step (fact guard, clean-up, repair,
|
||||
* Western shaping, basis completion, keepDirectReply) and before the answer is accepted, saved and sent as final.
|
||||
* Deterministic, no model call. It repairs only what no author means:
|
||||
* - an emptied bold span (「** **」, 「****」 standing alone) loses its markers;
|
||||
* - a `**` that pairs with nothing on its line goes (balanceStrongMarkers, incl. a lone 「** 」 at the start of a line);
|
||||
* - items numbered 一、二、三 at the start of their lines keep their order without gaps (「一、 …… 三、」 → 「一、 …… 二、」),
|
||||
* counting on from the list's first number;
|
||||
* one list ends at a `#` heading or a new 「一、」.
|
||||
* Each repair is listed in `repairs` so the run can record it. Running it twice changes nothing more.
|
||||
*/
|
||||
import { balanceStrongMarkers } from "./strong-markers.ts";
|
||||
|
||||
const FENCE = /^\s{0,3}(`{3,}|~{3,})/;
|
||||
const EMPTY_BOLD = /(^|[ \t])\*\*[ \t]*\*\*(?:[ \t]+|$)/gu;
|
||||
const DIGITS = ["", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
|
||||
|
||||
export function chineseNumeral(value: number): string {
|
||||
if (value < 10) return DIGITS[value] ?? "";
|
||||
const tens = Math.floor(value / 10);
|
||||
return `${tens === 1 ? "" : DIGITS[tens]}十${DIGITS[value % 10]}`;
|
||||
}
|
||||
|
||||
export function parseChineseNumeral(value: string): number | null {
|
||||
for (let candidate = 1; candidate < 100; candidate += 1) if (chineseNumeral(candidate) === value) return candidate;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** A line that opens a numbered item: optional list marker, optional opening `**`, then 「二、」. */
|
||||
const NUMBERED_ITEM = /^([ \t]*(?:[-*+][ \t]+)?(?:\*\*)?)([一二三四五六七八九十]{1,3})、/u;
|
||||
|
||||
function renumber(lines: string[], fenced: boolean[], repairs: string[]): void {
|
||||
let group: number[] = [];
|
||||
const flush = () => {
|
||||
if (group.length >= 2) {
|
||||
const first = parseChineseNumeral(NUMBERED_ITEM.exec(lines[group[0]!]!)![2]!)!;
|
||||
group.forEach((index, position) => {
|
||||
const match = NUMBERED_ITEM.exec(lines[index]!)!;
|
||||
const want = chineseNumeral(first + position);
|
||||
if (match[2] === want) return;
|
||||
repairs.push(`renumber:${match[2]}→${want}`);
|
||||
lines[index] = `${match[1]}${want}、${lines[index]!.slice(match[0].length)}`;
|
||||
});
|
||||
}
|
||||
group = [];
|
||||
};
|
||||
lines.forEach((line, index) => {
|
||||
if (fenced[index]) return;
|
||||
if (/^\s{0,3}#{1,6}(?:\s|$)/u.test(line)) { flush(); return; }
|
||||
const match = NUMBERED_ITEM.exec(line);
|
||||
const value = match ? parseChineseNumeral(match[2]!) : null;
|
||||
if (value === null) return;
|
||||
// A new 「一、」 starts a new list.
|
||||
if (value === 1) flush();
|
||||
group.push(index);
|
||||
});
|
||||
flush();
|
||||
}
|
||||
|
||||
export function sanitizeAnswerMarkdown(text: string): { output: string; repairs: string[] } {
|
||||
const repairs: string[] = [];
|
||||
let insideFence = false;
|
||||
const fenced: boolean[] = [];
|
||||
const lines = text.split("\n").map((line) => {
|
||||
if (FENCE.test(line)) {
|
||||
insideFence = !insideFence;
|
||||
fenced.push(true);
|
||||
return line;
|
||||
}
|
||||
fenced.push(insideFence);
|
||||
if (insideFence || !line.includes("**")) return line;
|
||||
return line.replace(EMPTY_BOLD, (hit, before: string) => {
|
||||
repairs.push("empty-bold");
|
||||
return before;
|
||||
});
|
||||
});
|
||||
renumber(lines, fenced, repairs);
|
||||
const bold = balanceStrongMarkers(lines.join("\n"));
|
||||
if (bold.removed) repairs.push(`lone-bold:${bold.removed}`);
|
||||
return { output: repairs.length ? bold.output : text, repairs };
|
||||
}
|
||||
@@ -318,6 +318,18 @@ function ruleDiagram(id: string, bodies: Record<string, Body>, rules: Record<str
|
||||
return found.length ? { kind: "set", bodies: found.slice(0, 4), label: found.map(zh).join("、") } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* BUG-2392 (占星师 11-25 第八项): the engine's matched participants draw this chart's actual configuration.
|
||||
* When the engine names none, the diagram is read from the rule's sentence (BUG-2387) and its caption says
|
||||
* it is an illustration of the rule, not the matched branch.
|
||||
*/
|
||||
function actualOrIllustration(row: Row, bound: string[], bodies: Record<string, Body>, rules: Record<string, number[]>): YogaDiagram {
|
||||
const diagram = rowDiagram(row, bound, bodies, rules);
|
||||
const wholeChart = diagram.kind === "spread" || diagram.kind === "chain" || diagram.kind === "none";
|
||||
if (bound.length || wholeChart) return diagram;
|
||||
return { ...diagram, label: `示意:${diagram.label}` };
|
||||
}
|
||||
|
||||
function rowDiagram(row: Row, bound: string[], bodies: Record<string, Body>, rules: Record<string, number[]> = {}): YogaDiagram {
|
||||
const category = String(row.category ?? "");
|
||||
const id = String(row.rule_id ?? "");
|
||||
@@ -436,8 +448,11 @@ export function buildYogaGroups(input: Readonly<{
|
||||
// A one-body yoga and a one-body structure on that body are the same fact (萨萨 and 7th lord in its own sign).
|
||||
if (planets.length === 1 && !formedPlanets.has(planets[0]!)) formedPlanets.set(planets[0]!, name);
|
||||
categories.set(id, String(row.category ?? ""));
|
||||
// BUG-2392 (占星师 11-25 第五项): a formed kendra–trikona Raja yoga keeps its modifier in plain words.
|
||||
const note = text(row.formation_note_zh);
|
||||
formed.push({
|
||||
id, group: "formed", name, alias, text: sentence, tags, same: false, planets, diagram: rowDiagram(row, planets, bodies, rules),
|
||||
id, group: "formed", name, alias, text: note ? `${sentence}。${note}`.replace(/。。/gu, "。") : sentence, tags, same: false, planets,
|
||||
diagram: actualOrIllustration(row, planets, bodies, rules),
|
||||
...(MINOR_CATEGORIES.has(String(row.category ?? "")) ? { minor: true } : {}),
|
||||
});
|
||||
}
|
||||
@@ -508,7 +523,7 @@ export function buildYogaGroups(input: Readonly<{
|
||||
id: `adverse:${key}`, group: "adverse", name, alias: null,
|
||||
text: `${conditionText(first)}${merged ? `。${merged}` : ""}`.replace(/。。/gu, "。"),
|
||||
tags: mitigations, same: false, planets,
|
||||
diagram: rowDiagram(first, planets, bodies, rules),
|
||||
diagram: actualOrIllustration(first, planets, bodies, rules),
|
||||
});
|
||||
}
|
||||
return { formed: [...formed.filter((card) => !card.minor), ...formed.filter((card) => card.minor)], support, adverse };
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* here too.
|
||||
*/
|
||||
import type { EvidenceCard } from "./consultation-evidence-card.ts";
|
||||
import { balanceStrongMarkers } from "./strong-markers.ts";
|
||||
import { balanceStrongMarkers, markdownSentences } from "./strong-markers.ts";
|
||||
import { isProtectedRemoval } from "./chat-answer-direct-reply.ts";
|
||||
|
||||
type Json = Record<string, unknown>;
|
||||
@@ -311,6 +311,7 @@ function sharesInstructionRun(sentence: string, notes: readonly string[]): boole
|
||||
/** Public / backstage and visibility claims (BUG-1621): the card says this chart does not show them. */
|
||||
const STAGE_CLAIM = /台前|幕前|幕后|不靠曝光|低显示度|高显示度|公众型|曝光度|抛头露面|聚光灯|站在前台|走到台前|低调地|不出名|名气(?:不大|有限|很大)/u;
|
||||
|
||||
/** Plain sentence split for the checks that only flag (no text is removed with it). */
|
||||
function splitSentences(text: string): string[] {
|
||||
return text.match(/[^。!?\n]+[。!?]?|\n/gu) ?? [];
|
||||
}
|
||||
@@ -341,13 +342,12 @@ export function dropNoteAndStageSentences(
|
||||
const stageRepair: string[] = [];
|
||||
const keptProtected: string[] = [];
|
||||
const asked = questionAsksStage(options.userText);
|
||||
let offset = 0;
|
||||
const kept = splitSentences(text).filter((sentence) => {
|
||||
const start = offset;
|
||||
offset += sentence.length;
|
||||
// BUG-2393: sentences never cut inside a bold span, and a numbered item's bold heading is never deleted (it was: 「**二、
|
||||
// ……幕后……。**」 went and left 「** 你的长处……」, item 二 without its number). A heading is kept and sent to the repair call.
|
||||
const kept = markdownSentences(text).filter(({ text: sentence, start, heading }) => {
|
||||
if (sentence === "\n" || !sentence.trim()) return true;
|
||||
if (/^\s*#/u.test(sentence)) return true;
|
||||
const protectedHere = () => isProtectedRemoval(text, start, start + sentence.length);
|
||||
const protectedHere = () => heading || isProtectedRemoval(text, start, start + sentence.length);
|
||||
if (META_SENTENCE.test(sentence) || sharesInstructionRun(sentence, notes)) {
|
||||
if (protectedHere()) { keptProtected.push(sentence.trim()); return true; }
|
||||
droppedNotes.push(sentence.trim());
|
||||
@@ -364,7 +364,7 @@ export function dropNoteAndStageSentences(
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return { output: kept.join("").replace(/\n{3,}/gu, "\n\n").replace(/^[ \t]*[-*][ \t]*$/gmu, ""), notes: droppedNotes, stage: droppedStage, stageRepair, kept: keptProtected };
|
||||
return { output: kept.map((unit) => unit.text).join("").replace(/\n{3,}/gu, "\n\n").replace(/^[ \t]*[-*][ \t]*$/gmu, ""), notes: droppedNotes, stage: droppedStage, stageRepair, kept: keptProtected };
|
||||
}
|
||||
|
||||
export type SahamRow = { name: string; sign: string; house: number | null };
|
||||
@@ -509,15 +509,16 @@ export function dropRepeats(text: string): { output: string; clauses: string[];
|
||||
const sentences: string[] = [];
|
||||
output = output.split("\n").map((line) => {
|
||||
if (/^\s*#/u.test(line)) return line;
|
||||
const parts = line.match(/[^。!?]+[。!?]?/gu) ?? [line];
|
||||
const kept = parts.filter((part) => {
|
||||
// BUG-2393: a bold span is not cut, and a repeated bold heading stays (only body sentences go).
|
||||
const parts = markdownSentences(line);
|
||||
const kept = parts.filter(({ text: part, heading }) => {
|
||||
const key = part.replace(/[\s*_]/gu, "").replace(/^[-•]/u, "");
|
||||
if (key.length < 14) return true;
|
||||
if (seen.has(key)) { sentences.push(part.trim()); return false; }
|
||||
if (seen.has(key) && !heading) { sentences.push(part.trim()); return false; }
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
return kept.join("");
|
||||
return kept.map((part) => part.text).join("");
|
||||
}).join("\n");
|
||||
output = output.replace(/^[ \t]*[-*][ \t]*$/gmu, "").replace(/\n{3,}/gu, "\n\n");
|
||||
return { output, clauses, sentences };
|
||||
@@ -741,15 +742,16 @@ export function dropMetaClauses(text: string): { output: string; dropped: string
|
||||
});
|
||||
// Per sentence: a sentence that opens with such a clause goes whole (「土星逆行不写成……,那只表示……」); otherwise only
|
||||
// the clauses that carry it (brackets kept whole).
|
||||
const sentences = out.match(/[^。!?]+[。!?]?/gu) ?? [out];
|
||||
out = sentences.map((sentence) => {
|
||||
// BUG-2393: sentences never cut inside a bold span; a numbered item's bold heading is never dropped whole (its clauses
|
||||
// may go, but a clause holding one `**` of a pair stays, so the markers stay paired).
|
||||
out = markdownSentences(out).map(({ text: sentence, heading }) => {
|
||||
if (!META_CLAUSE.test(sentence)) return sentence;
|
||||
const pieces = sentence.match(/(?:[^,;。!?((]|[((][^))]*[))])+[,;。!?]?/gu) ?? [sentence];
|
||||
const lead = /^\s*(?:[-*+]\s+)?(?:\*\*[^*]*\*\*[::]?\s*)?/u.exec(sentence)?.[0] ?? "";
|
||||
const firstText = pieces[0]!.slice(Math.min(lead.length, pieces[0]!.length));
|
||||
if (META_CLAUSE.test(firstText)) { dropped.push(sentence); return lead; }
|
||||
if (!heading && META_CLAUSE.test(firstText)) { dropped.push(sentence); return lead; }
|
||||
const kept = pieces.filter((piece) => {
|
||||
if (!META_CLAUSE.test(piece)) return true;
|
||||
if (!META_CLAUSE.test(piece) || (piece.split("**").length - 1) % 2 === 1) return true;
|
||||
dropped.push(piece);
|
||||
return false;
|
||||
}).join("");
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
* sentence of the body.
|
||||
*/
|
||||
import { ASK_USER_HEADING, ASK_USER_MAX_CHARS, FOLLOW_UP_HEADING, VERDICT_HEADING } from "./chat-answer-shape.ts";
|
||||
import { boldLeadSpan } from "./strong-markers.ts";
|
||||
import { GENERAL_NO_BIRTH_TIME_REFUSAL } from "./timing-output-guard.ts";
|
||||
|
||||
export type TextSpan = Readonly<{ start: number; end: number; text: string }>;
|
||||
@@ -85,6 +86,23 @@ function sectionAround(text: string, offset: number): { start: number; end: numb
|
||||
return { start: Math.min(start, text.length), end, heading };
|
||||
}
|
||||
|
||||
/**
|
||||
* BUG-2393: whether removing text[start, end) takes (part of) a numbered item's bold heading (「**二、……。**」) but leaves
|
||||
* the rest of its line: the item would lose its number and heading and could leave a lone `**`. Removing the whole line
|
||||
* is not this (the final markdown pass renumbers the items).
|
||||
*/
|
||||
function cutsBoldHeading(text: string, start: number, end: number): boolean {
|
||||
for (const item of lines(text)) {
|
||||
if (item.end < start) continue;
|
||||
if (item.start >= end) break;
|
||||
const lead = boldLeadSpan(item.line);
|
||||
if (!lead || start >= item.start + lead[1] || end <= item.start + lead[0]) continue;
|
||||
const rest = text.slice(item.start, Math.max(item.start, start)) + text.slice(Math.min(end, item.end), item.end);
|
||||
if (SUBSTANCE.test(rest)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether removing text[start, end) would take out the direct reply or leave its section (or, with no heading, the
|
||||
* whole answer) without any words. The steps that delete sentences ask this first and repair or keep instead.
|
||||
@@ -94,6 +112,7 @@ export function isProtectedRemoval(text: string, start: number, end: number): bo
|
||||
if (reply && start < reply.end && end > reply.start) return true;
|
||||
const section = sectionAround(text, start);
|
||||
if (section.heading && EVIDENCE_SECTIONS.has(section.heading)) return false;
|
||||
if (cutsBoldHeading(text, start, end)) return true;
|
||||
const left = text.slice(section.start, start) + text.slice(Math.min(end, section.end), section.end);
|
||||
return !SUBSTANCE.test(left.replace(/〔[^〔〕\n]*〕/gu, ""));
|
||||
}
|
||||
|
||||
@@ -3370,7 +3370,9 @@ export const EVIDENCE_CARD_YOGA_SELECTION_RULE = (
|
||||
"selection_reasons keeps every recall reason. direct: route_packet, domain_named, packet_domain, rule_topic (topic map "
|
||||
+ "pending the astrologer's review). dependency: an exchange or debilitation cancellation sharing a planet with a direct "
|
||||
+ "row (dependency_of); unrelated ones do not enter. weak: category alone, or a planet ruling a recall house "
|
||||
+ "(domain_house_lord; not used on whole-chart cards). Rows without a mapped topic are unmapped_rule_ids, never dropped."
|
||||
+ "(domain_house_lord; not used on whole-chart cards). Rows without a mapped topic are unmapped_rule_ids, never dropped. "
|
||||
+ "exchange_houses: a sign exchange recalled by the two houses it exchanges (exchanged_houses) — a recall rule, not a "
|
||||
+ "conclusion; same_exchange_as marks another rule on the same exchange, which is one piece of evidence, not extra support."
|
||||
);
|
||||
|
||||
export const EVIDENCE_CARD_YOGA_FIELD_RULE = (
|
||||
@@ -3388,7 +3390,45 @@ export const EVIDENCE_CARD_YOGA_COUNTS_RULE = (
|
||||
+ "hit_count > 1 is the same rule matched again, not independent support."
|
||||
);
|
||||
|
||||
const YOGA_DIRECT_REASONS = ["route_packet", "domain_named", "packet_domain", "rule_topic"] as const;
|
||||
const YOGA_DIRECT_REASONS = ["route_packet", "domain_named", "packet_domain", "rule_topic", "exchange_houses"] as const;
|
||||
|
||||
/**
|
||||
* BUG-2392 (占星师 2026-11-25 复核第四项): a sign-exchange row is retrieved for a domain by the two houses
|
||||
* actually exchanged on this chart — a retrieval rule, not a conclusion. 事业 10 + 6/7/2/11;财富 2、11 + 8/12;
|
||||
* 婚恋 5、7(+2/8);健康 1/6/8/12;居住 4;学习远行 5/9;手足沟通 3. One exchange is one row of evidence:
|
||||
* other rows on the same two planets are marked `same_exchange_as`, never counted as extra support.
|
||||
*/
|
||||
export const EXCHANGE_DOMAIN_HOUSES: Readonly<Partial<Record<ConsultationDomain, Readonly<{ core: readonly number[]; extra: readonly number[] }>>>> = {
|
||||
career: { core: [10], extra: [6, 7, 2, 11] },
|
||||
wealth: { core: [2, 11], extra: [8, 12] },
|
||||
marriage: { core: [5, 7], extra: [2, 8] },
|
||||
health: { core: [1, 6, 8, 12], extra: [] },
|
||||
family: { core: [4, 3], extra: [] },
|
||||
parents: { core: [4], extra: [] },
|
||||
education: { core: [5, 9], extra: [] },
|
||||
migration: { core: [9, 12], extra: [] },
|
||||
};
|
||||
|
||||
/** A domain recalls an exchange when one exchanged house is its core house, or both are among its core and extra houses. */
|
||||
export function exchangeRecalledFor(domain: ConsultationDomain, houses: readonly number[]): boolean {
|
||||
const spec = EXCHANGE_DOMAIN_HOUSES[domain];
|
||||
if (!spec || houses.length !== 2) return false;
|
||||
const all = [...spec.core, ...spec.extra];
|
||||
return houses.some((house) => spec.core.includes(house)) || houses.every((house) => all.includes(house));
|
||||
}
|
||||
|
||||
/** The two houses a sign-exchange row exchanges: the engine's house_class check, else its `exchange` places. */
|
||||
export function exchangedHouses(row: Record<string, unknown>): number[] {
|
||||
for (const check of Array.isArray(row.formation_checks) ? row.formation_checks as Json[] : []) {
|
||||
const value = record(check);
|
||||
if (value.id === "house_class") {
|
||||
const houses = record(value.witness).houses;
|
||||
if (Array.isArray(houses)) return houses.filter((h): h is number => typeof h === "number");
|
||||
}
|
||||
}
|
||||
const places = Object.values(record(row.exchange)).map((place) => record(place).house).filter((h): h is number => typeof h === "number");
|
||||
return places.length === 2 ? places : [];
|
||||
}
|
||||
type YogaReason = typeof YOGA_DIRECT_REASONS[number] | "dependency" | "category" | "domain_house_lord";
|
||||
|
||||
function yogaCategory(row: Record<string, unknown>): string | undefined {
|
||||
@@ -3468,6 +3508,11 @@ export function selectEvidenceCardYogaDetail(
|
||||
if (typeof row.name === "string" && named.has(row.name)) out.push("domain_named");
|
||||
if (typeof row.packet_domain === "string" && tags.has(row.packet_domain)) out.push("packet_domain");
|
||||
if (stringList(row.rule_topics).some((topic) => topics.has(topic))) out.push("rule_topic");
|
||||
const exchanged = exchangedHouses(row);
|
||||
if (!whole && exchanged.length === 2
|
||||
&& scope.domains.some((domain) => exchangeRecalledFor(domain, exchanged))) {
|
||||
out.push("exchange_houses");
|
||||
}
|
||||
return out;
|
||||
};
|
||||
const rows = [...unique.values()];
|
||||
@@ -3518,7 +3563,18 @@ export function selectEvidenceCardYogaDetail(
|
||||
chosen.sort((a, b) => rank[a.relevance] - rank[b.relevance] || String(a.row.rule_id).localeCompare(String(b.row.rule_id)));
|
||||
let detailCount = 0;
|
||||
let indexCount = 0;
|
||||
// BUG-2392: one exchange (two planets in each other's signs) is one piece of evidence however many rules name it.
|
||||
const exchangeFirst = new Map<string, string>();
|
||||
const exchangeKey = (row: Record<string, unknown>) => {
|
||||
const pair = Object.keys(record(row.exchange));
|
||||
const bound = pair.length === 2 ? pair : exchangedHouses(row).length === 2
|
||||
? (Array.isArray(row.planets) ? stringList(row.planets) : Object.keys(record(row.planets))) : [];
|
||||
return bound.length === 2 ? [...bound].sort().join(":") : "";
|
||||
};
|
||||
const outRows: Json[] = chosen.map(({ row, reasons, relevance, dependencyOf }) => {
|
||||
const exchangeOf = exchangeKey(row);
|
||||
const sameExchange = exchangeOf && exchangeFirst.has(exchangeOf) ? exchangeFirst.get(exchangeOf) : undefined;
|
||||
if (exchangeOf && !exchangeFirst.has(exchangeOf)) exchangeFirst.set(exchangeOf, String(row.rule_id));
|
||||
const common: JsonRecord = {
|
||||
// BUG-1976 / BUG-1978: rule id + layer; the method version is the snapshot's (yoga_id on the Python side).
|
||||
// BUG-1988: a per-planet rule (Neecha Bhanga main detector) keeps one row and one id per planet.
|
||||
@@ -3533,12 +3589,15 @@ export function selectEvidenceCardYogaDetail(
|
||||
...(dependencyOf ? { dependency_of: dependencyOf } : {}),
|
||||
...yogaTemporal(row),
|
||||
...(Number(row.hit_count ?? 1) > 1 ? { hit_count: Number(row.hit_count) } : {}),
|
||||
...(reasons.includes("exchange_houses") ? { exchanged_houses: exchangedHouses(row) as unknown as Json } : {}),
|
||||
...(sameExchange ? { same_exchange_as: sameExchange } : {}),
|
||||
};
|
||||
// Detail when the row bears on this question: a route packet, a domain section or the packet names it,
|
||||
// a dependency of such a row, or (single-domain cards) the rule's own topic. On a whole-chart card a
|
||||
// topic match alone is an index unless a participating planet runs a current period.
|
||||
const strong = reasons.some((r) => r === "route_packet" || r === "domain_named" || r === "packet_domain");
|
||||
const topicDetail = reasons.includes("rule_topic") && (!whole || stringList(row.running_dasha_levels).length > 0);
|
||||
const topicDetail = (reasons.includes("rule_topic") || reasons.includes("exchange_houses"))
|
||||
&& (!whole || stringList(row.running_dasha_levels).length > 0);
|
||||
const asIndex = relevance === "weak" || (relevance === "direct" && !strong && !topicDetail);
|
||||
if (asIndex) {
|
||||
indexCount += 1;
|
||||
|
||||
@@ -33,6 +33,7 @@ import { checkDayCalendar, dayCalendarShape, dayPanelTexts } from "./chat-day-ca
|
||||
import { bodyStripDateFlags, bodyStripDisagreements, datedWindow, programStretches, serverAnswerShape, timelineRequirement, timelineSectionFromReply, timelineSectionPrompt, withProgramBestTime, withTimelineSection } from "./chat-answer-timeline.ts";
|
||||
import { addImpliedKeys, bodyMechanismSentences, bodyTerms, checkBodyDirection, checkDirection, checkStripTone, checkTimelineEntries, expandEvidenceKeys, hasEvidenceTags, unkeyedConclusions } from "./chat-evidence-keys.ts";
|
||||
import { chineseNamesAndTerms, cleanChatAnswer } from "./chat-answer-checks.ts";
|
||||
import { sanitizeAnswerMarkdown } from "./answer-markdown-sanity.ts";
|
||||
import { isProtectedRemoval, keepDirectReply } from "./chat-answer-direct-reply.ts";
|
||||
import { answerRepairPlan, answerRepairPrompt, applyAnswerRepair, parseAnswerRepair, withoutFailingFixes } from "./chat-answer-repair.ts";
|
||||
import {
|
||||
@@ -1692,6 +1693,23 @@ export function streamAgentResponse(options: StreamAgentResponseOptions) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* BUG-2393: the last step before the answer is accepted and saved: balanced `**`, no emptied bold, numbered items in
|
||||
* order (answer-markdown-sanity.ts). Deterministic; a repair is recorded. Any error keeps the answer as it stands.
|
||||
*/
|
||||
function finalMarkdownCheck(controller: ReadableStreamDefaultController<Uint8Array> | undefined) {
|
||||
try {
|
||||
const result = sanitizeAnswerMarkdown(fullOutput);
|
||||
if (!result.repairs.length || result.output === fullOutput) return;
|
||||
options.state.answerChecks = { ...options.state.answerChecks, markdown: { repairs: result.repairs } };
|
||||
appendConsultationRuntimeStep(options.state, { kind: "validation", name: "answer-markdown-sanity", status: "completed", failureCode: result.repairs.join(";").slice(0, 120) });
|
||||
fullOutput = result.output;
|
||||
send(controller, { type: "answer.delta", text: fullOutput, replace: true });
|
||||
} catch {
|
||||
// Keep the answer as it stands.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* BUG-2306: one line per failed run saying which failure is behind the sentence the user saw. Every unclassified
|
||||
* failure (model stream error, settlement error, any other throw) shows the same 「咨询暂时无法完成,本次不会扣点。」,
|
||||
@@ -1852,6 +1870,7 @@ export function streamAgentResponse(options: StreamAgentResponseOptions) {
|
||||
await guardInternalWords(controller);
|
||||
completeBasis(controller);
|
||||
keepWrittenReply(controller, written);
|
||||
finalMarkdownCheck(controller);
|
||||
const rejected = options.acceptAnswer?.(fullOutput) ?? null;
|
||||
if (rejected) {
|
||||
appendConsultationRuntimeStep(options.state, {
|
||||
|
||||
@@ -22,9 +22,13 @@ export function canCloseStrong(before: string): boolean {
|
||||
return before !== "" && !WHITESPACE.test(before) && before !== "*";
|
||||
}
|
||||
|
||||
/** An unpaired `**` the author meant as text: between spaces / line edges, or inside an ASCII token. */
|
||||
/**
|
||||
* An unpaired `**` the author meant as text: between spaces, or inside an ASCII token.
|
||||
* 原值:行首 / 行尾也算「空白」,`** 你的长处……` 这样的落单开头被当成文字保留;新值:只有两边都是真空白才算文字;
|
||||
* 原因:BUG-2393,事业清理删掉粗体小标题后剩下行首 `** `,落库与渲染都露出星号。
|
||||
*/
|
||||
export function strayStrongIsText(before: string, after: string): boolean {
|
||||
const open = (char: string) => char === "" || WHITESPACE.test(char);
|
||||
const open = (char: string) => char !== "" && WHITESPACE.test(char);
|
||||
if (open(before) && open(after)) return true;
|
||||
return ASCII_WORD.test(before) && ASCII_WORD.test(after);
|
||||
}
|
||||
@@ -48,9 +52,10 @@ export function strongDelimiterOffsets(value: string): number[] {
|
||||
* offsets of the ones that pair with nothing. `masked` is the text with code
|
||||
* spans and link targets blanked out, so their asterisks are never counted.
|
||||
*/
|
||||
function strayDelimiters(masked: string): number[] {
|
||||
function pairLine(masked: string): { pairs: Array<[number, number]>; stray: number[] } {
|
||||
const offsets = strongDelimiterOffsets(masked);
|
||||
const stray: number[] = [];
|
||||
const pairs: Array<[number, number]> = [];
|
||||
let open = -1;
|
||||
for (const offset of offsets) {
|
||||
if (open !== -1 && masked.slice(open + 2, offset).includes("*")) {
|
||||
@@ -61,6 +66,7 @@ function strayDelimiters(masked: string): number[] {
|
||||
const before = offset > 0 ? masked[offset - 1]! : "";
|
||||
const after = masked[offset + 2] ?? "";
|
||||
if (open !== -1 && canCloseStrong(before) && offset > open + 2) {
|
||||
pairs.push([open, offset + 2]);
|
||||
open = -1;
|
||||
} else {
|
||||
if (open !== -1) stray.push(open);
|
||||
@@ -69,7 +75,11 @@ function strayDelimiters(masked: string): number[] {
|
||||
}
|
||||
}
|
||||
if (open !== -1) stray.push(open);
|
||||
return stray.filter((offset) => !strayStrongIsText(offset > 0 ? masked[offset - 1]! : "", masked[offset + 2] ?? ""));
|
||||
return { pairs, stray };
|
||||
}
|
||||
|
||||
function strayDelimiters(masked: string): number[] {
|
||||
return pairLine(masked).stray.filter((offset) => !strayStrongIsText(offset > 0 ? masked[offset - 1]! : "", masked[offset + 2] ?? ""));
|
||||
}
|
||||
|
||||
const FENCE = /^\s{0,3}(`{3,}|~{3,})/;
|
||||
@@ -124,3 +134,66 @@ export function balanceStrongMarkers(text: string): { output: string; removed: n
|
||||
});
|
||||
return { output: removed ? lines.join("\n") : text, removed };
|
||||
}
|
||||
|
||||
// ---- BUG-2393: bold spans are atomic for the steps that cut sentences -------------------------------------------------
|
||||
|
||||
/** The bold spans of one line as [start, end) with their markers (code spans and link targets ignored). */
|
||||
export function boldSpans(line: string): Array<[number, number]> {
|
||||
if (!line.includes("**")) return [];
|
||||
return pairLine(maskInline(line)).pairs;
|
||||
}
|
||||
|
||||
const LEAD_BEFORE_BOLD = /^[ \t]*(?:[-*+>][ \t]+|\d{1,2}[.、)][ \t]*)?(?:第?[一二三四五六七八九十]{1,3}[、,,.][ \t]*)?/u;
|
||||
|
||||
/**
|
||||
* A numbered item's bold heading at the start of a line (「**二、……。**」, 「- **合同写细。**」, 「二、**……**」): [0, end of
|
||||
* its closing marker), so the list marker and the number count as part of it. Null when the line does not open with one.
|
||||
*/
|
||||
export function boldLeadSpan(line: string): [number, number] | null {
|
||||
const lead = LEAD_BEFORE_BOLD.exec(line)?.[0].length ?? 0;
|
||||
if (!line.startsWith("**", lead)) return null;
|
||||
const span = boldSpans(line).find(([start]) => start === lead);
|
||||
return span ? [0, span[1]] : null;
|
||||
}
|
||||
|
||||
export type MarkdownSentence = Readonly<{ text: string; start: number; heading: boolean }>;
|
||||
|
||||
const SENTENCE_END = /[。!?]/u;
|
||||
|
||||
/**
|
||||
* Sentences of `text` for the steps that delete or rewrite whole sentences: like splitting after 。!? (each line break its
|
||||
* own unit), except that a bold span is never cut. A 。!? inside a bold span ends no sentence, and one right before the
|
||||
* closing `**` takes the marker with it. `heading` marks the unit that holds a line's bold heading (boldLeadSpan) or a
|
||||
* `#` heading line: content clean-ups never delete those. The units joined give `text` back unchanged.
|
||||
*/
|
||||
export function markdownSentences(text: string): MarkdownSentence[] {
|
||||
const out: MarkdownSentence[] = [];
|
||||
let lineStart = 0;
|
||||
text.split("\n").forEach((line, index) => {
|
||||
if (index > 0) {
|
||||
out.push({ text: "\n", start: lineStart - 1, heading: false });
|
||||
}
|
||||
const spans = boldSpans(line);
|
||||
const lead = /^\s*#/u.test(line) ? [0, line.length] : boldLeadSpan(line);
|
||||
let from = 0;
|
||||
const cut = (to: number) => {
|
||||
if (to <= from) return;
|
||||
out.push({ text: line.slice(from, to), start: lineStart + from, heading: Boolean(lead && from < lead[1] && to > lead[0]) });
|
||||
from = to;
|
||||
};
|
||||
for (let at = 0; at < line.length; at += 1) {
|
||||
if (!SENTENCE_END.test(line[at]!)) continue;
|
||||
let end = at + 1;
|
||||
const inside = spans.find(([start, close]) => start < end && end < close);
|
||||
if (inside) {
|
||||
if (end !== inside[1] - 2) continue;
|
||||
end = inside[1];
|
||||
}
|
||||
cut(end);
|
||||
at = end - 1;
|
||||
}
|
||||
cut(line.length);
|
||||
lineStart += line.length + 1;
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -503,7 +503,7 @@ export type ConsultationRuntimeState = {
|
||||
/** BUG-2229: what the deterministic clean-up and the layer repair did to this answer (records only). */
|
||||
/** BUG-2281: lit chart areas and one-year strip tones, derived from the answer's evidence keys; goes on the receipt. */
|
||||
answerShape?: AnswerShapeData;
|
||||
answerChecks?: { steps?: unknown; flags?: number; asked?: string[]; optionalNotMentioned?: string[]; repair?: Record<string, number>; plainBody?: Record<string, unknown>; directReply?: { restored: string[]; deletions: string[] }; timeline?: Record<string, unknown>; dayCalendar?: { mentioned: number; conflicts: string[] }; western?: Record<string, unknown> };
|
||||
answerChecks?: { steps?: unknown; flags?: number; asked?: string[]; optionalNotMentioned?: string[]; repair?: Record<string, number>; plainBody?: Record<string, unknown>; directReply?: { restored: string[]; deletions: string[] }; timeline?: Record<string, unknown>; dayCalendar?: { mentioned: number; conflicts: string[] }; western?: Record<string, unknown>; markdown?: { repairs: string[] } };
|
||||
};
|
||||
|
||||
export function createConsultationRuntimeState(options: { plannedSteps?: number; reservedValidationSteps?: number } = {}): ConsultationRuntimeState {
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import test from "node:test";
|
||||
import React from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
import { renderChatMarkdown } from "../src/components/chat-markdown-view.tsx";
|
||||
import { sanitizeAnswerMarkdown } from "../src/lib/answer-markdown-sanity.ts";
|
||||
import { cleanChatAnswer, dropMetaClauses, dropNoteAndStageSentences, dropRepeats } from "../src/lib/chat-answer-checks.ts";
|
||||
import { isProtectedRemoval } from "../src/lib/chat-answer-direct-reply.ts";
|
||||
import { applyFactRepair, factGuardUnits, type AnswerFactMismatch } from "../src/lib/consultation-answer-fact-guard.ts";
|
||||
import type { EvidenceCard } from "../src/lib/consultation-evidence-card.ts";
|
||||
import { balanceStrongMarkers, markdownSentences } from "../src/lib/strong-markers.ts";
|
||||
|
||||
// BUG-2393: a 「what way of working suits me」 answer rendered 「一、……」, then 「** 你的长处是把事做对、做稳……」, then 「三、……」.
|
||||
// The career clean-up (dropNoteAndStageSentences, BUG-1621 / BUG-2285) split sentences after 。 without looking at
|
||||
// markdown, so item 二's bold heading 「**二、……幕后……。」 was one 「sentence」 and its closer 「**」 started the next; the
|
||||
// heading went and 「** 你的长处……」 was left. balanceStrongMarkers kept that `**` because a line edge counted as a space.
|
||||
|
||||
const CARD = { domains: ["career"] } as unknown as EvidenceCard;
|
||||
const EMPTY_CARD = { base: { natal: {}, timing: {} }, domain_sections: {} } as unknown as EvidenceCard;
|
||||
const ANSWER = [
|
||||
"## 结论",
|
||||
"",
|
||||
"独立做事最适合你。",
|
||||
"",
|
||||
"**一、有一个自己的摊子,节奏自己定。** 你不喜欢被人排班。",
|
||||
"",
|
||||
"**二、在幕后把事做好,不必抢台前。** 你的长处是把事做对、做稳,让人回头找你。把手上的活做深。",
|
||||
"",
|
||||
"**三、一对一地谈,或者带一个很小的组。** 人多了你累。",
|
||||
"",
|
||||
].join("\n");
|
||||
const html = (markdown: string) => renderToStaticMarkup(<>{renderChatMarkdown(markdown)}</>);
|
||||
const visible = (markup: string) => markup.replace(/<[^>]+>/g, "");
|
||||
|
||||
test("the career clean-up keeps item 二's bold heading whole and sends it to the repair call", () => {
|
||||
// 原值:输出含「\n\n** 你的长处是把事做对、做稳……」(小标题连同「二、」被删,留下行首 `** `);新值:小标题原样保留,交给补写;原因:BUG-2393。
|
||||
const result = cleanChatAnswer(ANSWER, CARD);
|
||||
assert.match(result.output, /\*\*二、在幕后把事做好,不必抢台前。\*\* 你的长处是把事做对/);
|
||||
assert.doesNotMatch(result.output, /^\*\* /mu);
|
||||
assert.deepEqual(result.record.stageDropped, []);
|
||||
assert.ok(result.record.stageRepair.some((sentence) => sentence.startsWith("**二、")));
|
||||
// A stage sentence in the item's body still goes, the heading stays.
|
||||
const body = dropNoteAndStageSentences("**二、把事做稳。** 你更适合幕后。你的长处是把事做对。\n\n**三、别的。** 甲。", [], true);
|
||||
assert.equal(body.output, "**二、把事做稳。**你的长处是把事做对。\n\n**三、别的。** 甲。");
|
||||
assert.deepEqual(body.stage, ["你更适合幕后。"]);
|
||||
});
|
||||
|
||||
test("sentence units never cut inside a bold span and join back to the text", () => {
|
||||
const text = "- **甲。乙。** 丙。**丁?**戊\n二、**己。**庚。\n## 标题。\n`**码。` 辛。";
|
||||
const units = markdownSentences(text);
|
||||
assert.equal(units.map((unit) => unit.text).join(""), text);
|
||||
assert.deepEqual(units.filter((unit) => unit.text !== "\n").map((unit) => [unit.text, unit.heading]), [
|
||||
["- **甲。乙。**", true], [" 丙。", false], ["**丁?**", false], ["戊", false],
|
||||
["二、**己。**", true], ["庚。", false],
|
||||
["## 标题。", true],
|
||||
["`**码。", false], ["` 辛。", false],
|
||||
]);
|
||||
});
|
||||
|
||||
test("the meta-clause and repeat clean-ups leave bold headings and markers paired", () => {
|
||||
// 原值:「** 戊己。」;新值:小标题保留(含「回答里」的小标题不整句删);原因:BUG-2393。
|
||||
assert.equal(dropMetaClauses("**二、回答里不写成“反复”。** 戊己。").output, "**二、回答里不写成“反复”。** 戊己。");
|
||||
assert.equal(dropMetaClauses("**二、把事做稳。** 回答里不写成“反复”,你要慢一点。").output, "**二、把事做稳。** ");
|
||||
const repeated = "**你的长处是把事做对、做稳。** 甲乙丙丁。\n\n**你的长处是把事做对、做稳。** 戊己。";
|
||||
assert.equal(dropRepeats(repeated).output, repeated);
|
||||
});
|
||||
|
||||
test("fact guard and repair deletions do not take a heading off its item; whole lines may still go", () => {
|
||||
const answer = "## 怎么做\n\n独立做事最适合你。\n\n**二、在幕后有错把事做好。** 你的长处是把事做对。\n\n**三、别的。** 甲。";
|
||||
const at = answer.indexOf("**二、");
|
||||
const end = answer.indexOf("**", at + 2) + 2;
|
||||
assert.equal(isProtectedRemoval(answer, at, end), true);
|
||||
assert.equal(isProtectedRemoval(answer, at, answer.indexOf("\n", at)), false);
|
||||
const start = answer.indexOf("有错");
|
||||
const mismatch = [{ kind: "house_lord", layer: "", entity: "", reference: "", claimed: "", card: "", fact_id: "", source_path: "", quote: "有错", start, end: start + 2 } as unknown as AnswerFactMismatch];
|
||||
const units = factGuardUnits(answer, mismatch);
|
||||
const out = applyFactRepair(answer, units, new Map(), EMPTY_CARD, { isProtected: isProtectedRemoval }).output;
|
||||
assert.match(out, /\*\*二、在幕后有错把事做好。\*\* 你的长处/);
|
||||
});
|
||||
|
||||
test("a lone ** at the start or end of a line is removed and not rendered", () => {
|
||||
// 原值:行首 / 行尾的落单 `**` 当文字保留并显示;新值:删掉、不显示;中间两边都是空格的 ` ** ` 照旧当文字;原因:BUG-2393。
|
||||
assert.equal(balanceStrongMarkers("** 你的长处是把事做对。").output, " 你的长处是把事做对。");
|
||||
assert.equal(balanceStrongMarkers("前面一句 **").output, "前面一句 ");
|
||||
assert.equal(balanceStrongMarkers("只有一个 ** 星号").output, "只有一个 ** 星号");
|
||||
const out = html("**一、甲。** 乙。\n\n** 你的长处是把事做对、做稳。\n\n**三、丙。** 丁。");
|
||||
assert.doesNotMatch(visible(out), /\*/);
|
||||
});
|
||||
|
||||
test("the final markdown pass repairs orphans, emptied bold and numbering gaps, and is idempotent", () => {
|
||||
const owner = "**一、有一个自己的摊子。** 甲。\n\n** 你的长处是把事做对。\n\n**三、一对一地谈。** 乙。\n\n- ** ** 空的\n- ****\n";
|
||||
const once = sanitizeAnswerMarkdown(owner);
|
||||
assert.equal(once.output, "**一、有一个自己的摊子。** 甲。\n\n 你的长处是把事做对。\n\n**二、一对一地谈。** 乙。\n\n- 空的\n- \n");
|
||||
assert.ok(once.repairs.includes("renumber:三→二"));
|
||||
assert.ok(once.repairs.some((item) => item.startsWith("lone-bold:")));
|
||||
assert.ok(once.repairs.includes("empty-bold"));
|
||||
assert.deepEqual(sanitizeAnswerMarkdown(once.output).repairs, []);
|
||||
// Two lists, headings, fences, 第一 / 十一 and well-formed text are left alone.
|
||||
const fine = "## 甲\n\n一、a\n二、b\n\n一、c\n二、d\n\n## 乙\n\n二、e\n\n```\n**x\n一、\n三、\n```\n**粗。**体 2**3\n";
|
||||
assert.deepEqual(sanitizeAnswerMarkdown(fine), { output: fine, repairs: [] });
|
||||
assert.equal(sanitizeAnswerMarkdown("九、a\n十一、b").output, "九、a\n十、b");
|
||||
});
|
||||
|
||||
test("the stream runs the markdown pass after every post-processing step and before the answer is accepted", () => {
|
||||
const source = readFileSync(new URL("../src/lib/stream-agent-response.ts", import.meta.url), "utf8");
|
||||
const keep = source.indexOf("keepWrittenReply(controller, written);");
|
||||
const sanity = source.indexOf("finalMarkdownCheck(controller);");
|
||||
const accept = source.indexOf("options.acceptAnswer?.(fullOutput)");
|
||||
assert.ok(keep > 0 && sanity > keep && accept > sanity);
|
||||
});
|
||||
@@ -202,7 +202,8 @@ test("the check runs after the fact guard, replaces the shown answer once, and n
|
||||
// BUG-2164 原值:completeBasis 之后直接是 acceptAnswer / 新值:中间多一步 shortenBodyDates(正文超过四个精确到天的日期改写到月份,不调模型)/ 原因:第三十一轮问答正文有 8 个、4 个精确日期
|
||||
// BUG-2229 原值: completeBasis 之后是 shortenBodyDates(BUG-2164)/ 新值: 直接 acceptAnswer / 原因: 正文日期改到月去掉(时间线照写交接日)
|
||||
// BUG-2285 原值: completeBasis 之后直接 acceptAnswer / 新值: 中间多一步 keepWrittenReply(结论句和被删空的一节放回,不调模型)/ 原因: 回答后面的步骤不能删掉用户要的那句
|
||||
assert.match(stream, /await guardAnswerFacts\(controller\);\n\s+await guardInternalWords\(controller\);\n\s+completeBasis\(controller\);\n\s+keepWrittenReply\(controller, written\);\n\s+const rejected = options\.acceptAnswer/);
|
||||
// BUG-2393 原值: keepWrittenReply 之后直接 acceptAnswer / 新值: 中间多一步 finalMarkdownCheck(落单 `**`、空加粗、编号跳号,不调模型)/ 原因: 清理删掉编号小标题后留下字面 `** `
|
||||
assert.match(stream, /await guardAnswerFacts\(controller\);\n\s+await guardInternalWords\(controller\);\n\s+completeBasis\(controller\);\n\s+keepWrittenReply\(controller, written\);\n\s+finalMarkdownCheck\(controller\);\n\s+const rejected = options\.acceptAnswer/);
|
||||
assert.match(guard, /send\(controller, \{ type: "answer\.delta", text: fullOutput, replace: true \}\);/);
|
||||
assert.doesNotMatch(guard, /throw /);
|
||||
assert.match(guard, /\} catch \{\n\s+\/\/ Keep the answer as written\./);
|
||||
|
||||
@@ -194,7 +194,8 @@ test("staging deploy consumes only the isolated staging environment and tested r
|
||||
);
|
||||
|
||||
assert.match(qualityGate, /push:\s*\n\s*branches: \[staging\]/);
|
||||
assert.match(workflow, /actions: read/);
|
||||
// 原值:/actions: read/ 新值:/actions: write/ 原因:BUG-2390 跟进,deploy-staging 要排队完整发布检查(dispatch 需要写权限)
|
||||
assert.match(workflow, /actions: write/);
|
||||
assert.match(workflow, /deploy_sha:/);
|
||||
assert.match(workflow, /\^\[0-9a-f\]\{40\}\$/);
|
||||
assert.match(workflow, /endswith\("backend-quality-gate\.yml"\)/);
|
||||
|
||||
@@ -1137,7 +1137,7 @@ test("manual migration uses only PostgreSQL and the digest-pinned migrator", ()
|
||||
assert.doesNotMatch(runner, /\bup\b[^\n]*(?:api|web|caddy)/);
|
||||
});
|
||||
|
||||
test("manual release gate runs where Docker Compose v2 is available", () => {
|
||||
test("release gate (automatic after staging deploy, or manual) runs where Docker Compose v2 is available", () => {
|
||||
const workflow = read(giteaReleaseQualityWorkflow);
|
||||
|
||||
assert.match(workflow, /^on:\n\s+workflow_dispatch:/m);
|
||||
@@ -1149,6 +1149,18 @@ test("manual release gate runs where Docker Compose v2 is available", () => {
|
||||
assert.match(workflow, /RESOLVE_MODE: discover/);
|
||||
assert.match(workflow, /bash deploy\/resolve-release-revision\.sh/);
|
||||
assert.match(workflow, /H relative to R is docs-only/);
|
||||
// 原值: 只能从 main 手动触发,发布前在同一个 SHA 上再跑一遍完整检查(约 29 分钟)
|
||||
// 新值: Deploy staging 成功后自动在 refs/heads/staging 上触发一次;自动运行只认当前 staging 头(或纯文档前进)且该 SHA 的 staging 门禁成功;新的 staging 部署取消旧的排队运行;从 main 手动触发仍可用作兜底
|
||||
// 原因: BUG-2390,产品负责人 2026-11-25:同一个 SHA 的完整检查只跑一次,发布不再多等约 25 分钟
|
||||
assert.match(workflow, /group: release-quality-\$\{\{ gitea\.ref \}\}\n\s+cancel-in-progress: true/);
|
||||
assert.match(workflow, /GITEA_REF" == refs\/heads\/staging/);
|
||||
assert.match(workflow, /this automatic release gate is superseded/);
|
||||
assert.match(workflow, /bash deploy\/is-docs-only-range\.sh --api "\$GITEA_SHA" "\$staging_head"/);
|
||||
assert.match(workflow, /endswith\("backend-quality-gate\.yml"\)\) and[\s\S]*?\.head_sha == \$sha and \.head_branch == "staging" and \.event == "push" and \.conclusion == "success"/);
|
||||
const stagingDeploy = read(new URL("../../.gitea/workflows/deploy-staging.yml", import.meta.url));
|
||||
assert.match(stagingDeploy, /Queue the full release checks for this SHA[\s\S]*?if: steps\.revision\.outputs\.allow_rollback != 'true'[\s\S]*?actions\/workflows\/release-quality-gate\.yml\/dispatches/);
|
||||
assert.match(stagingDeploy, /payload='\{"ref":"refs\/heads\/staging"\}'/);
|
||||
assert.match(stagingDeploy, /::warning::could not queue the full release checks/);
|
||||
assert.match(workflow, /PIP_INDEX_URL: https:\/\/mirrors\.aliyun\.com\/pypi\/simple\//);
|
||||
assert.match(workflow, /NPM_CONFIG_REGISTRY: https:\/\/registry\.npmmirror\.com/);
|
||||
// 原值: 发布检查在前端安装之后跑 JYOTISHA_REQUIRE_LEGAL_ENTITY=1 的协议测试(#119 第 9 项)
|
||||
@@ -1865,3 +1877,21 @@ test("the gate runs up to 6 PostgreSQL fixtures at once, inside the Docker addre
|
||||
assert.equal(value, 6);
|
||||
assert.ok(value * 2 <= 12, "two concurrent gates must stay under the runner's address pool");
|
||||
});
|
||||
|
||||
test("release and production workflows never fetch full history (BUG-2391)", () => {
|
||||
// 原值: git init 之后 git fetch --no-tags origin "$SHA"(不带 --depth),在 runner 上要 11–12 分钟
|
||||
// 新值: 先从 runner 上的裸镜像 /root/.cache/jyotisha-mirror.git 取这个 SHA,取不到再做 --depth=1 的有时限浅取
|
||||
// 原因: BUG-2391,产品负责人 2026-11-25:正式发布约 13 分钟里 11–12 分钟花在拉完整历史;这几个工作流只用到这一个提交
|
||||
for (const name of ["deploy-production", "release-quality-gate", "create-production-recovery", "migrate-production-database"]) {
|
||||
const workflow = read(new URL(`../../.gitea/workflows/${name}.yml`, import.meta.url));
|
||||
assert.doesNotMatch(workflow, /^\s+git fetch --no-tags origin "\$[A-Z_]+"$/m, name);
|
||||
assert.match(workflow, /git -C \/root\/\.cache\/jyotisha-mirror\.git cat-file -e/, name);
|
||||
assert.match(workflow, /fetch --depth=1 --no-tags origin/, name);
|
||||
}
|
||||
});
|
||||
|
||||
test("BUG-2390 follow-up: deploy-staging may queue the release gate (actions: write)", () => {
|
||||
// 原值:actions: read(排队完整检查的 dispatch 返回 403) 新值:actions: write 原因:自动完整检查要从 deploy-staging 排队
|
||||
const workflow = readFileSync(join(process.cwd(), "..", ".gitea", "workflows", "deploy-staging.yml"), "utf8");
|
||||
assert.match(workflow, /permissions:\n\s+contents: read\n(\s+#[^\n]*\n)?\s+actions: write/);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
// BUG-2392(占星师 2026-11-25 九项复核第四至八项):互换按实际交换的两宫召回领域、Raja 结构满足显示成立并写明修正、
|
||||
// 月亮落陷的有效缓解出卡、见证条件分开写、示意图与本盘实际图分开。合成盘,无出生资料。
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import { buildYogaGroups } from "../src/lib/chart-yoga-groups.ts";
|
||||
import { exchangeRecalledFor, exchangedHouses, selectEvidenceCardYogaDetail } from "../src/lib/consultation-evidence-card.ts";
|
||||
import type { ConsultationDomain } from "../src/lib/consultation-domain-registry.ts";
|
||||
|
||||
type Json = Record<string, unknown>;
|
||||
const planets = [
|
||||
{ name: "Sun", sign: "Cancer", house: 1 }, { name: "Moon", sign: "Virgo", house: 3 },
|
||||
{ name: "Mars", sign: "Libra", house: 4 }, { name: "Mercury", sign: "Leo", house: 2 },
|
||||
{ name: "Jupiter", sign: "Capricorn", house: 7 }, { name: "Venus", sign: "Gemini", house: 12 },
|
||||
{ name: "Saturn", sign: "Pisces", house: 9 },
|
||||
];
|
||||
|
||||
test("item 4: an exchange is recalled by the two houses it exchanges, never by every house a lord rules", () => {
|
||||
// 7 and 9: marriage (7 core) and education (9 core); not career (only 7 is a career extra house), not wealth.
|
||||
assert.equal(exchangeRecalledFor("marriage", [7, 9]), true);
|
||||
assert.equal(exchangeRecalledFor("education", [7, 9]), true);
|
||||
assert.equal(exchangeRecalledFor("career", [7, 9]), false);
|
||||
assert.equal(exchangeRecalledFor("wealth", [7, 9]), false);
|
||||
// Two career extra houses together (2 and 11) are recalled for career; 10 alone is enough.
|
||||
assert.equal(exchangeRecalledFor("career", [2, 11]), true);
|
||||
assert.equal(exchangeRecalledFor("career", [10, 3]), true);
|
||||
assert.equal(exchangeRecalledFor("health", [6, 9]), true);
|
||||
});
|
||||
|
||||
const row = (id: string, extra: Json = {}): Json => ({
|
||||
name: `Yoga ${id}`, rule_id: id, status: "computed", rule_state: "formed", method_version: "m",
|
||||
instance_key: `${id}|m|D1`, condition: "c", topic_mapping: "unmapped", rule_topics: [], ...extra,
|
||||
});
|
||||
const select = (rows: Json[], domains: ConsultationDomain[]) =>
|
||||
selectEvidenceCardYogaDetail({ rows } as never, domains, [])!;
|
||||
|
||||
test("item 4: the evidence card recalls the exchange for marriage and marks the second rule on it as the same exchange", () => {
|
||||
const maha = row("maha_parivartana_yoga", { planets: ["Jupiter", "Saturn"],
|
||||
formation_checks: [{ id: "house_class", passed: true, witness: { houses: [7, 9], class: "maha" } }] });
|
||||
const raja = row("raja_yoga_parivartana", {
|
||||
exchange: { Jupiter: { sign: "Capricorn", house: 7 }, Saturn: { sign: "Pisces", house: 9 } } });
|
||||
assert.deepEqual(exchangedHouses(maha), [7, 9]);
|
||||
assert.deepEqual(exchangedHouses(raja).sort(), [7, 9]);
|
||||
const out = select([maha, raja], ["marriage"]);
|
||||
const rows = out.rows as Json[];
|
||||
assert.deepEqual(rows.map((r) => r.rule_id).sort(), ["maha_parivartana_yoga", "raja_yoga_parivartana"]);
|
||||
for (const r of rows) assert.ok((r.selection_reasons as string[]).includes("exchange_houses"));
|
||||
const marked = rows.filter((r) => typeof r.same_exchange_as === "string");
|
||||
assert.equal(marked.length, 1, "one exchange is one piece of evidence");
|
||||
// A career card does not recall a 7–9 exchange.
|
||||
assert.equal((select([maha], ["career"]).rows as Json[]).length, 0);
|
||||
});
|
||||
|
||||
test("item 5: a formed Raja yoga card keeps its dusthana modifier in plain words", () => {
|
||||
const raja = {
|
||||
rule_id: "raja_yoga_parivartana", name: "Raja Yoga", name_cn: "王者互换格局", category: "raja",
|
||||
planets: ["Jupiter", "Saturn"], reader_condition_zh: "木星与土星互换星座",
|
||||
formation_assessment: { status: "formed_under_source" },
|
||||
formation_note_zh: "实际作用有利有弊:木星同时管第 6 宫,土星同时管第 8 宫。",
|
||||
};
|
||||
const groups = buildYogaGroups({ rows: [raja], planets, ascendant: "Cancer" })!;
|
||||
const card = groups.formed.find((c) => c.id === "raja_yoga_parivartana")!;
|
||||
assert.ok(card, "formed, not a candidate");
|
||||
assert.equal(card.text, "木星与土星互换星座。实际作用有利有弊:木星同时管第 6 宫,土星同时管第 8 宫。");
|
||||
assert.doesNotMatch(card.text, /待核|候选|不能据此/u);
|
||||
});
|
||||
|
||||
test("items 6 and 7: a debilitated Moon with Mars in a kendra from the Moon gets its card; conditions stay separate", () => {
|
||||
const moonChart = [
|
||||
{ name: "Moon", sign: "Scorpio", house: 8 }, { name: "Mars", sign: "Aquarius", house: 11 },
|
||||
{ name: "Venus", sign: "Leo", house: 5 }, { name: "Sun", sign: "Aries", house: 1 },
|
||||
];
|
||||
const row = {
|
||||
rule_id: "neechabhanga_basic", name: "Neecha Bhanga", name_cn: "落陷取消", category: "nicha_bhanga",
|
||||
planets: ["Moon", "Mars", "Venus"],
|
||||
combination: "月亮落陷于天蝎座;成立条件:落陷星座主星火星在月亮起第4宫(角宫);该星入旺星座的主星金星在月亮起第10宫(角宫)",
|
||||
formation_evidence: { planet: "Moon", self_reference_only: false,
|
||||
cancellation_reasons: [{ condition: "dispositor_kendra_from_moon", planet: "Mars", reference: "Moon", self_reference: false }] },
|
||||
formation_assessment: { status: "formed_under_source" },
|
||||
};
|
||||
const groups = buildYogaGroups({ rows: [row], planets: moonChart, ascendant: "Aries" })!;
|
||||
const cards = groups.support.filter((c) => c.id.startsWith("neecha:"));
|
||||
assert.deepEqual(cards.map((c) => c.id), ["neecha:Moon"]);
|
||||
assert.match(cards[0]!.text, /缓解来自:落陷星座主星火星在月亮起第4宫(角宫);该星入旺星座的主星金星在月亮起第10宫(角宫)/u);
|
||||
assert.doesNotMatch(cards[0]!.text, /%/u);
|
||||
});
|
||||
|
||||
test("item 8: engine participants draw the actual chart; an inferred diagram is captioned as an illustration", () => {
|
||||
const withParticipants = { rule_id: "dhana_yoga", name: "Dhana Yoga", name_cn: "财富格局", category: "dhana",
|
||||
planets: ["Jupiter", "Saturn"], reader_condition_zh: "财富宫主星落入财富宫", formation_assessment: { status: "formed_under_source" } };
|
||||
const inferred = { rule_id: "bvr_sumukha_precise", name: "Sumukha", name_cn: "善面瑜伽", category: "special",
|
||||
planets: [], reader_condition_zh: "2宫主在角宫", formation_assessment: { status: "formed_under_source" } };
|
||||
const groups = buildYogaGroups({ rows: [withParticipants, inferred], planets, ascendant: "Cancer" })!;
|
||||
const actual = groups.formed.find((c) => c.id === "dhana_yoga")!;
|
||||
const sketch = groups.formed.find((c) => c.id === "bvr_sumukha_precise")!;
|
||||
assert.doesNotMatch(actual.diagram.label, /^示意/u);
|
||||
assert.match(sketch.diagram.label, /^示意:/u);
|
||||
});
|
||||
@@ -1073,7 +1073,8 @@
|
||||
"combo_template": "财富宫主星落入财富宫",
|
||||
"combo_template_en": "Lords of wealth houses placed in wealth houses",
|
||||
"strength": "中",
|
||||
"strength_en": "moderate"
|
||||
"strength_en": "moderate",
|
||||
"participants_expr": "[w for w in sorted(wl) if w in ctx.planets and house_of(w) in wh]"
|
||||
},
|
||||
"effects": [
|
||||
"财富积累",
|
||||
@@ -1104,7 +1105,8 @@
|
||||
"combo_template": "财富宫主星聚宫",
|
||||
"combo_template_en": "Lords of wealth houses conjoined",
|
||||
"strength": "强",
|
||||
"strength_en": "strong"
|
||||
"strength_en": "strong",
|
||||
"participants_expr": "[lp for h, lp in lords.items() if lp in ctx.planets and house_of(lp) in (2, 11) and sum(1 for q in lords.values() if q in ctx.planets and house_of(q) == house_of(lp)) >= 2]"
|
||||
},
|
||||
"effects": [
|
||||
"财运亨通",
|
||||
@@ -1565,7 +1567,8 @@
|
||||
"type": "custom",
|
||||
"expr": "\npairs = [(6,8), (6,12), (8,12)]\nmatched = []\nfor h1, h2 in pairs:\n l1 = lord(h1)\n l2 = lord(h2)\n if l1 in ctx.planets and l2 in ctx.planets:\n if house_of(l1) == h2 and house_of(l2) == h1:\n matched.append((h1, h2, l1, l2))\nmatched\n",
|
||||
"combo_template": "凶宫主星互落",
|
||||
"combo_template_en": "Dusthana lords placed in each other's houses"
|
||||
"combo_template_en": "Dusthana lords placed in each other's houses",
|
||||
"participants_expr": "[p for m in matched for p in m[2:]]"
|
||||
},
|
||||
"effects": [
|
||||
"因祸得福",
|
||||
@@ -12483,7 +12486,8 @@
|
||||
"logic": {
|
||||
"type": "custom",
|
||||
"expr": "\n# PyJHora/BVR-238: Lords of Lagna and 7th in conjunction or mutual graha aspect.\nl1 = lord(1)\nl7 = lord(7)\nif l1 not in ctx.planets or l7 not in ctx.planets:\n False\nelse:\n same_house(l1, l7) or (aspect(l1, l7) and aspect(l7, l1))\n",
|
||||
"combo_template": "PyJHora aligned source logic"
|
||||
"combo_template": "PyJHora aligned source logic",
|
||||
"participants_expr": "[l1, l7]"
|
||||
},
|
||||
"effects": [
|
||||
"既有规则的传统描述(非个人事实或结果保证):与多位女性交往"
|
||||
|
||||
+40
-2
@@ -349,7 +349,28 @@ def parivartana_class(house_a: int, house_b: int) -> Optional[str]:
|
||||
return 'maha'
|
||||
|
||||
|
||||
# BUG-2392 (占星师 2026-11-25 复核第五项; owner approved this frozen-file change): a kendra–trikona lord
|
||||
# Raja yoga whose structure is satisfied on the chart is formed (「成立」). Was: no reviewed contract,
|
||||
# so every hit stayed `candidate` (`source_definition_not_reviewed`). A lord that also rules the
|
||||
# 6th, 8th or 12th is a modifier written beside it (`formation_modifiers`), not a reason to withhold it.
|
||||
RAJA_STRUCTURAL_RULES = frozenset({
|
||||
'raja_yoga', 'raja_yoga_parivartana', 'dharma_karmadhipati', 'dharma_karmadhipati_parivartana',
|
||||
'raja_yoga_1_4', 'raja_yoga_5_9', 'raja_yoga_4_9', 'raja_yoga_mutual_aspect', 'raja_yoga_1_10',
|
||||
'raja_yoga_7_9', 'raja_yoga_5_10_lord',
|
||||
})
|
||||
RAJA_STRUCTURAL_PROFILE = 'kendra_trikona_lord_structure'
|
||||
|
||||
|
||||
def _product_formation_contract(rule_id: str) -> Optional[dict[str, Any]]:
|
||||
if rule_id in RAJA_STRUCTURAL_RULES:
|
||||
return {
|
||||
'profile': RAJA_STRUCTURAL_PROFILE, 'name': None,
|
||||
'source': {'title': 'BPHS', 'section': 'Raja yoga (kendra and trikona lords)'},
|
||||
# The rule's own executed definition is the definition (no second detector).
|
||||
'definition': None,
|
||||
'required': ['d1_scope', 'consistent_geometry', 'lord_structure'],
|
||||
'variant_boundary': '角宫主与三方宫主按本条规则结合;兼管第 6、8、12 宫的宫主写在修正里。',
|
||||
}
|
||||
for kind in PARIVARTANA_CLASSES:
|
||||
if rule_id == f'{kind}_parivartana_yoga':
|
||||
return {
|
||||
@@ -379,7 +400,8 @@ def _assess_product_contract(row: dict[str, Any], contract: dict[str, Any]) -> d
|
||||
missing = [key for key in required if key not in satisfied and key not in failed]
|
||||
issues = []
|
||||
if (row.get('formation_source_profile') != contract['profile'] or
|
||||
evidence.get('definition') != contract['definition']):
|
||||
(evidence.get('definition') != contract['definition'] if contract['definition'] is not None
|
||||
else not evidence.get('definition'))):
|
||||
issues.append('source_definition_mismatch')
|
||||
if len(by_id) != len(checks):
|
||||
issues.append('duplicate_condition_evidence')
|
||||
@@ -393,7 +415,7 @@ def _assess_product_contract(row: dict[str, Any], contract: dict[str, Any]) -> d
|
||||
formed = not issues and not missing and not failed
|
||||
return {
|
||||
'status': 'formed_under_source' if formed else 'conditions_not_met' if failed else 'candidate',
|
||||
'name': contract['name'], 'source_profile': contract['profile'], 'source': dict(contract['source']),
|
||||
'name': contract['name'] or row.get('name'), 'source_profile': contract['profile'], 'source': dict(contract['source']),
|
||||
'required_conditions': list(required), 'satisfied_conditions': satisfied,
|
||||
'missing_conditions': missing, 'failed_conditions': failed,
|
||||
'review_issues': issues, 'checks': checks, 'variant_boundary': contract['variant_boundary'],
|
||||
@@ -1892,6 +1914,22 @@ class YogaEngine:
|
||||
ctx.is_own_sign('Jupiter') or ctx.is_exalted('Jupiter') or
|
||||
SIGN_LORDS.get(sign) in FRIENDLY_PLANETS['Jupiter'],
|
||||
{'planet': 'Jupiter', 'sign': sign, 'friendship': 'natural'})
|
||||
elif contract.get('profile') == RAJA_STRUCTURAL_PROFILE:
|
||||
# BUG-2392: the bound lords and the houses each rules; any 6/8/12 lordship is a modifier.
|
||||
lordships = {p: [h for h in range(1, 13) if ctx.lord_of_house(h) == p] for p in planets_bound}
|
||||
royal = {p: [h for h in houses if h in (1, 4, 5, 7, 9, 10)] for p, houses in lordships.items()}
|
||||
check('lord_structure', None if len(planets_bound) < 2 else
|
||||
len(set(planets_bound)) >= 2 and all(royal.values()),
|
||||
{'lordships': lordships} if len(planets_bound) >= 2 else None)
|
||||
modifiers = [{'planet': p, 'houses': [h for h in houses if h in (6, 8, 12)]}
|
||||
for p, houses in lordships.items() if any(h in (6, 8, 12) for h in houses)]
|
||||
if modifiers:
|
||||
entry['formation_modifiers'] = modifiers
|
||||
entry['formation_note_zh'] = '实际作用有利有弊:' + ','.join(
|
||||
f"{PLANET_ZH.get(m['planet'], m['planet'])}同时管第 {'、'.join(map(str, m['houses']))} 宫"
|
||||
for m in modifiers) + '。'
|
||||
entry['formation_note_en'] = 'Mixed in effect: ' + '; '.join(
|
||||
f"{m['planet']} also rules house {', '.join(map(str, m['houses']))}" for m in modifiers) + '.'
|
||||
elif contract.get('profile') == 'phaladeepika_6_parivartana_houses':
|
||||
# BUG-2388: the two lords sit in each other's signs, and the two houses decide the kind.
|
||||
pair = [p for p in planets_bound if p in SIGN_LORDS.values()][:2]
|
||||
|
||||
@@ -334,7 +334,14 @@ def test_installer_test_alert_without_channels_stays_local(tmp_path: Path) -> No
|
||||
|
||||
def test_off_host_probe_workflow_runs_every_five_minutes_from_main() -> None:
|
||||
text = PROBE_WORKFLOW.read_text(encoding="utf-8")
|
||||
assert 'cron: "*/5 * * * *"' in text
|
||||
# 原值: cron 每 5 分钟、timeout-minutes 5、整库浅取、cancel-in-progress false
|
||||
# 新值: 每 10 分钟、timeout-minutes 3、只取两个监控脚本(镜像或 raw API,每次 20 秒上限)、新运行取消旧运行
|
||||
# 原因: BUG-2389,整库浅取在 runner 上要 4-8 分钟,每次都被 5 分钟上限取消(exit code -1)并占着 runner
|
||||
assert 'cron: "*/10 * * * *"' in text
|
||||
assert "timeout-minutes: 3" in text
|
||||
assert "cancel-in-progress: true" in text
|
||||
assert "git fetch" not in text
|
||||
assert "--max-time 20" in text
|
||||
assert "if: gitea.ref == 'refs/heads/main'" in text
|
||||
assert "runs-on: xiaoxin" in text
|
||||
assert "JYOTISHA_COMMIT_ALERT=off" in text
|
||||
|
||||
@@ -75,7 +75,10 @@ def test_synced_rules_carry_participants_expr_and_name_their_planets():
|
||||
# 原值:34
|
||||
# 新值:32
|
||||
# 原因:BUG-2301 照上游 58f37ee5b,她从 daridra_2、daridra_yoga_combined 去掉了 participants_expr(两条改为取法待核、不给作用)
|
||||
assert len(carrying) == 32
|
||||
# 原值:32 / 新值:36 / 原因:BUG-2392(占星师 11-25 第八项)dhana_yoga、grahi_dhana、vipreet_pairs、
|
||||
# bvr_bahu_sthree_yoga 写明实际命中分支的参与星(产品自加,不是上游同步)
|
||||
assert len(carrying) == 36
|
||||
assert {"dhana_yoga", "grahi_dhana", "vipreet_pairs", "bvr_bahu_sthree_yoga"} <= carrying
|
||||
# Her expression for this rule belongs to a different condition text than ours; not copied.
|
||||
assert "bvr_matrunasa_precise" not in carrying
|
||||
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
"""BUG-2392: the astrologer's 2026-11-25 review, items 5, 6 and 8 on the engine side (synthetic charts only).
|
||||
|
||||
Item 5: a kendra–trikona Raja yoga whose structure holds is formed; a lord that also rules a dusthana is
|
||||
written as a modifier. Item 6: Neecha Bhanga self-reference is only the Moon measured from itself; a
|
||||
debilitated Moon with its dispositor in a kendra from the Moon is a real mitigation. Item 8: a custom rule
|
||||
names the planets of the branch that matched.
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from scripts.yoga_engine import RAJA_STRUCTURAL_RULES, SIGNS, YogaEngine
|
||||
|
||||
RULES = Path(__file__).resolve().parents[1] / "references" / "yoga_rules.json"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def engine():
|
||||
return YogaEngine(str(RULES))
|
||||
|
||||
|
||||
def chart(ascendant, signs):
|
||||
asc = SIGNS.index(ascendant)
|
||||
return {p: {"sign": s, "house": (SIGNS.index(s) - asc) % 12 + 1} for p, s in signs.items()}
|
||||
|
||||
|
||||
def run(engine, ascendant, signs, ids=None):
|
||||
rows = engine.detect(chart(ascendant, signs), ascendant, context={"chart_type": "D1"})
|
||||
return [r for r in rows if ids is None or r["rule_id"] in ids]
|
||||
|
||||
|
||||
CANCER = {"Jupiter": "Capricorn", "Saturn": "Pisces", "Sun": "Cancer", "Moon": "Virgo",
|
||||
"Mars": "Libra", "Mercury": "Leo", "Venus": "Gemini"}
|
||||
|
||||
|
||||
def test_raja_exchange_is_formed_with_its_dusthana_modifier(engine):
|
||||
rows = {r["rule_id"]: r for r in run(engine, "Cancer", CANCER, RAJA_STRUCTURAL_RULES)}
|
||||
row = rows["raja_yoga_parivartana"]
|
||||
assert row["formation_assessment"]["status"] == "formed_under_source"
|
||||
assert row["formation_assessment"]["review_issues"] == []
|
||||
checks = {c["id"]: c for c in row["formation_checks"]}
|
||||
assert checks["lord_structure"]["passed"] is True
|
||||
assert checks["lord_structure"]["witness"]["lordships"] == {"Jupiter": [6, 9], "Saturn": [7, 8]}
|
||||
assert row["formation_note_zh"] == "实际作用有利有弊:木星同时管第 6 宫,土星同时管第 8 宫。"
|
||||
assert "待核" not in row["formation_note_zh"]
|
||||
|
||||
|
||||
def test_a_raja_rule_without_a_second_royal_lord_is_not_formed(engine):
|
||||
# Aries: Sun (lord of 5) with Moon (lord of 4) in the 4th — formed; the check names both royal lords.
|
||||
rows = {r["rule_id"]: r for r in run(engine, "Aries", {
|
||||
"Sun": "Cancer", "Moon": "Cancer", "Mars": "Aries", "Mercury": "Gemini", "Jupiter": "Libra",
|
||||
"Venus": "Virgo", "Saturn": "Scorpio"}, RAJA_STRUCTURAL_RULES)}
|
||||
assert rows, "expected a Raja row"
|
||||
for row in rows.values():
|
||||
assert row["formation_assessment"]["status"] == "formed_under_source", row["rule_id"]
|
||||
lordships = {c["id"]: c for c in row["formation_checks"]}["lord_structure"]["witness"]["lordships"]
|
||||
assert all(any(h in (1, 4, 5, 7, 9, 10) for h in houses) for houses in lordships.values())
|
||||
|
||||
|
||||
def test_debilitated_moon_with_its_dispositor_in_a_kendra_from_the_moon_is_mitigated(engine):
|
||||
rows = run(engine, "Aries", {"Moon": "Scorpio", "Mars": "Aquarius", "Sun": "Aries", "Jupiter": "Pisces",
|
||||
"Saturn": "Gemini", "Mercury": "Taurus", "Venus": "Leo"}, {"neechabhanga_basic"})
|
||||
evidence = rows[0]["formation_evidence"]
|
||||
assert evidence["planet"] == "Moon"
|
||||
assert evidence["self_reference_only"] is False
|
||||
mars = [r for r in evidence["cancellation_reasons"] if r["planet"] == "Mars"]
|
||||
assert mars and mars[0]["reference"] == "Moon" and mars[0]["self_reference"] is False
|
||||
assert rows[0]["formation_assessment"]["status"] == "formed_under_source"
|
||||
assert "火星在月亮起第4宫" in str(rows[0]["combination"])
|
||||
|
||||
|
||||
def test_only_the_moon_measured_from_itself_is_self_reference(engine):
|
||||
# Jupiter in Capricorn: Moon (lord of Jupiter's exaltation sign Cancer) "in a kendra from the Moon" is the
|
||||
# tautology; Saturn (lord of Capricorn) in the 7th from the Moon is a separate, real condition.
|
||||
rows = run(engine, "Cancer", CANCER, {"neechabhanga_basic"})
|
||||
reasons = rows[0]["formation_evidence"]["cancellation_reasons"]
|
||||
by = {(r["planet"], r["condition"]): r for r in reasons}
|
||||
assert by[("Moon", "exaltation_sign_lord_kendra_from_moon")]["self_reference"] is True
|
||||
assert by[("Saturn", "dispositor_kendra_from_moon")]["self_reference"] is False
|
||||
assert rows[0]["formation_evidence"]["self_reference_only"] is False
|
||||
|
||||
|
||||
def test_custom_rules_name_the_planets_of_the_matched_branch(engine):
|
||||
# Aries: lords of 2/5/9/11 are Venus, Sun, Jupiter, Saturn; Jupiter in the 2nd and Venus in the 5th.
|
||||
rows = run(engine, "Aries", {"Jupiter": "Taurus", "Venus": "Leo", "Sun": "Capricorn", "Saturn": "Gemini",
|
||||
"Moon": "Aries", "Mars": "Virgo", "Mercury": "Sagittarius"}, {"dhana_yoga"})
|
||||
assert rows and sorted(rows[0]["planets"]) == ["Jupiter", "Venus"]
|
||||
Reference in New Issue
Block a user