@jjh32456/longlive 0.0.0-stage → 2.0.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/CHANGELOG.md +235 -0
- package/LICENSE +21 -0
- package/QUICKSTART.md +362 -0
- package/README.en.md +64 -0
- package/README.md +256 -2
- package/SPEC.md +211 -0
- package/build-info.json +1665 -0
- package/cordis.patch.yml +208 -0
- package/docs/A1-MIGRATION.md +75 -0
- package/docs/ANSWER-GUARD.md +92 -0
- package/docs/ARCHITECTURE.md +128 -0
- package/docs/AUTO-RECALL-WIRING.md +115 -0
- package/docs/AUTO-RECALL.md +237 -0
- package/docs/CONCEPTS.md +143 -0
- package/docs/CONFIG.md +839 -0
- package/docs/ERRORS.md +271 -0
- package/docs/FAQ.md +186 -0
- package/docs/FEATURES.md +579 -0
- package/docs/INDEX-FRESHNESS.md +21 -0
- package/docs/METRICS.md +244 -0
- package/docs/MIGRATION-1.6.0.md +220 -0
- package/docs/OPERATIONS.md +439 -0
- package/docs/PANEL-INTEGRATION.md +190 -0
- package/docs/PRIVACY.md +88 -0
- package/docs/QUICKSTART.md +155 -0
- package/docs/RAW-INDEX-POLICY.md +7 -0
- package/docs/README.en.md +48 -0
- package/docs/RESIDENT-WATCHER.md +90 -0
- package/docs/SESSION-WATCH.md +214 -0
- package/docs/TOOLS.md +184 -0
- package/docs/TROUBLESHOOTING.md +329 -0
- package/icon.svg +11 -0
- package/lib/client.js +436 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +163 -4
- package/runbook.md +343 -0
- package/scripts/archive-digest-build.mjs +668 -0
- package/scripts/auto-truncate-run.ps1 +752 -0
- package/scripts/backfill-auto-cards.mjs +98 -0
- package/scripts/edges-build.mjs +1003 -0
- package/scripts/index-maintain.mjs +39 -0
- package/scripts/index-reconcile.mjs +49 -0
- package/scripts/index-status.mjs +28 -0
- package/scripts/install-resident-watcher.ps1 +15 -0
- package/scripts/install-session-watch.ps1 +332 -0
- package/scripts/install-surgery-task.ps1 +174 -0
- package/scripts/lib/auto-truncate-run.ps1 +512 -0
- package/scripts/lib/session-watch-fixture.mjs +207 -0
- package/scripts/longlive-doctor.mjs +578 -0
- package/scripts/metrics-read.mjs +79 -0
- package/scripts/metrics-sample.mjs +215 -0
- package/scripts/migrate-180.mjs +163 -0
- package/scripts/migrate-200.mjs +8 -0
- package/scripts/migrate-a1-legacy.mjs +62 -0
- package/scripts/migrate-lifecycle.mjs +157 -0
- package/scripts/pack.mjs +392 -0
- package/scripts/recall-index-build.mjs +128 -0
- package/scripts/recall-links-build.mjs +420 -0
- package/scripts/rescore-cards.mjs +36 -0
- package/scripts/resident-watcher-status.ps1 +15 -0
- package/scripts/resident-watcher.ps1 +643 -0
- package/scripts/session-watch-drill.mjs +553 -0
- package/scripts/session-watch-status.ps1 +146 -0
- package/scripts/session-watch.mjs +1367 -0
- package/scripts/surgery-inspect.mjs +122 -0
- package/scripts/surgery-run.cmd +34 -0
- package/scripts/truncate-cli.mjs +279 -0
- package/scripts/unattended-surgery.ps1 +1019 -0
- package/scripts/uninstall-resident-watcher.ps1 +15 -0
- package/scripts/uninstall-session-watch.ps1 +192 -0
- package/scripts/verify-card-anchors.mjs +138 -0
- package/scripts/watch-loop.ps1 +916 -0
- package/src/actions/audit.js +125 -0
- package/src/actions/evidence.js +122 -0
- package/src/actions/fs.js +162 -0
- package/src/activity/index.js +873 -0
- package/src/activity/model.js +351 -0
- package/src/activity/store.js +786 -0
- package/src/activity/summary.js +180 -0
- package/src/activity/thinking.js +191 -0
- package/src/adapters/constants.js +11 -0
- package/src/adapters/engram/data/aliases.json +51 -0
- package/src/adapters/engram/data/policy.json +8 -0
- package/src/adapters/engram/data/routing-rules.json +546 -0
- package/src/adapters/engram/index.js +278 -0
- package/src/adapters/registry.js +315 -0
- package/src/answer/audit.js +238 -0
- package/src/answer/claim-guard.mjs +234 -0
- package/src/answer/evidence.js +30 -0
- package/src/answer/guard.js +1370 -0
- package/src/answer/index.js +1086 -0
- package/src/answer/query.js +111 -0
- package/src/answer/second-hop.mjs +101 -0
- package/src/auto-truncate-status.js +164 -0
- package/src/auto-truncate.js +1181 -0
- package/src/autoprocedure/candidate.js +342 -0
- package/src/autoprocedure/config.js +122 -0
- package/src/autoprocedure/evidence.js +345 -0
- package/src/autoprocedure/index.js +83 -0
- package/src/autoprocedure/ledger.js +329 -0
- package/src/autoprocedure/lint.js +232 -0
- package/src/autoprocedure/llm.js +409 -0
- package/src/autoprocedure/locks.js +102 -0
- package/src/autoprocedure/paths.js +39 -0
- package/src/autoprocedure/privacy.js +87 -0
- package/src/autoprocedure/rules.js +288 -0
- package/src/autoprocedure/runtime.js +718 -0
- package/src/autoprocedure/session-reader.js +328 -0
- package/src/backup.js +310 -0
- package/src/bus/bus.mjs +1446 -0
- package/src/codec.js +269 -0
- package/src/compaction/cut-engine.js +44 -0
- package/src/compaction/engine-core.js +1237 -0
- package/src/compaction/entry.js +228 -0
- package/src/compaction.js +230 -0
- package/src/conclusion.js +366 -0
- package/src/config.js +835 -0
- package/src/d6/runtime.js +517 -0
- package/src/d6/surface.js +181 -0
- package/src/deps.js +189 -0
- package/src/engine-status.js +141 -0
- package/src/features.js +1035 -0
- package/src/handoff/index.js +1077 -0
- package/src/handoff/model.js +1058 -0
- package/src/handoff/store.js +1233 -0
- package/src/heartbeat.js +385 -0
- package/src/home.js +16 -0
- package/src/host-version.js +280 -0
- package/src/hot-truncate-diag.js +98 -0
- package/src/identity/card-marker.js +281 -0
- package/src/identity/handover.js +845 -0
- package/src/identity/index.js +337 -0
- package/src/identity/inject-position.js +133 -0
- package/src/identity/writeback.js +344 -0
- package/src/identity.js +118 -0
- package/src/index.js +647 -0
- package/src/lifecycle/gap-clocks.js +364 -0
- package/src/lifecycle/index.js +269 -0
- package/src/lifecycle/proactive.js +1426 -0
- package/src/live-target.js +212 -0
- package/src/live.js +1603 -0
- package/src/log-rotation.js +153 -0
- package/src/memory/a1-migration.js +190 -0
- package/src/memory/activity-capture.js +229 -0
- package/src/memory/anchor-fallback.js +116 -0
- package/src/memory/anchors.js +194 -0
- package/src/memory/archive-cold-state.mjs +794 -0
- package/src/memory/archive-staging.mjs +305 -0
- package/src/memory/archive.mjs +415 -0
- package/src/memory/audit-records.js +222 -0
- package/src/memory/auto-cards.js +441 -0
- package/src/memory/capture-host.js +297 -0
- package/src/memory/capture.js +496 -0
- package/src/memory/card-anchors.js +203 -0
- package/src/memory/card-priority.js +110 -0
- package/src/memory/cards.js +425 -0
- package/src/memory/catchup.mjs +534 -0
- package/src/memory/conclusion-distill.js +381 -0
- package/src/memory/conclusion-drafts.js +243 -0
- package/src/memory/conflicts.js +1060 -0
- package/src/memory/consolidate.js +834 -0
- package/src/memory/decay.js +311 -0
- package/src/memory/distill.js +485 -0
- package/src/memory/event-index.js +1826 -0
- package/src/memory/evidence-chain.js +295 -0
- package/src/memory/evidence.js +213 -0
- package/src/memory/filter-runner.js +555 -0
- package/src/memory/filter.js +1035 -0
- package/src/memory/forget-v2.js +680 -0
- package/src/memory/forget.js +531 -0
- package/src/memory/frames-activation.js +249 -0
- package/src/memory/frontmatter.js +454 -0
- package/src/memory/fts-query.js +342 -0
- package/src/memory/governance.js +604 -0
- package/src/memory/index-freshness.js +234 -0
- package/src/memory/index.js +435 -0
- package/src/memory/l2-gate.js +169 -0
- package/src/memory/land.mjs +743 -0
- package/src/memory/lifecycle.js +235 -0
- package/src/memory/lock.js +121 -0
- package/src/memory/maintenance.js +1149 -0
- package/src/memory/manifest.js +245 -0
- package/src/memory/memory-health.mjs +607 -0
- package/src/memory/migrate-200.js +1681 -0
- package/src/memory/migrate-lifecycle.js +1808 -0
- package/src/memory/migrate.js +139 -0
- package/src/memory/paths.js +229 -0
- package/src/memory/procedure-candidate.mjs +377 -0
- package/src/memory/procedure.js +982 -0
- package/src/memory/prospective-memory.mjs +362 -0
- package/src/memory/provenance.js +119 -0
- package/src/memory/recall-feedback.mjs +406 -0
- package/src/memory/recall-v2.js +218 -0
- package/src/memory/recall.js +357 -0
- package/src/memory/reconcile.js +265 -0
- package/src/memory/records.js +433 -0
- package/src/memory/reinforce.js +281 -0
- package/src/memory/retention.js +162 -0
- package/src/memory/review.js +124 -0
- package/src/memory/state.js +279 -0
- package/src/memory/tiers.js +168 -0
- package/src/memory/topic-phrases.js +73 -0
- package/src/memory/trust.js +97 -0
- package/src/memory/turn-budget.mjs +290 -0
- package/src/memory/version-chain.js +264 -0
- package/src/memory/wake-bridge.mjs +2999 -0
- package/src/memory/wal.js +137 -0
- package/src/memory/working-frame.js +779 -0
- package/src/metrics/classify.mjs +191 -0
- package/src/metrics/estimate.mjs +108 -0
- package/src/metrics/index.mjs +204 -0
- package/src/metrics/measure.mjs +462 -0
- package/src/metrics/prestep-latency.mjs +307 -0
- package/src/metrics/store.mjs +264 -0
- package/src/original.js +294 -0
- package/src/policy/threshold-policy.js +224 -0
- package/src/policy-profile.js +463 -0
- package/src/recall/anaphora.mjs +87 -0
- package/src/recall/archive-config.mjs +130 -0
- package/src/recall/archive-fallback.mjs +390 -0
- package/src/recall/archive-search.mjs +428 -0
- package/src/recall/archive-state.mjs +588 -0
- package/src/recall/brain.mjs +501 -0
- package/src/recall/cards.mjs +202 -0
- package/src/recall/current-line.mjs +110 -0
- package/src/recall/edges.js +398 -0
- package/src/recall/embedding.mjs +698 -0
- package/src/recall/entities.mjs +112 -0
- package/src/recall/explain.mjs +443 -0
- package/src/recall/force-policy.mjs +138 -0
- package/src/recall/gate-log.mjs +280 -0
- package/src/recall/gate-metrics.mjs +191 -0
- package/src/recall/index.js +1337 -0
- package/src/recall/inject-order.mjs +279 -0
- package/src/recall/link-recall.mjs +183 -0
- package/src/recall/links.mjs +696 -0
- package/src/recall/privacy.mjs +208 -0
- package/src/recall/recall-core.mjs +810 -0
- package/src/recall/shared-visibility.js +302 -0
- package/src/recall/time-normalizer.mjs +196 -0
- package/src/recall/turn-budget-inject.mjs +154 -0
- package/src/retention/cold-gate.mjs +146 -0
- package/src/retention/config.js +163 -0
- package/src/retention/index.js +801 -0
- package/src/role/activation.js +191 -0
- package/src/role/attention.js +318 -0
- package/src/role/base.js +36 -0
- package/src/role/channels.js +423 -0
- package/src/role/index.js +425 -0
- package/src/role/interfaces.js +115 -0
- package/src/role/personality.js +370 -0
- package/src/role/readers.js +151 -0
- package/src/role/relationships.js +477 -0
- package/src/role/store.js +202 -0
- package/src/role/writeprotect.js +373 -0
- package/src/router/aliases.json +182 -0
- package/src/router/background/agent-runner.mjs +239 -0
- package/src/router/background/anchor.mjs +323 -0
- package/src/router/background/audit.mjs +337 -0
- package/src/router/background/budget-ledger.mjs +648 -0
- package/src/router/background/host-sim.mjs +451 -0
- package/src/router/background/index.mjs +81 -0
- package/src/router/background/memory.mjs +63 -0
- package/src/router/background/mock-llm.mjs +203 -0
- package/src/router/background/queue.mjs +224 -0
- package/src/router/background/retry.mjs +255 -0
- package/src/router/background/router.mjs +1459 -0
- package/src/router/background/stream.mjs +276 -0
- package/src/router/background/tool-policy.mjs +255 -0
- package/src/router/design-headings.json +221 -0
- package/src/router/face/config.mjs +155 -0
- package/src/router/face/context.mjs +284 -0
- package/src/router/face/face.mjs +466 -0
- package/src/router/face/identity.mjs +130 -0
- package/src/router/face/index.mjs +65 -0
- package/src/router/face/journal.mjs +119 -0
- package/src/router/face/llm.mjs +252 -0
- package/src/router/face/outbox.mjs +153 -0
- package/src/router/face/paths.mjs +54 -0
- package/src/router/judge.mjs +987 -0
- package/src/router/policies/generic.json +131 -0
- package/src/router/route.js +1766 -0
- package/src/router/router.mjs +535 -0
- package/src/router/routing-rules.json +816 -0
- package/src/router/run-sim.mjs +530 -0
- package/src/router/runtime.js +569 -0
- package/src/router/service/apply.mjs +1218 -0
- package/src/router/service/board.mjs +712 -0
- package/src/router/service/caller.mjs +131 -0
- package/src/router/service/config.mjs +361 -0
- package/src/router/service/context.mjs +314 -0
- package/src/router/service/hint.mjs +668 -0
- package/src/router/service/lease.mjs +494 -0
- package/src/router/service/live.mjs +251 -0
- package/src/router/service/lock.mjs +550 -0
- package/src/router/service/merge.mjs +255 -0
- package/src/router/service/model-resolve.mjs +350 -0
- package/src/router/service/paths.mjs +168 -0
- package/src/router/service/proposals.mjs +1461 -0
- package/src/router/service/queue.mjs +477 -0
- package/src/router/service/reconcile.mjs +271 -0
- package/src/router/service/service.mjs +2998 -0
- package/src/router/service/sources.mjs +352 -0
- package/src/router/service/status.mjs +520 -0
- package/src/router/service/store.mjs +476 -0
- package/src/router/service/ticklock.mjs +239 -0
- package/src/router/service/tokens.mjs +95 -0
- package/src/router/service/tools.mjs +248 -0
- package/src/router/service/wake.mjs +544 -0
- package/src/router/service/wal.mjs +685 -0
- package/src/router/shadow.mjs +821 -0
- package/src/surgery-recovery.js +1909 -0
- package/src/tool-output.js +485 -0
- package/src/tools.js +3262 -0
- package/src/truncate-visible.js +2416 -0
- package/src/truncate.js +999 -0
- package/src/ui/actions.js +1312 -0
- package/src/ui/flags.js +259 -0
- package/src/ui/panel-api.js +371 -0
- package/src/ui/panel-auth.js +251 -0
- package/src/ui/panel-integrity.js +243 -0
- package/src/ui/routes-readonly.js +759 -0
- package/src/ui/routes.js +284 -0
- package/src/util/append-store.js +368 -0
- package/src/util/local-day.js +30 -0
- package/src/util/redact.js +227 -0
- package/src/util/stale-locks.js +148 -0
- package/src/version.js +99 -0
- package/test/fixtures/pre-step-container.mjs +100 -0
- package/test/p1_probe.mjs +97 -0
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
// src/autoprocedure/ledger.js — 记账、计数与 stalled 告警(D6。
|
|
2
|
+
//
|
|
3
|
+
// 唯一账本:`.longlive/logs/auto-procedure.jsonl`(append-store:单写锁 + fsync)。
|
|
4
|
+
// 固定字段:at, day, attemptId, sessionId, turn, kind, reason?, tokens{in,out},
|
|
5
|
+
// model?, candidateSlug?, generator?, dropped?
|
|
6
|
+
// `turns.jsonl` 永远不写(N3:运行前后字节不变)。
|
|
7
|
+
//
|
|
8
|
+
// N3 账本语义(红队 18:15 澄清):一次尝试会写多行(sample / llm / draft|reject),
|
|
9
|
+
// 不要断言「总行数 = 尝试次数」。改为:
|
|
10
|
+
// * 每行带 attemptId;
|
|
11
|
+
// * 每个 attemptId 恰好 1 行终态(draft / reject / stale 三者之一);
|
|
12
|
+
// * sample 行数 = 尝试数;terminal 行数 = 尝试数;llm / llm_enable_ack 独立计数;
|
|
13
|
+
// * 独立 stale(周期抽查报告,没有 attemptId)单独计数。
|
|
14
|
+
//
|
|
15
|
+
// 计数与告警只记状态码/计数,不记内容(C 条)。stalled 状态写到既有的
|
|
16
|
+
// `.longlive/memory-state.json` 的 `autoProcedure` 字段,形状:
|
|
17
|
+
// { state: "stalled"|"ok", lastDraftAt, drafted7d, rejectTop }
|
|
18
|
+
// 连续 7 天 drafted=0 且 enabled=true 且账本已运行 ≥7 天 → stalled;
|
|
19
|
+
// rejectTop 里带同一原因连续出现的天数(≥3 天即可作为「需要处理的失败」上报)。
|
|
20
|
+
|
|
21
|
+
import { appendJsonLine, readJsonLines } from '../util/append-store.js';
|
|
22
|
+
import { dayString } from '../memory/frontmatter.js';
|
|
23
|
+
import { readState, updateState } from '../memory/state.js';
|
|
24
|
+
import { autoProcedurePaths } from './paths.js';
|
|
25
|
+
import { AUTOPROCEDURE_STALLED_DAYS, AUTOPROCEDURE_REPEAT_REJECT_DAYS } from './config.js';
|
|
26
|
+
|
|
27
|
+
export const LEDGER_SCHEMA = 'auto-procedure/v1';
|
|
28
|
+
export const LEDGER_KINDS = Object.freeze(['sample', 'draft', 'reject', 'llm', 'stale', 'llm_enable_ack']);
|
|
29
|
+
export const TERMINAL_KINDS = Object.freeze(['draft', 'reject', 'stale']);
|
|
30
|
+
export const REJECT_REASONS = Object.freeze([
|
|
31
|
+
// v0.3 §3.9 枚举
|
|
32
|
+
'privacy', 'evidence', 'budget', 'llm_timeout', 'llm_unavailable', 'parse', 'too_big',
|
|
33
|
+
// 实现层失败原因(非内容):不计入内容隐私面,只用于对账
|
|
34
|
+
'ineligible', 'lock', 'quota', 'io',
|
|
35
|
+
]);
|
|
36
|
+
export const LLM_REASONS = Object.freeze(['output_unusable']);
|
|
37
|
+
/**
|
|
38
|
+
* D2:这类 reject 是「配置/前置条件」而不是「需要人工处理的失败」,
|
|
39
|
+
* 保留在 rejectTop 的计数里(可观测性不降),但不算进连续 ≥3 天的告警天数。
|
|
40
|
+
*/
|
|
41
|
+
export const REJECT_ATTENTION_EXCLUDED = Object.freeze(['quota', 'ineligible']);
|
|
42
|
+
export const LEDGER_READ_LIMIT = 5000;
|
|
43
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
44
|
+
|
|
45
|
+
function dateOf(now) {
|
|
46
|
+
const value = typeof now === 'function' ? now() : (now ?? Date.now());
|
|
47
|
+
const date = value instanceof Date ? value : new Date(value);
|
|
48
|
+
return Number.isNaN(date.getTime()) ? new Date() : date;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function isoOf(now) {
|
|
52
|
+
return dateOf(now).toISOString();
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function msOf(now) {
|
|
56
|
+
return dateOf(now).getTime();
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Build the fixed-shape ledger row (undefined optionals are omitted). */
|
|
60
|
+
export function makeLedgerRow({
|
|
61
|
+
attemptId = null,
|
|
62
|
+
sessionId = null,
|
|
63
|
+
turn = null,
|
|
64
|
+
kind,
|
|
65
|
+
reason = null,
|
|
66
|
+
tokens = null,
|
|
67
|
+
model = null,
|
|
68
|
+
candidateSlug = null,
|
|
69
|
+
generator = null,
|
|
70
|
+
dropped = null,
|
|
71
|
+
now = new Date(),
|
|
72
|
+
}) {
|
|
73
|
+
const date = dateOf(now);
|
|
74
|
+
const row = {
|
|
75
|
+
schema: LEDGER_SCHEMA,
|
|
76
|
+
at: date.toISOString(),
|
|
77
|
+
day: dayString(date),
|
|
78
|
+
kind: LEDGER_KINDS.includes(kind) ? kind : 'reject',
|
|
79
|
+
};
|
|
80
|
+
if (attemptId !== null) row.attemptId = attemptId;
|
|
81
|
+
if (sessionId !== null) row.sessionId = sessionId;
|
|
82
|
+
if (Number.isInteger(turn)) row.turn = turn;
|
|
83
|
+
if (reason !== null) row.reason = String(reason);
|
|
84
|
+
const inTokens = Number.isInteger(tokens?.in) ? tokens.in : 0;
|
|
85
|
+
const outTokens = Number.isInteger(tokens?.out) ? tokens.out : 0;
|
|
86
|
+
row.tokens = { in: inTokens, out: outTokens };
|
|
87
|
+
if (model !== null) row.model = String(model);
|
|
88
|
+
if (candidateSlug !== null) row.candidateSlug = String(candidateSlug);
|
|
89
|
+
if (generator !== null) row.generator = String(generator);
|
|
90
|
+
if (dropped && typeof dropped === 'object') {
|
|
91
|
+
row.dropped = {};
|
|
92
|
+
for (const [key, value] of Object.entries(dropped)) {
|
|
93
|
+
if (Number.isInteger(value) && value > 0) row.dropped[key] = value;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return row;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Append one row to the ledger via append-store (never throws). */
|
|
100
|
+
export function appendLedgerRow({ memoryRoot, row, now = null, append = null }) {
|
|
101
|
+
// D2:reject/llm 的 reason 必须是固定枚举,未知 reason 不得落账本(不含自由文本)。
|
|
102
|
+
// stale 行的 reason 是 E_ 开头的证据错误码(抽查报告),只允许代码形状。
|
|
103
|
+
const kind = row?.kind;
|
|
104
|
+
const reason = row?.reason;
|
|
105
|
+
if (reason !== undefined && reason !== null) {
|
|
106
|
+
if (kind === 'stale') {
|
|
107
|
+
if (typeof reason !== 'string' || !/^E_[A-Z0-9_]{1,64}$/.test(reason)) {
|
|
108
|
+
return { ok: false, code: 'E_AP_BAD_REASON', reason: String(reason) };
|
|
109
|
+
}
|
|
110
|
+
} else {
|
|
111
|
+
const allowed = kind === 'llm' ? [...LLM_REASONS, ...REJECT_REASONS] : REJECT_REASONS;
|
|
112
|
+
if (!allowed.includes(reason)) {
|
|
113
|
+
return { ok: false, code: 'E_AP_BAD_REASON', reason: String(reason) };
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
const paths = autoProcedurePaths(memoryRoot);
|
|
118
|
+
const at = now == null ? new Date() : now;
|
|
119
|
+
const withTime = row.at ? row : { ...row, at: isoOf(at), day: dayString(dateOf(at)) };
|
|
120
|
+
if (typeof append === 'function') return append(paths.ledger, withTime);
|
|
121
|
+
return appendJsonLine({
|
|
122
|
+
file: paths.ledger,
|
|
123
|
+
row: withTime,
|
|
124
|
+
label: 'auto-procedure',
|
|
125
|
+
healthRoot: paths.root,
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Read the ledger; bad lines are counted, never fatal. */
|
|
130
|
+
export function readLedgerRows(memoryRoot, { limit = LEDGER_READ_LIMIT } = {}) {
|
|
131
|
+
const paths = autoProcedurePaths(memoryRoot);
|
|
132
|
+
const read = readJsonLines(paths.ledger, { limit });
|
|
133
|
+
return {
|
|
134
|
+
ok: read.ok,
|
|
135
|
+
present: read.present,
|
|
136
|
+
rows: read.rows,
|
|
137
|
+
badLines: read.badLines,
|
|
138
|
+
file: paths.ledger,
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function dayOfRow(row) {
|
|
143
|
+
return typeof row?.day === 'string' && row.day !== '' ? row.day : String(row?.at ?? '').slice(0, 10);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Counters for one ledger snapshot.
|
|
148
|
+
* @returns {{rows:number, sampled:number, drafts:number, terminals:number,
|
|
149
|
+
* rejects:object, staleStandalone:number, llmCalls:number, acks:number,
|
|
150
|
+
* tokensIn:number, tokensOut:number, lastDraftAt:string|null,
|
|
151
|
+
* drafted7d:number, samples7d:number, firstAt:number|null,
|
|
152
|
+
* rejectTop:{reason:string,count:number,days:number}|null,
|
|
153
|
+
* attempts:number, terminalByAttempt:Map<string,string>, duplicateTerminals:string[]}}
|
|
154
|
+
*/
|
|
155
|
+
export function summarizeLedger(rows, { now = new Date(), windowDays = AUTOPROCEDURE_STALLED_DAYS } = {}) {
|
|
156
|
+
const list = Array.isArray(rows) ? rows : [];
|
|
157
|
+
const nowMs = msOf(now);
|
|
158
|
+
const windowStart = nowMs - windowDays * DAY_MS;
|
|
159
|
+
const summary = {
|
|
160
|
+
rows: list.length,
|
|
161
|
+
sampled: 0,
|
|
162
|
+
drafts: 0,
|
|
163
|
+
terminals: 0,
|
|
164
|
+
terminalByAttempt: new Map(),
|
|
165
|
+
duplicateTerminals: [],
|
|
166
|
+
attempts: 0,
|
|
167
|
+
rejects: {},
|
|
168
|
+
staleStandalone: 0,
|
|
169
|
+
llmCalls: 0,
|
|
170
|
+
acks: 0,
|
|
171
|
+
tokensIn: 0,
|
|
172
|
+
tokensOut: 0,
|
|
173
|
+
lastDraftAt: null,
|
|
174
|
+
drafted7d: 0,
|
|
175
|
+
samples7d: 0,
|
|
176
|
+
firstAt: null,
|
|
177
|
+
rejectTop: null,
|
|
178
|
+
};
|
|
179
|
+
const attempts = new Set();
|
|
180
|
+
const rejectReasons = new Map();
|
|
181
|
+
const rejectDays = new Map();
|
|
182
|
+
let firstMs = null;
|
|
183
|
+
|
|
184
|
+
for (const row of list) {
|
|
185
|
+
if (!row || typeof row !== 'object') continue;
|
|
186
|
+
const kind = row.kind;
|
|
187
|
+
const at = Date.parse(String(row.at ?? ''));
|
|
188
|
+
if (Number.isFinite(at) && (firstMs === null || at < firstMs)) firstMs = at;
|
|
189
|
+
if (Number.isInteger(row.tokens?.in)) summary.tokensIn += row.tokens.in;
|
|
190
|
+
if (Number.isInteger(row.tokens?.out)) summary.tokensOut += row.tokens.out;
|
|
191
|
+
const attemptId = typeof row.attemptId === 'string' && row.attemptId !== '' ? row.attemptId : null;
|
|
192
|
+
if (attemptId !== null) attempts.add(attemptId);
|
|
193
|
+
|
|
194
|
+
if (kind === 'sample') {
|
|
195
|
+
summary.sampled += 1;
|
|
196
|
+
if (Number.isFinite(at) && at >= windowStart) summary.samples7d += 1;
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
if (kind === 'llm_enable_ack') {
|
|
200
|
+
summary.acks += 1;
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
if (kind === 'llm') {
|
|
204
|
+
summary.llmCalls += 1;
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
if (kind === 'stale' && attemptId === null) {
|
|
208
|
+
summary.staleStandalone += 1;
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
if (!TERMINAL_KINDS.includes(kind)) continue;
|
|
212
|
+
summary.terminals += 1;
|
|
213
|
+
if (attemptId !== null) {
|
|
214
|
+
if (summary.terminalByAttempt.has(attemptId)) summary.duplicateTerminals.push(attemptId);
|
|
215
|
+
summary.terminalByAttempt.set(attemptId, kind);
|
|
216
|
+
}
|
|
217
|
+
if (kind === 'draft') {
|
|
218
|
+
summary.drafts += 1;
|
|
219
|
+
if (Number.isFinite(at) && at >= windowStart) summary.drafted7d += 1;
|
|
220
|
+
if (summary.lastDraftAt === null || String(row.at ?? '') > String(summary.lastDraftAt)) {
|
|
221
|
+
summary.lastDraftAt = String(row.at ?? '');
|
|
222
|
+
}
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
if (kind === 'reject') {
|
|
226
|
+
const reason = typeof row.reason === 'string' && row.reason !== '' ? row.reason : 'unknown';
|
|
227
|
+
summary.rejects[reason] = (summary.rejects[reason] ?? 0) + 1;
|
|
228
|
+
const inWindow = Number.isFinite(at) && at >= windowStart;
|
|
229
|
+
if (inWindow) {
|
|
230
|
+
rejectReasons.set(reason, (rejectReasons.get(reason) ?? 0) + 1);
|
|
231
|
+
// D2:quota/ineligible 只计数,不算「连续同因需处理」的天数。
|
|
232
|
+
if (REJECT_ATTENTION_EXCLUDED.includes(reason)) continue;
|
|
233
|
+
const day = dayOfRow(row);
|
|
234
|
+
if (!rejectDays.has(reason)) rejectDays.set(reason, new Set());
|
|
235
|
+
rejectDays.get(reason).add(day);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
summary.attempts = attempts.size;
|
|
240
|
+
summary.firstAt = firstMs;
|
|
241
|
+
let best = null;
|
|
242
|
+
for (const [reason, count] of rejectReasons.entries()) {
|
|
243
|
+
const days = rejectDays.get(reason)?.size ?? 0;
|
|
244
|
+
if (best === null || count > best.count || (count === best.count && reason < best.reason)) {
|
|
245
|
+
best = { reason, count, days, needsAttention: days >= AUTOPROCEDURE_REPEAT_REJECT_DAYS };
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
summary.rejectTop = best;
|
|
249
|
+
return summary;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Drafts per local day, total and per session (for budget/quota checks). */
|
|
253
|
+
export function draftsToday(rows, { day = null, now = new Date() } = {}) {
|
|
254
|
+
const targetDay = day ?? dayString(now instanceof Date ? now : new Date(now));
|
|
255
|
+
let total = 0;
|
|
256
|
+
const bySession = new Map();
|
|
257
|
+
for (const row of Array.isArray(rows) ? rows : []) {
|
|
258
|
+
if (row?.kind !== 'draft') continue;
|
|
259
|
+
if (dayOfRow(row) !== targetDay) continue;
|
|
260
|
+
total += 1;
|
|
261
|
+
if (typeof row.sessionId === 'string' && row.sessionId !== '') {
|
|
262
|
+
bySession.set(row.sessionId, (bySession.get(row.sessionId) ?? 0) + 1);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
return { day: targetDay, total, bySession };
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** LLM budget/quota consumption for one local day.
|
|
269
|
+
*
|
|
270
|
+
* MAJ-5 语义:`calls` 统计的是**真实 provider 调用尝试**(成功、超时、不可用都算),
|
|
271
|
+
* 预算拒绝本身(llm 行 reason='budget')不计——它没有发生调用。该计数与候选产出
|
|
272
|
+
* 解耦:次数/预算耗尽后只是不再调模型,本地 rules 草稿照常产出候选。
|
|
273
|
+
*/
|
|
274
|
+
export function llmUsageToday(rows, { day = null, now = new Date() } = {}) {
|
|
275
|
+
const targetDay = day ?? dayString(now instanceof Date ? now : new Date(now));
|
|
276
|
+
let calls = 0;
|
|
277
|
+
let tokensIn = 0;
|
|
278
|
+
let tokensOut = 0;
|
|
279
|
+
for (const row of Array.isArray(rows) ? rows : []) {
|
|
280
|
+
if (dayOfRow(row) !== targetDay) continue;
|
|
281
|
+
if (row?.kind === 'llm') {
|
|
282
|
+
if (row.reason !== 'budget') calls += 1;
|
|
283
|
+
tokensIn += Number.isInteger(row.tokens?.in) ? row.tokens.in : 0;
|
|
284
|
+
tokensOut += Number.isInteger(row.tokens?.out) ? row.tokens.out : 0;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
return { day: targetDay, calls, tokensIn, tokensOut, tokens: tokensIn + tokensOut };
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** Read the persisted autoProcedure state block (tolerant; never throws). */
|
|
291
|
+
export function readAutoProcedureState(memoryRoot) {
|
|
292
|
+
try {
|
|
293
|
+
const state = readState(memoryRoot);
|
|
294
|
+
const value = state?.autoProcedure;
|
|
295
|
+
return value && typeof value === 'object' ? value : null;
|
|
296
|
+
} catch {
|
|
297
|
+
return null;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Evaluate the stalled condition and persist it into memory-state.json.
|
|
303
|
+
* Reads only the ledger tail (limit 5000) — no content, no session log.
|
|
304
|
+
*
|
|
305
|
+
* @returns {{ok:boolean, state:object|null, code?:string}}
|
|
306
|
+
*/
|
|
307
|
+
export function evaluateStalled({ memoryRoot, enabled = true, now = new Date() } = {}) {
|
|
308
|
+
if (!enabled) return { ok: false, code: 'E_AP_DISABLED', state: null };
|
|
309
|
+
const read = readLedgerRows(memoryRoot);
|
|
310
|
+
if (!read.ok) return { ok: false, code: 'E_AP_LEDGER_READ', state: null };
|
|
311
|
+
const summary = summarizeLedger(read.rows, { now });
|
|
312
|
+
const nowMs = msOf(now);
|
|
313
|
+
const runningLongEnough = summary.firstAt !== null && (nowMs - summary.firstAt) >= AUTOPROCEDURE_STALLED_DAYS * DAY_MS;
|
|
314
|
+
const stalled = summary.drafted7d === 0 && runningLongEnough;
|
|
315
|
+
const state = {
|
|
316
|
+
state: stalled ? 'stalled' : 'ok',
|
|
317
|
+
lastDraftAt: summary.lastDraftAt,
|
|
318
|
+
drafted7d: summary.drafted7d,
|
|
319
|
+
rejectTop: summary.rejectTop
|
|
320
|
+
? { reason: summary.rejectTop.reason, count: summary.rejectTop.count, days: summary.rejectTop.days }
|
|
321
|
+
: null,
|
|
322
|
+
};
|
|
323
|
+
try {
|
|
324
|
+
updateState(memoryRoot, { autoProcedure: state }, { now: now instanceof Date ? now : new Date(now) });
|
|
325
|
+
return { ok: true, state, summary };
|
|
326
|
+
} catch (error) {
|
|
327
|
+
return { ok: false, code: error?.code ?? 'E_AP_STATE_WRITE', state };
|
|
328
|
+
}
|
|
329
|
+
}
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
// src/autoprocedure/lint.js — 本地确定性 lint(D5,无放行权)。
|
|
2
|
+
//
|
|
3
|
+
// 运行时只跑这 5 类本地规则,不启动子脑、不调 LLM;结果 `issues[]` 写 sidecar。
|
|
4
|
+
// 规则:
|
|
5
|
+
// ① 危险动作黑名单(删除/覆盖/权限/注册表/服务/计划任务/网络/密钥/批量写/安装卸载)
|
|
6
|
+
// ② 证据可验(结构校验 + 本次落盘前校验结果)
|
|
7
|
+
// ③ 与现有 procedures/*.md 的名称/触发词/步骤相似度冲突(只读;同时只读扫描
|
|
8
|
+
// A1 的 staging/auto-cards/*.md 根级,避免与 A1 结论重复)
|
|
9
|
+
// ④ 触发词为空或过窄
|
|
10
|
+
// ⑤ 路径/用户名未归一化(裸盘符绝对路径)
|
|
11
|
+
//
|
|
12
|
+
// 边界(必须写进文档):lint 只证明「未发现这几类问题」,不证明内容正确,
|
|
13
|
+
// 也没有放行权;任何字符串内容(包括看起来像指令的文本)都只当数据检查,
|
|
14
|
+
// 绝不被执行、不改变流程分支、不产生额外副作用。
|
|
15
|
+
|
|
16
|
+
import fs from 'node:fs';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
|
|
19
|
+
import { containsUnnormalizedPath } from './privacy.js';
|
|
20
|
+
import { validateEvidenceItem } from './evidence.js';
|
|
21
|
+
import { composeSectionsText } from './candidate.js';
|
|
22
|
+
|
|
23
|
+
export const LINT_RULES = Object.freeze([
|
|
24
|
+
'DANGEROUS_ACTION',
|
|
25
|
+
'EVIDENCE_UNVERIFIABLE',
|
|
26
|
+
'CONFLICT_EXISTING',
|
|
27
|
+
'TRIGGER_TOO_NARROW',
|
|
28
|
+
'PATH_NOT_NORMALIZED',
|
|
29
|
+
]);
|
|
30
|
+
|
|
31
|
+
/** ① 危险动作黑名单:只做本地正则匹配,绝不出网、绝不执行。 */
|
|
32
|
+
export const DANGEROUS_PATTERNS = Object.freeze([
|
|
33
|
+
{ kind: '删除', re: /(?:\brm\s+-rf\b|\bdel\s+\/|\bRemove-Item\b|\brmdir\b|删除|格式化|\bformat\s+[A-Za-z]:)/i },
|
|
34
|
+
{ kind: '覆盖', re: /(?:覆盖|\boverwrite\b|>\s*[A-Za-z]:\\|--force\b)/i },
|
|
35
|
+
{ kind: '权限', re: /(?:\bchmod\b|\bchown\b|\bicacls\b|\btakeown\b|提权|权限提升|\bsudo\b)/i },
|
|
36
|
+
{ kind: '注册表', re: /(?:\breg\s+add\b|\bregedit\b|\bHKEY_[A-Z_]+|注册表)/i },
|
|
37
|
+
{ kind: '服务', re: /(?:\bsc\s+create\b|\bnet\s+start\b|\bsc\s+delete\b|\bsystemctl\b|服务安装)/i },
|
|
38
|
+
{ kind: '计划任务', re: /(?:\bschtasks\b|\bRegister-ScheduledTask\b|\bcrontab\b|计划任务)/i },
|
|
39
|
+
{ kind: '网络', re: /(?:\bcurl\s+http|\bwget\s+http|\bInvoke-WebRequest\b|\bssh\s|\bscp\s|\bftp\s)/i },
|
|
40
|
+
{ kind: '密钥', re: /(?:\bsk-[A-Za-z0-9]|\bapi[_-]?key\b|\bpassword\b|\bsecret\b|\bcredential\b|密钥)/i },
|
|
41
|
+
{ kind: '批量写', re: /(?:批量|for\s+\/f\b|Get-ChildItem[^\n]*-Recurse[^\n]*\|\s*Remove)/i },
|
|
42
|
+
{ kind: '安装卸载', re: /(?:\bnpm\s+(?:install|i)\b|\bpip\s+install\b|\bwinget\s+install\b|\bchoco\s+install\b|\bmsiexec\b|安装|卸载)/i },
|
|
43
|
+
]);
|
|
44
|
+
|
|
45
|
+
/** ① 危险动作:逐段扫描,命中即记 issue(不阻断候选落盘,但标 high risk)。 */
|
|
46
|
+
export function lintDangerousActions(sections) {
|
|
47
|
+
const issues = [];
|
|
48
|
+
const steps = Array.isArray(sections?.steps) ? sections.steps : [];
|
|
49
|
+
const visits = steps.map((step, index) => ({ step: index + 1, text: String(step ?? '') }));
|
|
50
|
+
visits.push({ step: 0, text: String(sections?.when ?? '') });
|
|
51
|
+
visits.push({ step: 0, text: String(sections?.failureModes ?? '') });
|
|
52
|
+
visits.push({ step: 0, text: String(sections?.example ?? '') });
|
|
53
|
+
for (const visit of visits) {
|
|
54
|
+
for (const pattern of DANGEROUS_PATTERNS) {
|
|
55
|
+
pattern.re.lastIndex = 0;
|
|
56
|
+
const match = pattern.re.exec(visit.text);
|
|
57
|
+
if (match) {
|
|
58
|
+
issues.push({
|
|
59
|
+
code: 'DANGEROUS_ACTION',
|
|
60
|
+
step: visit.step,
|
|
61
|
+
reason: `命中危险动作(${pattern.kind}):${match[0].trim().slice(0, 80)}`,
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return issues;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** ② 证据可验:结构校验 + 本次落盘前校验结果;缺失任何一条都算 issue。 */
|
|
70
|
+
export function lintEvidence(evidence, evidenceResults = null) {
|
|
71
|
+
const issues = [];
|
|
72
|
+
const list = Array.isArray(evidence) ? evidence : [];
|
|
73
|
+
if (list.length === 0) {
|
|
74
|
+
issues.push({ code: 'EVIDENCE_UNVERIFIABLE', step: 0, reason: '候选没有任何证据锚点' });
|
|
75
|
+
return issues;
|
|
76
|
+
}
|
|
77
|
+
const resultByIndex = Array.isArray(evidenceResults) ? evidenceResults : [];
|
|
78
|
+
for (let i = 0; i < list.length; i += 1) {
|
|
79
|
+
const checked = validateEvidenceItem(list[i]);
|
|
80
|
+
if (!checked.ok) {
|
|
81
|
+
issues.push({ code: 'EVIDENCE_UNVERIFIABLE', step: list[i]?.step ?? 0, reason: `证据结构非法:${checked.errors.join(', ')}` });
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
if (resultByIndex.length === 0) {
|
|
85
|
+
issues.push({ code: 'EVIDENCE_UNVERIFIABLE', step: list[i]?.step ?? 0, reason: '证据未在落盘前校验' });
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
const verification = resultByIndex[i]?.result;
|
|
89
|
+
if (!verification || verification.ok !== true) {
|
|
90
|
+
issues.push({
|
|
91
|
+
code: 'EVIDENCE_UNVERIFIABLE',
|
|
92
|
+
step: list[i]?.step ?? 0,
|
|
93
|
+
reason: `证据校验失败:${verification?.code ?? '未校验'}`,
|
|
94
|
+
});
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
// D4/D8:D2 证据的 meta 缺失时接受降级(只做偏移 + redactedSha256 校验),
|
|
98
|
+
// 但必须留一条 issue,让复审者知道这条证据的身份字段没被核对。
|
|
99
|
+
if (list[i]?.from === 'd2' && verification.metaMissing === true) {
|
|
100
|
+
issues.push({
|
|
101
|
+
code: 'EVIDENCE_D2_META_MISSING',
|
|
102
|
+
step: list[i]?.step ?? 0,
|
|
103
|
+
reason: 'D2 meta 缺失,已降级为仅 D2 偏移 + redactedSha256 校验',
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return issues;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function normalizeForSimilarity(text) {
|
|
111
|
+
return String(text ?? '').toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ' ').trim();
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function bigrams(text) {
|
|
115
|
+
const value = normalizeForSimilarity(text).replace(/\s+/g, '');
|
|
116
|
+
const set = new Set();
|
|
117
|
+
for (let i = 0; i < value.length - 1; i += 1) set.add(value.slice(i, i + 2));
|
|
118
|
+
return set;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Deterministic Dice similarity on character bigrams (0..1). */
|
|
122
|
+
export function diceSimilarity(left, right) {
|
|
123
|
+
const a = bigrams(left);
|
|
124
|
+
const b = bigrams(right);
|
|
125
|
+
if (a.size === 0 || b.size === 0) return 0;
|
|
126
|
+
let hit = 0;
|
|
127
|
+
for (const gram of a) if (b.has(gram)) hit += 1;
|
|
128
|
+
return (2 * hit) / (a.size + b.size);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function readCardSummary(file) {
|
|
132
|
+
let text = '';
|
|
133
|
+
try {
|
|
134
|
+
const stat = fs.lstatSync(file);
|
|
135
|
+
if (!stat.isFile() || stat.size > 512 * 1024) return null;
|
|
136
|
+
text = fs.readFileSync(file, 'utf8');
|
|
137
|
+
} catch {
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
const name = /^\s*name:\s*(.+)$/m.exec(text)?.[1]?.trim() ?? path.basename(file, '.md');
|
|
141
|
+
const trigger = /^\s*trigger:\s*\[(.*?)\]/m.exec(text)?.[1]?.trim() ?? '';
|
|
142
|
+
const steps = [...text.matchAll(/^\s*\d+[.)]\s+(.+)$/gm)].map((match) => match[1].trim()).join(';');
|
|
143
|
+
return { name, trigger, steps, rel: path.basename(file) };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function listMarkdown(dir) {
|
|
147
|
+
try {
|
|
148
|
+
return fs.readdirSync(dir, { withFileTypes: true })
|
|
149
|
+
.filter((entry) => entry.isFile() && entry.name.toLowerCase().endsWith('.md') && !entry.name.startsWith('.'))
|
|
150
|
+
.map((entry) => path.join(dir, entry.name));
|
|
151
|
+
} catch {
|
|
152
|
+
return [];
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** ③ 冲突:与现有正式卡 + A1 staging 根级候选做名称/触发词/步骤相似度比较(只读)。 */
|
|
157
|
+
export function lintConflicts({ memoryRoot, sections }) {
|
|
158
|
+
const issues = [];
|
|
159
|
+
const stepsText = (Array.isArray(sections?.steps) ? sections.steps : []).join(';');
|
|
160
|
+
const probe = {
|
|
161
|
+
name: String(sections?.when ?? ''),
|
|
162
|
+
trigger: String(sections?.when ?? ''),
|
|
163
|
+
steps: stepsText,
|
|
164
|
+
};
|
|
165
|
+
const dirs = [
|
|
166
|
+
path.join(memoryRoot, 'procedures'),
|
|
167
|
+
path.join(memoryRoot, '.longlive', 'staging', 'auto-cards'),
|
|
168
|
+
];
|
|
169
|
+
for (const dir of dirs) {
|
|
170
|
+
for (const file of listMarkdown(dir)) {
|
|
171
|
+
const card = readCardSummary(file);
|
|
172
|
+
if (!card) continue;
|
|
173
|
+
const nameScore = diceSimilarity(probe.name, card.name);
|
|
174
|
+
const triggerScore = diceSimilarity(probe.trigger, card.trigger);
|
|
175
|
+
const stepScore = diceSimilarity(probe.steps, card.steps);
|
|
176
|
+
if (nameScore >= 0.6 || stepScore >= 0.75 || (triggerScore >= 0.8 && triggerScore > 0 && stepScore >= 0.3)) {
|
|
177
|
+
issues.push({
|
|
178
|
+
code: 'CONFLICT_EXISTING',
|
|
179
|
+
step: 0,
|
|
180
|
+
reason: `与既有卡 ${card.rel} 相似(name=${nameScore.toFixed(2)}, steps=${stepScore.toFixed(2)})`,
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return issues;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** ④ 触发词为空或过窄。 */
|
|
189
|
+
export function lintTrigger(trigger) {
|
|
190
|
+
const list = Array.isArray(trigger) ? trigger.filter((item) => String(item ?? '').trim() !== '') : [];
|
|
191
|
+
if (list.length === 0) {
|
|
192
|
+
return [{ code: 'TRIGGER_TOO_NARROW', step: 0, reason: '触发词为空' }];
|
|
193
|
+
}
|
|
194
|
+
const total = list.reduce((sum, item) => sum + Array.from(String(item)).length, 0);
|
|
195
|
+
if (list.length < 2 || total < 4) {
|
|
196
|
+
return [{ code: 'TRIGGER_TOO_NARROW', step: 0, reason: `触发词过窄(${list.length} 个 / ${total} 字)` }];
|
|
197
|
+
}
|
|
198
|
+
return [];
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** ⑤ 路径/用户名未归一化。 */
|
|
202
|
+
export function lintPaths(sections) {
|
|
203
|
+
const body = composeSectionsText(sections);
|
|
204
|
+
if (containsUnnormalizedPath(body) || /\bUsers[\\/][^\\/\s]+/.test(body)) {
|
|
205
|
+
return [{ code: 'PATH_NOT_NORMALIZED', step: 0, reason: '正文仍含裸盘符绝对路径或用户名路径' }];
|
|
206
|
+
}
|
|
207
|
+
return [];
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Run all five local rules. Pure except the read-only conflict scan.
|
|
212
|
+
*
|
|
213
|
+
* @param {{memoryRoot:string, candidate:{sections,trigger}, evidence:Array,
|
|
214
|
+
* evidenceResults:Array, at?:string}} input
|
|
215
|
+
*/
|
|
216
|
+
export function runLocalLint({ memoryRoot, candidate, evidence = null, evidenceResults = null, at = null }) {
|
|
217
|
+
const sections = candidate?.sections ?? {};
|
|
218
|
+
const evidenceList = evidence ?? candidate?.evidence ?? [];
|
|
219
|
+
const issues = [
|
|
220
|
+
...lintDangerousActions(sections),
|
|
221
|
+
...lintEvidence(evidenceList, evidenceResults),
|
|
222
|
+
...lintConflicts({ memoryRoot, sections }),
|
|
223
|
+
...lintTrigger(candidate?.trigger),
|
|
224
|
+
...lintPaths(sections),
|
|
225
|
+
];
|
|
226
|
+
return {
|
|
227
|
+
at: at ?? new Date().toISOString(),
|
|
228
|
+
verdict: issues.length === 0 ? 'pass' : 'issues',
|
|
229
|
+
issues,
|
|
230
|
+
rules: [...LINT_RULES],
|
|
231
|
+
};
|
|
232
|
+
}
|