@chrono-meta/fh-gate 3.32.0 → 3.34.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +4 -4
- package/AGENTS.md +23 -0
- package/CATALOG.md +44 -0
- package/CLAUDE.md +2 -2
- package/knowledge/shared/harness-core/claude_md_full_reference.md +19 -0
- package/knowledge/shared/harness-core/dispatch_conditional_prohibition.md +9 -0
- package/knowledge/shared/learnings/subagent_invocations_log.yaml +105 -0
- package/knowledge/shared/rules/operations.md +11 -0
- package/knowledge/shared/rules/sister_asset_protocol.md +21 -2
- package/package.json +5 -1
- package/plugins/fh-commons/.claude-plugin/plugin.json +1 -1
- package/plugins/fh-commons/skills/ko-tech-writer/SKILL.md +28 -0
- package/plugins/fh-commons/skills/ko-tech-writer/fixtures/known_negative.md +32 -0
- package/plugins/fh-commons/skills/ko-tech-writer/fixtures/known_positive.md +22 -0
- package/plugins/fh-commons/skills/ko-tech-writer/fixtures/rewrite_clean.md +4 -0
- package/plugins/fh-commons/skills/ko-tech-writer/fixtures/rewrite_drops_metaphor.md +4 -0
- package/plugins/fh-commons/skills/ko-tech-writer/fixtures/rewrite_invents_number.md +4 -0
- package/plugins/fh-commons/skills/ko-tech-writer/fixtures/rewrite_keep.txt +2 -0
- package/plugins/fh-commons/skills/ko-tech-writer/fixtures/rewrite_original.md +4 -0
- package/plugins/fh-commons/skills/persona-cast/SKILL.md +12 -6
- package/plugins/fh-meta/.claude-plugin/plugin.json +1 -1
- package/plugins/fh-meta/CHANGELOG.md +37 -0
- package/plugins/fh-meta/skills/frontier-digest/SKILL.md +3 -1
- package/plugins/fh-meta/skills/frontier-digest/SKILL_detail.md +12 -0
- package/plugins/fh-preprep/.claude-plugin/plugin.json +1 -1
- package/plugins/fh-qp/.claude-plugin/plugin.json +1 -1
- package/scripts/absorption_queue.py +493 -0
- package/scripts/digest_landing_check.sh +110 -5
- package/scripts/digest_slow_leg.py +456 -0
- package/scripts/fh_session_load.sh +12 -0
- package/scripts/ko_tech_writer_calibrate.py +284 -7
- package/scripts/selfcheck.sh +2 -0
- package/scripts/test_absorption_queue_lanes.sh +10 -0
- package/scripts/test_digest_slow_leg_lanes.sh +11 -0
|
@@ -114,7 +114,7 @@ SECTION_RE="${DLC_SECTION_RE:-^## .*Immediate Application Candidates}"
|
|
|
114
114
|
_extract() { # $1 = digest path
|
|
115
115
|
awk -v sec="$SECTION_RE" '
|
|
116
116
|
# 판별자 추출 — 표/문단 **두 경로가 공유**한다(중복 정규화기 방지).
|
|
117
|
-
function harvest(body, toks, tmp, w, t) {
|
|
117
|
+
function harvest(body, toks, tmp, w, t, idk) {
|
|
118
118
|
tmp=body
|
|
119
119
|
while (match(tmp, /\[\[[^]]+\]\]/)) {
|
|
120
120
|
w=substr(tmp, RSTART+2, RLENGTH-4); tmp=substr(tmp, RSTART+RLENGTH)
|
|
@@ -123,11 +123,19 @@ _extract() { # $1 = digest path
|
|
|
123
123
|
tmp=body
|
|
124
124
|
while (match(tmp, /`[^`]+`/)) {
|
|
125
125
|
t=substr(tmp, RSTART+1, RLENGTH-2); tmp=substr(tmp, RSTART+RLENGTH)
|
|
126
|
-
|
|
126
|
+
# 출처 ID 는 콜론에서 자르지 않는다 — 자르면 `arXiv` · `HN` 한 낱말만 남아 레포 어디에나 맞거나
|
|
127
|
+
# 버려진다(AQ-20261028-9). `arXiv:NNNN.NNNNN` 은 번호만 남긴다(번호 자체가 고유하고, 착지문은
|
|
128
|
+
# `arXiv:2610.x` · `arXiv 2610.x` 둘 다 쓴다). `HN:` · `GN:` 은 접두어째 둔다 — 번호만 남기면 다른
|
|
129
|
+
# 출처의 같은 번호에 맞는다. 그 밖의 `이름:값`(timeout:10000 · localhost:8080)은 종전대로 자른다
|
|
130
|
+
# (cross-family codex R1 이 넓은 «접두어:숫자» 조건의 세 오착지를 지목).
|
|
131
|
+
idk = (t ~ /^arXiv:[0-9][0-9][0-9][0-9]\.[0-9][0-9][0-9][0-9]+$/ || t ~ /^(HN|GN):[0-9]+$/)
|
|
132
|
+
if (t ~ /^arXiv:/ && idk) sub(/^arXiv:/, "", t); else if (!idk) sub(/[: ].*$/, "", t)
|
|
127
133
|
gsub(/^[[:space:]]+|[[:space:]]+$/, "", t)
|
|
128
134
|
if (length(t) < 5) continue
|
|
129
135
|
if (t ~ /[][(){}.*+?^$\\|]/) { if (t ~ /^[A-Za-z0-9_.-]+$/) { } else continue }
|
|
130
136
|
gsub(/\./, "\\.", t)
|
|
137
|
+
# 출처 ID 는 숫자 경계로 감싼다 — `HN:123` 이 `HN:12345` 에 맞지 않게(codex R2). 검사기는 grep -E
|
|
138
|
+
if (idk) t = "(^|[^0-9])" t "([^0-9]|$)"
|
|
131
139
|
toks = (toks == "" ? t : toks "|" t)
|
|
132
140
|
}
|
|
133
141
|
return toks
|
|
@@ -193,7 +201,10 @@ _extract() { # $1 = digest path
|
|
|
193
201
|
tmp=substr(tmp, RSTART+RLENGTH)
|
|
194
202
|
# ⚠️ 콜론/공백 뒤를 자른다. `allow_force_pushes: true` 를 통째로 걸면 실제 착지문
|
|
195
203
|
# (`allow_force_pushes` 만 쓴 카드)을 **놓친다** — 실측으로 확인된 오검출 방향.
|
|
196
|
-
|
|
204
|
+
# 단, 출처 ID 는 예외(AQ-20261028-9, 10-26 digest 후보 셋 다 ALL-LANDED): `arXiv:NNNN.NNNNN` 은
|
|
205
|
+
# 번호만, `HN:` · `GN:` 은 접두어째. 그 밖의 `이름:값` 은 종전대로 자른다(codex R1).
|
|
206
|
+
idk = (t ~ /^arXiv:[0-9][0-9][0-9][0-9]\.[0-9][0-9][0-9][0-9]+$/ || t ~ /^(HN|GN):[0-9]+$/)
|
|
207
|
+
if (t ~ /^arXiv:/ && idk) sub(/^arXiv:/, "", t); else if (!idk) sub(/[: ].*$/, "", t)
|
|
197
208
|
gsub(/^[[:space:]]+|[[:space:]]+$/, "", t)
|
|
198
209
|
# 판별력 없는 짧은/일반 토큰은 버린다
|
|
199
210
|
if (length(t) < 5) continue
|
|
@@ -203,6 +214,8 @@ _extract() { # $1 = digest path
|
|
|
203
214
|
if (t ~ /^[A-Za-z0-9_.-]+$/) { } else continue
|
|
204
215
|
}
|
|
205
216
|
gsub(/\./, "\\.", t)
|
|
217
|
+
# 출처 ID 는 숫자 경계로 감싼다 — `HN:123` 이 `HN:12345` 에 맞지 않게(codex R2). 검사기는 grep -E
|
|
218
|
+
if (idk) t = "(^|[^0-9])" t "([^0-9]|$)"
|
|
206
219
|
toks = (toks == "" ? t : toks "|" t)
|
|
207
220
|
}
|
|
208
221
|
print id "\t" toks
|
|
@@ -271,6 +284,8 @@ do_check() {
|
|
|
271
284
|
# 실측: forge-wiki 대상 첫 런이 정확히 그렇게 «SOME-UNLANDED (rc=1)» 을 남겼고 본문은 없었다.
|
|
272
285
|
# 올바른 값은 rc=10(타깃 0건 = HARNESS-ERROR)이다. 빈 배열 확장을 전부 방어한다.
|
|
273
286
|
local -a targets=()
|
|
287
|
+
# 잘림 판정의 근거 — 이 호출에서 센 값만 쓴다(전역이라 상속값 · 앞선 호출값이 새면 rc=1 이 10 으로 바뀐다, codex R2)
|
|
288
|
+
IGNORED_FOUND=0
|
|
274
289
|
if [ "$#" -gt 0 ]; then targets=("$@")
|
|
275
290
|
else
|
|
276
291
|
# 기본 스코프 = 공개 FH 자산 + tracks. **비공개 store 제외**(운영자 결정).
|
|
@@ -316,8 +331,24 @@ do_check() {
|
|
|
316
331
|
[ -f "$FH/$f" ] && targets+=("$FH/$f")
|
|
317
332
|
done < <(git -C "$FH" log --since="@$_dts" --name-only --pretty=format: -- $DLC_TRACKED_PATHS 2>/dev/null | sort -u)
|
|
318
333
|
if [ -n "$DLC_IGNORED_DIR" ] && [ -d "$FH/$DLC_IGNORED_DIR" ]; then
|
|
319
|
-
|
|
320
|
-
|
|
334
|
+
# 깊이 2 까지만(최상위 기록 + 한 단계 하위의 REPORT · RESULT) — 그 아래는 실험 클론 안의 FH
|
|
335
|
+
# 사본이라 착지 기록이 아니고, 어휘가 겹쳐 가짜 착지를 만든다. 깊이 제한 없이 `head -400` 만
|
|
336
|
+
# 두었을 때 10-20 digest 의 첫 400 중 148 이 실험 클론(p3_contract_ab) 안 파일이었다
|
|
337
|
+
# (AQ-20261031-4). 상한은 남기되 잘리면 그 수를 출력한다 — 조용히 덜 읽지 않는다.
|
|
338
|
+
# 숫자가 아닌 깊이 · 상한은 설정 오류다 — find/head 가 조용히 실패하면 이 축이 꺼진 채 판정이 나온다(codex R1)
|
|
339
|
+
local _v
|
|
340
|
+
for _v in "${DLC_IGNORED_DEPTH:-2}" "${DLC_IGNORED_CAP:-400}"; do
|
|
341
|
+
case "$_v" in
|
|
342
|
+
*[!0-9]*|0*) echo "❌ DLC_IGNORED_DEPTH / DLC_IGNORED_CAP 는 1 이상의 정수여야 한다(받은 값: '${DLC_IGNORED_DEPTH-}' '${DLC_IGNORED_CAP-}')" >&2; return 10 ;;
|
|
343
|
+
esac
|
|
344
|
+
done
|
|
345
|
+
local _ign; _ign="$(find "$FH/$DLC_IGNORED_DIR" -maxdepth "${DLC_IGNORED_DEPTH:-2}" -name '*.md' -type f -newer "$d" 2>/dev/null)"
|
|
346
|
+
# 세기와 자르기를 한 루프에서 — `| head` 는 조기 종료로 앞 단계를 SIGPIPE 로 죽인다(pipefail 잠금)
|
|
347
|
+
while IFS= read -r f; do
|
|
348
|
+
[ -n "$f" ] || continue
|
|
349
|
+
IGNORED_FOUND=$((IGNORED_FOUND+1))
|
|
350
|
+
[ "$IGNORED_FOUND" -le "${DLC_IGNORED_CAP:-400}" ] && targets+=("$f")
|
|
351
|
+
done <<< "$_ign"
|
|
321
352
|
fi
|
|
322
353
|
# dirty tracked — 커밋 안 된 수정본엔 git 시각 증거가 없다. 초록으로 만들지 않고 셈에 남긴다.
|
|
323
354
|
DIRTY_TRACKED="$(git -C "$FH" diff --name-only -- $DLC_TRACKED_PATHS 2>/dev/null | grep -c '[.]md$')" || true
|
|
@@ -418,6 +449,9 @@ do_check() {
|
|
|
418
449
|
echo "── digest 착지 검증: $(basename "$d") ──"
|
|
419
450
|
echo " 스코프: git추적[${DLC_TRACKED_PATHS}] + ignored[${DLC_IGNORED_DIR:-없음}] (비공개 companion store 제외 — '조직 전파'가 아니라 '레포 내부 착지')"
|
|
420
451
|
echo " 타깃 파일 ${#targets[@]}건 (digest 이후 수정분만) · 판별불가 후보 ${unchk}건"
|
|
452
|
+
if [ "${IGNORED_FOUND:-0}" -gt "${DLC_IGNORED_CAP:-400}" ]; then
|
|
453
|
+
echo " ⚠️ ignored 축 ${IGNORED_FOUND}건 중 ${DLC_IGNORED_CAP:-400}건만 읽었다 — 미착지 판정은 덜 읽은 결과일 수 있다(DLC_IGNORED_CAP 로 올려라)"
|
|
454
|
+
fi
|
|
421
455
|
echo " 축: git추적=커밋시각 · gitignored=mtime · dirty tracked ${DIRTY_TRACKED:-0}건=UNMEASURED"
|
|
422
456
|
echo " ⚠️ 이 계기는 **선후**를 잰다. 인과가 아니다 — 히트는 열어서 확인하라"
|
|
423
457
|
echo
|
|
@@ -426,6 +460,13 @@ do_check() {
|
|
|
426
460
|
local rc=$?
|
|
427
461
|
rm -f "$probes"
|
|
428
462
|
|
|
463
|
+
# ⚠️ ignored 축이 잘렸으면 «미착지» 는 확정이 아니다 — 안 읽은 파일에 근거가 있을 수 있다.
|
|
464
|
+
# 본 착지(양성)는 그대로 유효하지만 부재 주장은 못 한다 ⇒ 미측정(10)(codex R1).
|
|
465
|
+
if [ "$rc" -eq 1 ] && [ "${IGNORED_FOUND:-0}" -gt "${DLC_IGNORED_CAP:-400}" ]; then
|
|
466
|
+
echo
|
|
467
|
+
echo "🟡 미착지 후보가 있지만 ignored 축을 ${IGNORED_FOUND}건 중 ${DLC_IGNORED_CAP:-400}건만 읽었다 — 미착지를 확정하지 않는다. rc=10"
|
|
468
|
+
return 10
|
|
469
|
+
fi
|
|
429
470
|
# ⚠️ 재지 못한 후보가 있으면 전건 착지라도 0 을 내지 않는다.
|
|
430
471
|
if [ "$rc" -eq 0 ] && [ "${unchk:-0}" -gt 0 ]; then
|
|
431
472
|
echo
|
|
@@ -479,6 +520,70 @@ EOF
|
|
|
479
520
|
rc=0; DLC_CONTROLS="forge-harness session" bash "$SELF_DIR/$(basename "${BASH_SOURCE[0]}")" "$T/digest.md" "$T/tgt/card.md" >/dev/null 2>&1 || rc=$?
|
|
480
521
|
_t "둘 다 착지 → 전건 착지(0)" 0 "$rc"
|
|
481
522
|
|
|
523
|
+
# P3 — «접두어:번호» ID (AQ-20261028-9). 다른 arXiv 번호만 있는 타깃에서 착지로 읽히면 안 되고
|
|
524
|
+
# (옛 추출은 토큰이 `arXiv` 하나라 rc=0), 공백 표기 `arXiv 2610.x` 착지문은 잡아야 한다.
|
|
525
|
+
printf '# digest\n## 📌 FH Immediate Application Candidates\n\n- **Q1** — `arXiv:2610.99999` 를 게이트에\n\n## ⚠️ Warning Signals\n' > "$T/digest_id.md"
|
|
526
|
+
printf 'forge-harness session card\narXiv:2610.11111 은 다른 논문이다\n' > "$T/tgt/idcard.md"
|
|
527
|
+
rc=0; DLC_CONTROLS="forge-harness session" bash "$SELF_DIR/$(basename "${BASH_SOURCE[0]}")" "$T/digest_id.md" "$T/tgt/idcard.md" >/dev/null 2>&1 || rc=$?
|
|
528
|
+
_t "다른 arXiv 번호만 있음 → 미착지(1), 접두어로 착지 안 읽는다" 1 "$rc"
|
|
529
|
+
printf '설계 근거 arXiv 2610.99999 (공백 표기)\n' >> "$T/tgt/idcard.md"
|
|
530
|
+
rc=0; DLC_CONTROLS="forge-harness session" bash "$SELF_DIR/$(basename "${BASH_SOURCE[0]}")" "$T/digest_id.md" "$T/tgt/idcard.md" >/dev/null 2>&1 || rc=$?
|
|
531
|
+
_t "같은 번호 공백 표기 → 착지(0)" 0 "$rc"
|
|
532
|
+
# P3-b — 출처 아닌 `이름:값` 은 종전대로 이름을 건다, 출처 접두어는 지운 채 맞추지 않는다(codex R1)
|
|
533
|
+
printf '# digest\n## 📌 FH Immediate Application Candidates\n\n- **Q2** — `timeout:10000` 로 늘린다\n- **Q3** — `GN:36254` 글을 근거로\n- **Q4** — `HN:123` 스레드\n\n## ⚠️ Warning Signals\n' > "$T/digest_kv.md"
|
|
534
|
+
printf 'forge-harness session card\n대기 10000ms 와 HN:36254 는 다른 이야기다 · HN:12345 도 다르다\n' > "$T/tgt/kvcard.md"
|
|
535
|
+
# 후보별로 본다 — rc=1 은 «하나라도 미착지» 라 한쪽만 오착지해도 통과한다
|
|
536
|
+
local kvout; kvout="$(DLC_CONTROLS="forge-harness session" bash "$SELF_DIR/$(basename "${BASH_SOURCE[0]}")" "$T/digest_kv.md" "$T/tgt/kvcard.md" 2>&1)"
|
|
537
|
+
rc=0; printf '%s\n' "$kvout" | grep -qE '후보 Q2[[:space:]]+미착지' || rc=1
|
|
538
|
+
_t "값만(10000) → Q2 미착지" 0 "$rc"
|
|
539
|
+
rc=0; printf '%s\n' "$kvout" | grep -qE '후보 Q3[[:space:]]+미착지' || rc=1
|
|
540
|
+
_t "다른 출처 같은 번호(HN:36254) → Q3 미착지" 0 "$rc"
|
|
541
|
+
rc=0; printf '%s\n' "$kvout" | grep -qE '후보 Q4[[:space:]]+미착지' || rc=1
|
|
542
|
+
_t "번호 접두 일치(HN:123 vs HN:12345) → Q4 미착지" 0 "$rc"
|
|
543
|
+
|
|
544
|
+
# P4 — ignored 축 깊이와 상한(AQ-20261031-4). 깊이 3 의 사본은 착지가 아니고, 상한을 넘으면 그 수를 말한다
|
|
545
|
+
local IG2; IG2="$(mktemp -d -t dlc_d.XXXXXX)" || return 10
|
|
546
|
+
(
|
|
547
|
+
mkdir -p "$IG2/wiki" "$IG2/meta/a/b" && cd "$IG2" && git init -q . && git config user.email t@t && git config user.name t
|
|
548
|
+
printf '# d\n## 📌 FH Immediate Application Candidates\n\n- **D1** — `zzz_top` 반영\n- **D2** — `zzz_deep` 반영\n- **D3** — `zzz_mid` 반영\n\n## end\n' > wiki/digest.md
|
|
549
|
+
touch -t 200101010000 wiki/digest.md
|
|
550
|
+
git add -A && git commit -qm d
|
|
551
|
+
# 컨트롤은 추적 축에도 둔다 — ignored 축이 꺼져도 컨트롤이 살아 있어야 «축이 조용히 꺼짐» 이 10 이 아닌 값으로 드러난다
|
|
552
|
+
printf 'zzz_ctl 추적 축 컨트롤\n' > wiki/ctl.md && git add wiki/ctl.md && git commit -qm c
|
|
553
|
+
printf 'zzz_top 을 반영했다 · zzz_ctl\n' > meta/top.md
|
|
554
|
+
printf 'zzz_deep 이 사본 안에 있다 · zzz_ctl\n' > meta/a/b/deep.md
|
|
555
|
+
printf 'zzz_mid 을 반영한 보고서 · zzz_ctl\n' > meta/a/report.md
|
|
556
|
+
) >/dev/null 2>&1
|
|
557
|
+
local p4out; p4out="$(cd "$IG2" && CLAUDE_PROJECT_DIR="$IG2" DLC_TRACKED_PATHS="wiki" DLC_IGNORED_DIR="meta" DLC_CONTROLS="zzz_ctl" \
|
|
558
|
+
bash "$SELF_DIR/$(basename "${BASH_SOURCE[0]}")" "$IG2/wiki/digest.md" 2>&1)"
|
|
559
|
+
rc=0; printf '%s\n' "$p4out" | grep -qE '후보 D1[[:space:]]+[0-9]+파일' || rc=1
|
|
560
|
+
_t "ignored 축 깊이 1 기록 → D1 착지" 0 "$rc"
|
|
561
|
+
rc=0; printf '%s\n' "$p4out" | grep -qE '후보 D2[[:space:]]+미착지' || rc=1
|
|
562
|
+
_t "ignored 축 깊이 3 사본 → D2 미착지(사본은 착지가 아니다)" 0 "$rc"
|
|
563
|
+
rc=0; printf '%s\n' "$p4out" | grep -qE '후보 D3[[:space:]]+[0-9]+파일' || rc=1
|
|
564
|
+
_t "ignored 축 깊이 2 보고서 → D3 착지(기본 깊이 경계)" 0 "$rc"
|
|
565
|
+
printf 'zzz_top 두 번째 기록 · zzz_ctl\n' > "$IG2/meta/top2.md"
|
|
566
|
+
p4out="$(cd "$IG2" && CLAUDE_PROJECT_DIR="$IG2" DLC_TRACKED_PATHS="wiki" DLC_IGNORED_DIR="meta" DLC_CONTROLS="zzz_ctl" DLC_IGNORED_CAP=1 \
|
|
567
|
+
bash "$SELF_DIR/$(basename "${BASH_SOURCE[0]}")" "$IG2/wiki/digest.md" 2>&1)"
|
|
568
|
+
rc=0; printf '%s\n' "$p4out" | grep -qF 'ignored 축 3건 중 1건만 읽었다' || rc=1
|
|
569
|
+
_t "상한을 넘으면 잘린 수를 말한다(3건 중 1건)" 0 "$rc"
|
|
570
|
+
rc=0; (cd "$IG2" && CLAUDE_PROJECT_DIR="$IG2" DLC_TRACKED_PATHS="wiki" DLC_IGNORED_DIR="meta" DLC_CONTROLS="zzz_ctl" DLC_IGNORED_CAP=1 \
|
|
571
|
+
bash "$SELF_DIR/$(basename "${BASH_SOURCE[0]}")" "$IG2/wiki/digest.md") >/dev/null 2>&1 || rc=$?
|
|
572
|
+
_t "잘린 채 미착지(D2) → 확정 안 함, 미측정(10)" 10 "$rc"
|
|
573
|
+
rc=0; (cd "$IG2" && CLAUDE_PROJECT_DIR="$IG2" DLC_TRACKED_PATHS="wiki" DLC_IGNORED_DIR="meta" DLC_CONTROLS="zzz_ctl" DLC_IGNORED_DEPTH=abc \
|
|
574
|
+
bash "$SELF_DIR/$(basename "${BASH_SOURCE[0]}")" "$IG2/wiki/digest.md") >/dev/null 2>&1 || rc=$?
|
|
575
|
+
_t "깊이 설정이 숫자가 아니면 → HARNESS-ERROR(10), 축을 조용히 끄지 않는다" 10 "$rc"
|
|
576
|
+
rc=0; (cd "$IG2" && CLAUDE_PROJECT_DIR="$IG2" DLC_TRACKED_PATHS="wiki" DLC_IGNORED_DIR="meta" DLC_CONTROLS="zzz_ctl" DLC_IGNORED_DEPTH=0 \
|
|
577
|
+
bash "$SELF_DIR/$(basename "${BASH_SOURCE[0]}")" "$IG2/wiki/digest.md") >/dev/null 2>&1 || rc=$?
|
|
578
|
+
_t "깊이 0 → HARNESS-ERROR(10)(숫자지만 아무것도 안 읽는다)" 10 "$rc"
|
|
579
|
+
rc=0; (cd "$IG2" && CLAUDE_PROJECT_DIR="$IG2" DLC_TRACKED_PATHS="wiki" DLC_IGNORED_DIR="" DLC_CONTROLS="zzz_ctl" IGNORED_FOUND=999 \
|
|
580
|
+
bash "$SELF_DIR/$(basename "${BASH_SOURCE[0]}")" "$IG2/wiki/digest.md") >/dev/null 2>&1 || rc=$?
|
|
581
|
+
_t "상속된 IGNORED_FOUND 는 무시 — ignored 축이 꺼져 있으면 미착지 그대로(1)" 1 "$rc"
|
|
582
|
+
rm -rf "$IG2"
|
|
583
|
+
printf 'timeout 을 올렸고 GN:36254 를 인용했다 · HN:123 도 봤다\n' >> "$T/tgt/kvcard.md"
|
|
584
|
+
rc=0; DLC_CONTROLS="forge-harness session" bash "$SELF_DIR/$(basename "${BASH_SOURCE[0]}")" "$T/digest_kv.md" "$T/tgt/kvcard.md" >/dev/null 2>&1 || rc=$?
|
|
585
|
+
_t "이름(timeout) · 같은 출처 ID(GN:36254) → 착지(0)" 0 "$rc"
|
|
586
|
+
|
|
482
587
|
# N1 — 컨트롤 사망(타깃에 컨트롤 토큰이 없다) → HARNESS-ERROR(10), PASS 도 FAIL 도 아님
|
|
483
588
|
printf 'allow_force_pushes\nprime_agent_sister_asset\n' > "$T/tgt/nocontrol.md"
|
|
484
589
|
rc=0; bash "$SELF_DIR/$(basename "${BASH_SOURCE[0]}")" "$T/digest.md" "$T/tgt/nocontrol.md" >/dev/null 2>&1 || rc=$?
|
|
@@ -0,0 +1,456 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""digest_slow_leg.py — the frontier digest's weekly "slow leg": conference channels and tech blogs.
|
|
3
|
+
|
|
4
|
+
Why (2026-10-29): the daily legs (HN · arXiv · TLDR · GeekNews · launch channels · vendor changelogs)
|
|
5
|
+
never reach conference talk archives or company tech blogs, and SKILL.md filed YouTube as a walled
|
|
6
|
+
channel. A channel's upload list is a plain Atom feed (youtube.com/feeds/videos.xml?channel_id=…),
|
|
7
|
+
so listing new talks needs no video access; reading a talk is video-ingest's job, not this script's.
|
|
8
|
+
Measured the same day: that feed answered 404 for every channel tried, including a well-known control
|
|
9
|
+
channel, and answered again a few hours later — intermittent, so a youtube row falls back to `yt-dlp --flat-playlist` (public listing, no download) and
|
|
10
|
+
the output names which transport produced the list. Neither works -> UNREACHABLE, not 0. The fallback
|
|
11
|
+
fires on 404 only: a 403/429 is a refusal, and a refusal is never retried another way.
|
|
12
|
+
Talks come out yearly and run 30-40 minutes, so this leg is weekly and lists, it does not summarize.
|
|
13
|
+
|
|
14
|
+
The source list is operator-local (gitignored) on purpose: which companies a person follows can
|
|
15
|
+
identify their employer, and this repo is public. Nothing here names a source.
|
|
16
|
+
|
|
17
|
+
Rules this script keeps:
|
|
18
|
+
- A feed that refuses an automated client (403 · 429 · any HTTP error) is UNREACHABLE(<code>).
|
|
19
|
+
It is never retried with a different client identity. The operator hands those in by hand.
|
|
20
|
+
- A feed that answered but parsed to zero entries is PARSE-ZERO; malformed XML is PARSE-ERROR.
|
|
21
|
+
Neither is "0 new" — both are instrument problems until shown otherwise.
|
|
22
|
+
- "0 new" is only printed when entries parsed and all were already seen.
|
|
23
|
+
- The listing is APPENDED to a dated file BEFORE the seen-set is saved, so neither a lost stdout nor
|
|
24
|
+
a same-day rerun loses items.
|
|
25
|
+
- A week where no source was read does not count as done: `due` stays DUE.
|
|
26
|
+
- A source seen for the first time, or moved from its feed to the yt-dlp listing, is seeded
|
|
27
|
+
(recorded as seen, not listed) and says so — never a flood of a whole channel as "new". The
|
|
28
|
+
yt-dlp -> feed direction needs no reseed (the feed's ~15 items are a subset of what was seen).
|
|
29
|
+
|
|
30
|
+
Usage:
|
|
31
|
+
digest_slow_leg.py run [--sources F] [--state F] [--out F] [--backfill] [--dry-run]
|
|
32
|
+
digest_slow_leg.py due [--state F] [--days 7]
|
|
33
|
+
digest_slow_leg.py --self-test
|
|
34
|
+
|
|
35
|
+
Source file (TSV, '#' comments): id <TAB> kind <TAB> target <TAB> label
|
|
36
|
+
kind = feed (RSS or Atom URL) | youtube (a channel id, UC…). Duplicate ids are rejected.
|
|
37
|
+
Defaults: $FH_DIGEST_SLOW_SOURCES or <repo>/tracks/_meta/digest_slow_sources.tsv,
|
|
38
|
+
$FH_DIGEST_SLOW_STATE or <repo>/tracks/_meta/digest_slow_state.json,
|
|
39
|
+
--out <repo>/tracks/_meta/digest_slow_<YYYY-MM-DD>.md
|
|
40
|
+
exit (run): 0 every source read · 4 ran, but at least one source UNREACHABLE/PARSE-* (listing still
|
|
41
|
+
written) · 2 source file missing/invalid or state file invalid
|
|
42
|
+
exit (due): 0 due · 3 not due · 2 state file invalid (read as UNMEASURED, never as not-due)
|
|
43
|
+
exit (self-test): 0 pass · 1 fail
|
|
44
|
+
"""
|
|
45
|
+
import copy, json, math, os, shutil, subprocess, sys, tempfile, time, urllib.error, urllib.request
|
|
46
|
+
import xml.etree.ElementTree as ET
|
|
47
|
+
|
|
48
|
+
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
49
|
+
UA = "fh-digest-slow-leg/1 (+weekly feed listing)"
|
|
50
|
+
ATOM = "{http://www.w3.org/2005/Atom}"
|
|
51
|
+
MAX_BYTES = 5_000_000
|
|
52
|
+
SLACK = 3600 # a daily runner starts at the same clock time; a few seconds' drift must not slip a week
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class StateInvalid(Exception):
|
|
56
|
+
pass
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _arg(argv, name, default=None):
|
|
60
|
+
return argv[argv.index(name) + 1] if name in argv and argv.index(name) + 1 < len(argv) else default
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def load_sources(path):
|
|
64
|
+
rows, ids = [], set()
|
|
65
|
+
for n, line in enumerate(open(path, encoding="utf-8"), 1):
|
|
66
|
+
line = line.rstrip("\n")
|
|
67
|
+
if not line.strip() or line.lstrip().startswith("#"):
|
|
68
|
+
continue
|
|
69
|
+
parts = line.split("\t")
|
|
70
|
+
if len(parts) < 3 or parts[1] not in ("feed", "youtube") or not parts[2].strip() or not parts[0].strip():
|
|
71
|
+
raise ValueError(f"{path}:{n}: want id<TAB>feed|youtube<TAB>target[<TAB>label]")
|
|
72
|
+
sid = parts[0].strip()
|
|
73
|
+
if sid in ids:
|
|
74
|
+
raise ValueError(f"{path}:{n}: duplicate id {sid!r} (two rows would share one seen-set)")
|
|
75
|
+
ids.add(sid)
|
|
76
|
+
rows.append({"id": sid, "kind": parts[1], "target": parts[2].strip(),
|
|
77
|
+
"label": parts[3].strip() if len(parts) > 3 and parts[3].strip() else sid})
|
|
78
|
+
if not rows:
|
|
79
|
+
raise ValueError(f"{path}: no sources (comments only) — measuring nothing is not '0 new'")
|
|
80
|
+
return rows
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def load_state(path):
|
|
84
|
+
if not os.path.exists(path):
|
|
85
|
+
return {}
|
|
86
|
+
try:
|
|
87
|
+
st = json.load(open(path, encoding="utf-8"))
|
|
88
|
+
if not isinstance(st, dict):
|
|
89
|
+
raise ValueError("not an object")
|
|
90
|
+
lr = st.get("last_run", 0)
|
|
91
|
+
if isinstance(lr, bool) or not isinstance(lr, (int, float)) or not math.isfinite(lr) or lr < 0:
|
|
92
|
+
raise ValueError(f"last_run is {lr!r}")
|
|
93
|
+
seen = st.get("seen", {})
|
|
94
|
+
if not isinstance(seen, dict) or not all(isinstance(v, list) and all(isinstance(k, str) for k in v) for v in seen.values()):
|
|
95
|
+
raise ValueError("seen must map id -> list of strings")
|
|
96
|
+
via = st.get("via", {})
|
|
97
|
+
if not isinstance(via, dict) or not all(v in ("feed", "yt-dlp") for v in via.values()):
|
|
98
|
+
raise ValueError("via must map id -> feed|yt-dlp")
|
|
99
|
+
return st
|
|
100
|
+
except Exception as e:
|
|
101
|
+
raise StateInvalid(f"{path}: {type(e).__name__}: {e}")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def save_atomic(path, text):
|
|
105
|
+
d = os.path.dirname(os.path.abspath(path))
|
|
106
|
+
fd, tmp = tempfile.mkstemp(dir=d, prefix=".slowleg_")
|
|
107
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
108
|
+
f.write(text)
|
|
109
|
+
os.replace(tmp, path)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def feed_url(src):
|
|
113
|
+
if src["kind"] == "youtube":
|
|
114
|
+
return "https://www.youtube.com/feeds/videos.xml?channel_id=" + src["target"]
|
|
115
|
+
return src["target"]
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def fetch(url):
|
|
119
|
+
"""Return (status, body). status is 'OK' or 'UNREACHABLE(<why>)'. One attempt, one identity."""
|
|
120
|
+
try:
|
|
121
|
+
req = urllib.request.Request(url, headers={"User-Agent": UA})
|
|
122
|
+
with urllib.request.urlopen(req, timeout=20) as r:
|
|
123
|
+
return "OK", r.read(MAX_BYTES)
|
|
124
|
+
except urllib.error.HTTPError as e:
|
|
125
|
+
return f"UNREACHABLE({e.code})", b""
|
|
126
|
+
except Exception as e: # DNS, timeout, refused, missing file:// path
|
|
127
|
+
return f"UNREACHABLE({type(e).__name__})", b""
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def parse(body):
|
|
131
|
+
"""Return (entries, keyless). Raises ET.ParseError on malformed XML."""
|
|
132
|
+
root = ET.fromstring(body)
|
|
133
|
+
out, keyless = [], 0
|
|
134
|
+
for it in root.iter("item"): # RSS 2.0
|
|
135
|
+
title = (it.findtext("title") or "").strip()
|
|
136
|
+
link = (it.findtext("link") or "").strip()
|
|
137
|
+
date = (it.findtext("pubDate") or "").strip()
|
|
138
|
+
key = (it.findtext("guid") or "").strip() or link or (f"t:{title}" if title else "")
|
|
139
|
+
if not key:
|
|
140
|
+
keyless += 1; continue
|
|
141
|
+
out.append({"key": key, "title": title, "link": link, "date": date})
|
|
142
|
+
for e in root.iter(ATOM + "entry"): # Atom (YouTube channel feeds are Atom)
|
|
143
|
+
links = e.findall(ATOM + "link")
|
|
144
|
+
alt = [l for l in links if l.get("rel", "alternate") == "alternate"]
|
|
145
|
+
link = ((alt or links)[0].get("href") if (alt or links) else "") or ""
|
|
146
|
+
title = (e.findtext(ATOM + "title") or "").strip()
|
|
147
|
+
date = (e.findtext(ATOM + "published") or e.findtext(ATOM + "updated") or "").strip()
|
|
148
|
+
key = (e.findtext(ATOM + "id") or "").strip() or link or (f"t:{title}" if title else "")
|
|
149
|
+
if not key:
|
|
150
|
+
keyless += 1; continue
|
|
151
|
+
out.append({"key": key, "title": title, "link": link, "date": date})
|
|
152
|
+
return out, keyless
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def yt_list(src):
|
|
156
|
+
"""Channel listing via yt-dlp. Return (status, entries). Entries carry no dates in flat mode, and
|
|
157
|
+
the listing is NOT newest-first (measured 2026-10-29: a 566-video channel listed 2021 uploads
|
|
158
|
+
first), so the whole channel is read and "new" means an id not seen before — never a top-N cut.
|
|
159
|
+
Keys use the Atom feed's form (yt:video:<id>) so either transport names a video the same way."""
|
|
160
|
+
exe = os.environ.get("FH_YTDLP") or shutil.which("yt-dlp")
|
|
161
|
+
if not exe:
|
|
162
|
+
return "UNREACHABLE(no-yt-dlp)", []
|
|
163
|
+
url = f"https://www.youtube.com/channel/{src['target']}/videos"
|
|
164
|
+
try:
|
|
165
|
+
r = subprocess.run([exe, "--flat-playlist", "--print", "%(id)s\t%(title)s", url],
|
|
166
|
+
capture_output=True, text=True, timeout=600)
|
|
167
|
+
except Exception as e:
|
|
168
|
+
return f"UNREACHABLE(yt-dlp:{type(e).__name__})", []
|
|
169
|
+
if r.returncode != 0:
|
|
170
|
+
return f"UNREACHABLE(yt-dlp rc={r.returncode})", []
|
|
171
|
+
out = []
|
|
172
|
+
for line in r.stdout.splitlines():
|
|
173
|
+
vid, _, title = line.partition("\t")
|
|
174
|
+
if vid.strip():
|
|
175
|
+
out.append({"key": "yt:video:" + vid.strip(), "title": title.strip(), "date": "",
|
|
176
|
+
"link": "https://www.youtube.com/watch?v=" + vid.strip()})
|
|
177
|
+
if not out:
|
|
178
|
+
return "PARSE-ZERO(yt-dlp printed no ids)", []
|
|
179
|
+
return "OK", out
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def md_title(s):
|
|
183
|
+
s = " ".join((s or "").split())
|
|
184
|
+
for ch in "\\[]()":
|
|
185
|
+
s = s.replace(ch, "\\" + ch)
|
|
186
|
+
return s or "(제목 없음)"
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def md_link(u):
|
|
190
|
+
u = (u or "").strip()
|
|
191
|
+
return u.replace(" ", "%20").replace("(", "%28").replace(")", "%29") if u else "링크 없음"
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def run(sources, state, backfill, yt=yt_list, url_of=None):
|
|
195
|
+
"""Return (markdown lines, new state, read count, unread count). Does not mutate `state`."""
|
|
196
|
+
url_of = url_of or feed_url
|
|
197
|
+
st = copy.deepcopy(state)
|
|
198
|
+
seen = st.setdefault("seen", {})
|
|
199
|
+
via_prev = st.setdefault("via", {})
|
|
200
|
+
lines, read, unread, n_new, n_seed, partial = [], 0, 0, 0, 0, 0
|
|
201
|
+
t0 = int(time.time())
|
|
202
|
+
for s in sources:
|
|
203
|
+
head = f"### {s['label']} (`{s['id']}`)"
|
|
204
|
+
status, body = fetch(url_of(s))
|
|
205
|
+
via = "feed"
|
|
206
|
+
ents = None
|
|
207
|
+
if status == "UNREACHABLE(404)" and s["kind"] == "youtube": # 404 only: a refusal (403/429) is never retried another way
|
|
208
|
+
first = status
|
|
209
|
+
status, ents = yt(s)
|
|
210
|
+
via = "yt-dlp"
|
|
211
|
+
if status != "OK":
|
|
212
|
+
status = f"{first} · {status}"
|
|
213
|
+
if status != "OK":
|
|
214
|
+
unread += 1
|
|
215
|
+
lines += [head, f"- {status} — 수집 안 됨(0 이 아니다). 운영자가 직접 넘겨야 한다", ""]
|
|
216
|
+
continue
|
|
217
|
+
keyless = 0
|
|
218
|
+
if ents is None:
|
|
219
|
+
try:
|
|
220
|
+
ents, keyless = parse(body)
|
|
221
|
+
except ET.ParseError as e:
|
|
222
|
+
unread += 1
|
|
223
|
+
lines += [head, f"- PARSE-ERROR({e}) — 계기 문제로 본다(0 이 아니다)", ""]
|
|
224
|
+
continue
|
|
225
|
+
if not ents:
|
|
226
|
+
unread += 1
|
|
227
|
+
lines += [head, "- PARSE-ZERO — 응답은 왔는데 항목 0개. 계기 불일치로 본다(0 이 아니다)", ""]
|
|
228
|
+
continue
|
|
229
|
+
read += 1
|
|
230
|
+
lines.append(head + (" — 경로: yt-dlp (채널 Atom 피드가 안 열림)" if via == "yt-dlp" else ""))
|
|
231
|
+
if keyless:
|
|
232
|
+
partial += 1
|
|
233
|
+
lines.append(f"- 식별자 없는 항목 {keyless}개는 판정 못 함(guid · link · title 모두 없음) — 이 소스는 부분 읽음")
|
|
234
|
+
uniq = {}
|
|
235
|
+
for x in ents: # one feed can carry two items with the same key (e.g. same title, no guid/link)
|
|
236
|
+
uniq.setdefault(x["key"], x)
|
|
237
|
+
ents = list(uniq.values())
|
|
238
|
+
keys = set(uniq)
|
|
239
|
+
reseed = None
|
|
240
|
+
if s["id"] not in seen:
|
|
241
|
+
reseed = "처음 등록"
|
|
242
|
+
elif via_prev.get(s["id"], "feed") == "feed" and via == "yt-dlp":
|
|
243
|
+
reseed = "수집 경로 변경(feed → yt-dlp) — 그 사이 새 항목이 있었다면 놓쳤을 수 있다"
|
|
244
|
+
if reseed and not backfill:
|
|
245
|
+
n_seed += 1
|
|
246
|
+
lines += [f"- {reseed}: 항목 {len(ents)}개를 본 것으로 기록했다(목록은 --backfill). 다음 실행부터 새 항목만 나온다", ""]
|
|
247
|
+
seen[s["id"]] = sorted(set(seen.get(s["id"], [])) | keys)
|
|
248
|
+
via_prev[s["id"]] = via
|
|
249
|
+
continue
|
|
250
|
+
old = set(seen.get(s["id"], []))
|
|
251
|
+
new = ents if backfill else [x for x in ents if x["key"] not in old]
|
|
252
|
+
if not new:
|
|
253
|
+
lines.append(f"- 새 항목 0 (읽은 항목 {len(ents)}개 모두 이미 봄)")
|
|
254
|
+
for x in new:
|
|
255
|
+
n_new += 1
|
|
256
|
+
lines.append(f"- {(x['date'][:16] + ' · ') if x['date'] else ''}[{md_title(x['title'])}]({md_link(x['link'])})")
|
|
257
|
+
lines.append("")
|
|
258
|
+
seen[s["id"]] = sorted(old | keys)
|
|
259
|
+
via_prev[s["id"]] = via
|
|
260
|
+
lines.append(f"**느린 갈래 요약: 새 항목 {n_new} · 읽음 {read} · 못 읽음 {unread} · 부분 읽음 {partial} · 목록 없이 기록만(처음 등록·경로 변경) {n_seed} (소스 {len(sources)})**")
|
|
261
|
+
if read: # a week where nothing was read is not a week done; stamp the START so a long run does not slip a week
|
|
262
|
+
st["last_run"] = t0
|
|
263
|
+
return lines, st, read, unread + partial
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def main(argv):
|
|
267
|
+
if "--self-test" in argv:
|
|
268
|
+
return self_test()
|
|
269
|
+
if not argv or argv[0] not in ("run", "due"):
|
|
270
|
+
print(__doc__); return 2
|
|
271
|
+
state_p = _arg(argv, "--state", os.environ.get("FH_DIGEST_SLOW_STATE",
|
|
272
|
+
os.path.join(REPO, "tracks", "_meta", "digest_slow_state.json")))
|
|
273
|
+
try:
|
|
274
|
+
state = load_state(state_p)
|
|
275
|
+
except StateInvalid as e:
|
|
276
|
+
print(f"STATE-INVALID: {e} — UNMEASURED(상태 파일 깨짐). 아직 아님으로 읽지 마라"); return 2
|
|
277
|
+
if argv[0] == "due":
|
|
278
|
+
days = float(_arg(argv, "--days", "7"))
|
|
279
|
+
last = state.get("last_run", 0)
|
|
280
|
+
due = time.time() - last >= days * 86400 - SLACK
|
|
281
|
+
print("DUE" if due else f"NOT-DUE (last run {time.strftime('%Y-%m-%d', time.localtime(last))})")
|
|
282
|
+
return 0 if due else 3
|
|
283
|
+
src_p = _arg(argv, "--sources", os.environ.get("FH_DIGEST_SLOW_SOURCES",
|
|
284
|
+
os.path.join(REPO, "tracks", "_meta", "digest_slow_sources.tsv")))
|
|
285
|
+
if not os.path.exists(src_p):
|
|
286
|
+
print(f"SOURCES-MISSING: {src_p} — 느린 갈래는 UNMEASURED(소스 목록 없음)"); return 2
|
|
287
|
+
try:
|
|
288
|
+
sources = load_sources(src_p)
|
|
289
|
+
except ValueError as e:
|
|
290
|
+
print(f"SOURCES-INVALID: {e}"); return 2
|
|
291
|
+
lines, new_state, read, unread = run(sources, state, "--backfill" in argv)
|
|
292
|
+
text = "\n".join(lines) + "\n"
|
|
293
|
+
print(text, end="")
|
|
294
|
+
if "--dry-run" not in argv:
|
|
295
|
+
out_p = _arg(argv, "--out", os.path.join(REPO, "tracks", "_meta",
|
|
296
|
+
f"digest_slow_{time.strftime('%Y-%m-%d')}.md"))
|
|
297
|
+
prev = open(out_p, encoding="utf-8").read() if os.path.exists(out_p) else ""
|
|
298
|
+
stamp = f"<!-- run {time.strftime('%Y-%m-%d %H:%M:%S')} -->\n"
|
|
299
|
+
save_atomic(out_p, prev + ("\n" if prev else "") + stamp + text) # listing first, appended
|
|
300
|
+
save_atomic(state_p, json.dumps(new_state, ensure_ascii=False, indent=1))
|
|
301
|
+
print(f"(목록 저장: {out_p})")
|
|
302
|
+
return 4 if unread else 0
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def self_test():
|
|
306
|
+
"""Known-pair lanes, offline: file:// feeds, a local HTTP server that answers 403, a fake yt-dlp,
|
|
307
|
+
and main() end to end on temp files. Each lane names the branch it would turn red without."""
|
|
308
|
+
d = tempfile.mkdtemp(prefix="slowleg_")
|
|
309
|
+
saved_env = {k: os.environ.get(k) for k in ("FH_YTDLP", "no_proxy", "NO_PROXY")}
|
|
310
|
+
try: # env and temp dir are restored even if setup (server bind, fixtures) raises
|
|
311
|
+
return _self_test_body(d, saved_env)
|
|
312
|
+
finally:
|
|
313
|
+
for k, v in saved_env.items():
|
|
314
|
+
if v is None:
|
|
315
|
+
os.environ.pop(k, None)
|
|
316
|
+
else:
|
|
317
|
+
os.environ[k] = v
|
|
318
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _self_test_body(d, saved_env):
|
|
322
|
+
import http.server, threading
|
|
323
|
+
os.environ["no_proxy"] = os.environ["NO_PROXY"] = "127.0.0.1,localhost" # lane measures the code, not a proxy
|
|
324
|
+
W = lambda name, text: (open(os.path.join(d, name), "w").write(text), os.path.join(d, name))[1]
|
|
325
|
+
rss = W("r.xml", "<rss><channel><item><title>T1</title><link>https://x/1</link><guid>g1</guid>"
|
|
326
|
+
"<pubDate>Tue, 27 Oct 2026 15:00:00 GMT</pubDate></item><item><title>T2</title>"
|
|
327
|
+
"<link>https://x/2</link></item><item><title>T3</title></item><item></item></channel></rss>")
|
|
328
|
+
atom = W("a.xml", '<feed xmlns="http://www.w3.org/2005/Atom"><entry><id>yt:video:abc</id>'
|
|
329
|
+
'<title>Talk</title><link rel="self" href="https://y/self"/>'
|
|
330
|
+
'<link rel="alternate" href="https://y/abc"/>'
|
|
331
|
+
'<published>2026-10-28T00:00:00+00:00</published></entry></feed>')
|
|
332
|
+
empty = W("e.xml", "<rss><channel></channel></rss>")
|
|
333
|
+
bad = W("b.xml", "<rss><channel><item>")
|
|
334
|
+
|
|
335
|
+
class H(http.server.BaseHTTPRequestHandler):
|
|
336
|
+
def do_GET(self):
|
|
337
|
+
self.send_response(404 if self.path.startswith("/gone") else 403); self.end_headers()
|
|
338
|
+
def log_message(self, *a):
|
|
339
|
+
pass
|
|
340
|
+
srv = http.server.HTTPServer(("127.0.0.1", 0), H)
|
|
341
|
+
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
|
342
|
+
port = srv.server_address[1]
|
|
343
|
+
|
|
344
|
+
src = W("s.tsv", "# test\n"
|
|
345
|
+
f"r\tfeed\tfile://{rss}\tRSS\n"
|
|
346
|
+
f"a\tfeed\tfile://{atom}\tAtom\n"
|
|
347
|
+
f"m\tfeed\tfile://{d}/missing.xml\tMissing\n"
|
|
348
|
+
f"e\tfeed\tfile://{empty}\tEmpty\n"
|
|
349
|
+
f"b\tfeed\tfile://{bad}\tBad\n"
|
|
350
|
+
f"h\tfeed\thttp://127.0.0.1:{port}/feed\tHTTP403\n")
|
|
351
|
+
srcs = load_sources(src)
|
|
352
|
+
ok = True
|
|
353
|
+
|
|
354
|
+
def check(name, cond):
|
|
355
|
+
nonlocal ok
|
|
356
|
+
print(("ok " if cond else "FAIL ") + name); ok = ok and cond
|
|
357
|
+
|
|
358
|
+
try:
|
|
359
|
+
# seeding
|
|
360
|
+
l0, st0, r0, u0 = run(srcs, {}, False)
|
|
361
|
+
t0 = "\n".join(l0)
|
|
362
|
+
check("first run seeds instead of dumping", t0.count("처음 등록: 항목") == 2 and "[T1]" not in t0)
|
|
363
|
+
check("HTTP refusal is UNREACHABLE(403), not 0", "UNREACHABLE(403)" in t0)
|
|
364
|
+
check("missing feed is UNREACHABLE, not 0", "UNREACHABLE(URLError)" in t0)
|
|
365
|
+
check("empty feed is PARSE-ZERO", "PARSE-ZERO" in t0)
|
|
366
|
+
check("malformed feed is PARSE-ERROR", "PARSE-ERROR(" in t0)
|
|
367
|
+
check("summary counts read/unread/partial", "읽음 2 · 못 읽음 4 · 부분 읽음 1 ·" in t0 and "(소스 6)" in t0 and (r0, u0) == (2, 5))
|
|
368
|
+
check("unreached sources not added to seen", not ({"m", "e", "b", "h"} & set(st0["seen"])))
|
|
369
|
+
# listing on a seeded state
|
|
370
|
+
l1, st1, _, _ = run(srcs, {"seen": {"r": [], "a": []}}, False)
|
|
371
|
+
t1 = "\n".join(l1)
|
|
372
|
+
check("rss lists keyed items (guid, link, title fallback)", all(s in t1 for s in ("[T1](https://x/1)", "[T2](https://x/2)", "[T3](링크 없음)")))
|
|
373
|
+
check("summary counts new items (3 rss + 1 atom)", "새 항목 4 ·" in t1)
|
|
374
|
+
check("titles are flattened and escaped", md_title("a]\n## b(") == "a\\] ## b\\(" and md_title("x\\") == "x\\\\")
|
|
375
|
+
check("links with ) or space are encoded", md_link("https://w/a b)") == "https://w/a%20b%29")
|
|
376
|
+
dup = W("dup.xml", "<rss><channel><item><title>Same</title></item><item><title>Same</title></item></channel></rss>")
|
|
377
|
+
ld, _, _, _ = run([{"id": "d", "kind": "feed", "target": f"file://{dup}", "label": "Dup"}], {"seen": {"d": []}}, False)
|
|
378
|
+
check("same-key items listed once", "\n".join(ld).count("[Same]") == 1)
|
|
379
|
+
check("summary counts seeded sources", "목록 없이 기록만(처음 등록·경로 변경) 2" in t0)
|
|
380
|
+
check("keyless rss item skipped and counted", "식별자 없는 항목 1개" in t1)
|
|
381
|
+
check("atom prefers rel=alternate", "[Talk](https://y/abc)" in t1 and "y/self" not in t1)
|
|
382
|
+
l2, _, _, _ = run(srcs, st1, False)
|
|
383
|
+
t2 = "\n".join(l2)
|
|
384
|
+
check("second run: 0 new on rss and atom", t2.count("- 새 항목 0") == 2 and "새 항목 0 ·" in t2 and "[T1]" not in t2)
|
|
385
|
+
check("backfill re-lists seen items", "[T1](https://x/1)" in "\n".join(run(srcs, st1, True)[0]))
|
|
386
|
+
inp = {"seen": {"r": ["g1"]}}
|
|
387
|
+
run(srcs, inp, False)
|
|
388
|
+
check("input state left untouched", inp == {"seen": {"r": ["g1"]}})
|
|
389
|
+
# youtube: fake yt-dlp end to end (real yt_list, real parsing of its output)
|
|
390
|
+
fake = W("fake_ytdlp.sh", '#!/bin/sh\nprintf "v1\\tConf talk\\nv2\\tOther\\n"\n'); os.chmod(fake, 0o755)
|
|
391
|
+
fail = W("fail_ytdlp.sh", "#!/bin/sh\nexit 1\n"); os.chmod(fail, 0o755)
|
|
392
|
+
silent = W("silent_ytdlp.sh", "#!/bin/sh\nexit 0\n"); os.chmod(silent, 0o755)
|
|
393
|
+
ysrc = [{"id": "y", "kind": "youtube", "target": "UCtest", "label": "YT"}]
|
|
394
|
+
no_rss = lambda s: f"http://127.0.0.1:{port}/gone/{s['target']}" # the measured case: feed 404
|
|
395
|
+
refused = lambda s: f"http://127.0.0.1:{port}/feed/{s['target']}" # 403: a refusal
|
|
396
|
+
os.environ["FH_YTDLP"] = fake
|
|
397
|
+
ly, sty, _, _ = run(ysrc, {"seen": {"y": []}, "via": {"y": "yt-dlp"}}, False, url_of=no_rss)
|
|
398
|
+
ty = "\n".join(ly)
|
|
399
|
+
check("youtube falls back to real yt_list and names the transport",
|
|
400
|
+
"[Conf talk](https://www.youtube.com/watch?v=v1)" in ty and "경로: yt-dlp" in ty)
|
|
401
|
+
check("yt-dlp keys use the Atom form", "yt:video:v1" in sty["seen"]["y"])
|
|
402
|
+
lt, _, _, _ = run(ysrc, {"seen": {"y": ["yt:video:abc"]}, "via": {"y": "feed"}}, False, url_of=no_rss)
|
|
403
|
+
check("transport change reseeds instead of flooding", "수집 경로 변경(feed → yt-dlp)" in "\n".join(lt) and "[Conf talk]" not in "\n".join(lt))
|
|
404
|
+
lb, stb, _, _ = run(ysrc, {"seen": {"y": ["yt:video:abc"]}, "via": {"y": "yt-dlp"}}, False,
|
|
405
|
+
url_of=lambda s: f"file://{atom}")
|
|
406
|
+
check("yt-dlp -> feed does not reseed and records feed", "수집 경로 변경" not in "\n".join(lb) and "- 새 항목 0" in "\n".join(lb) and stb["via"]["y"] == "feed")
|
|
407
|
+
os.environ["FH_YTDLP"] = fail
|
|
408
|
+
lf, stf, _, uf = run(ysrc, {}, False, url_of=no_rss)
|
|
409
|
+
check("yt-dlp rc!=0 -> UNREACHABLE naming both transports", "UNREACHABLE(404) · UNREACHABLE(yt-dlp rc=1)" in "\n".join(lf) and uf == 1)
|
|
410
|
+
check("a week with nothing read does not stamp last_run", "last_run" not in stf)
|
|
411
|
+
os.environ["FH_YTDLP"] = silent
|
|
412
|
+
check("yt-dlp printing nothing is PARSE-ZERO, not 0", "PARSE-ZERO(yt-dlp" in "\n".join(run(ysrc, {}, False, url_of=no_rss)[0]))
|
|
413
|
+
os.environ["FH_YTDLP"] = fake
|
|
414
|
+
lr_, str_, _, ur_ = run(ysrc, {"seen": {"y": []}, "via": {"y": "yt-dlp"}}, False, url_of=refused)
|
|
415
|
+
check("403 refusal is never retried through yt-dlp", "UNREACHABLE(403)" in "\n".join(lr_) and "yt-dlp" not in "\n".join(lr_) and ur_ == 1)
|
|
416
|
+
# transport memory: two fallback runs back to back on the returned state, a new upload on the second
|
|
417
|
+
_, s1, _, _ = run(ysrc, {"seen": {"y": ["yt:video:abc"]}, "via": {"y": "feed"}}, False, url_of=no_rss)
|
|
418
|
+
more = W("more_ytdlp.sh", '#!/bin/sh\nprintf "v1\\tConf talk\\nv2\\tOther\\nv3\\tBrand new\\n"\n'); os.chmod(more, 0o755)
|
|
419
|
+
os.environ["FH_YTDLP"] = more
|
|
420
|
+
l2b, _, _, _ = run(ysrc, s1, False, url_of=no_rss)
|
|
421
|
+
t2b = "\n".join(l2b)
|
|
422
|
+
check("fallback remembers its transport: next run lists the new upload, no reseed",
|
|
423
|
+
"[Brand new](https://www.youtube.com/watch?v=v3)" in t2b and "수집 경로 변경" not in t2b)
|
|
424
|
+
# main() end to end
|
|
425
|
+
stp, outp = os.path.join(d, "st.json"), os.path.join(d, "out.md")
|
|
426
|
+
good = W("good.tsv", f"a\tfeed\tfile://{atom}\tAtom\n")
|
|
427
|
+
rc_due0 = main(["due", "--state", stp])
|
|
428
|
+
rc_run = main(["run", "--sources", good, "--state", stp, "--out", outp])
|
|
429
|
+
rc_due1 = main(["due", "--state", stp])
|
|
430
|
+
check("due: no state -> 0, after a good run -> 3", (rc_due0, rc_run, rc_due1) == (0, 0, 3))
|
|
431
|
+
check("listing file written by run", os.path.exists(outp) and "처음 등록" in open(outp).read())
|
|
432
|
+
main(["run", "--sources", good, "--state", stp, "--out", outp])
|
|
433
|
+
txt = open(outp).read()
|
|
434
|
+
check("same-day rerun appends, first listing kept", txt.count("<!-- run ") == 2 and "처음 등록" in txt and "새 항목 0" in txt)
|
|
435
|
+
check("run with an unread source exits 4", main(["run", "--sources", src, "--state", os.path.join(d, "st2.json"), "--out", outp]) == 4)
|
|
436
|
+
open(stp, "w").write('{"seen": {"r": [')
|
|
437
|
+
check("corrupt state: due exits 2, not 3", main(["due", "--state", stp]) == 2)
|
|
438
|
+
check("corrupt state: run exits 2", main(["run", "--sources", good, "--state", stp, "--out", outp]) == 2)
|
|
439
|
+
check("comments-only sources -> 2", main(["run", "--sources", W("c.tsv", "# none\n"), "--state", os.path.join(d, "s4.json"), "--dry-run"]) == 2)
|
|
440
|
+
for bad_state in ('{"last_run": 9999999999, "seen": null}', '{"last_run": "x"}', '{"last_run": NaN}', '{"last_run": 1e400}', '{"seen": {"r": [1]}}', '{"via": {"y": "rss"}}'):
|
|
441
|
+
open(stp, "w").write(bad_state)
|
|
442
|
+
check(f"shallow-valid but broken state -> due 2: {bad_state[:28]}", main(["due", "--state", stp]) == 2)
|
|
443
|
+
check("missing sources -> 2", main(["run", "--sources", os.path.join(d, "nope.tsv"), "--state", os.path.join(d, "s3.json"), "--dry-run"]) == 2)
|
|
444
|
+
for bad_tsv, why in (("x\tvideo\tz\n", "invalid kind"), ("x\tfeed\tu\nx\tfeed\tv\n", "duplicate id")):
|
|
445
|
+
try:
|
|
446
|
+
load_sources(W("bad.tsv", bad_tsv)); check(f"{why} rejected", False)
|
|
447
|
+
except ValueError:
|
|
448
|
+
check(f"{why} rejected", True)
|
|
449
|
+
finally:
|
|
450
|
+
srv.shutdown(); srv.server_close()
|
|
451
|
+
print("self-test:", "PASS" if ok else "FAIL")
|
|
452
|
+
return 0 if ok else 1
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
if __name__ == "__main__":
|
|
456
|
+
sys.exit(main(sys.argv[1:]))
|