@thincoder/core 0.11.1 → 0.11.2
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 +46 -2
- package/advisor/convergence.mjs +34 -3
- package/advisor/loop.mjs +42 -10
- package/advisor/messages.mjs +42 -25
- package/advisor/project-context.mjs +171 -42
- package/advisor/run.mjs +7 -4
- package/advisor.mjs +29 -43
- package/agent/batch-attribution.mjs +87 -0
- package/agent/batch-changed-surface.mjs +129 -0
- package/agent/completion.mjs +44 -3
- package/agent/dispatch-gates.mjs +6 -0
- package/agent/dispatch.mjs +8 -3
- package/agent/family-tools.mjs +27 -12
- package/agent/helpers.mjs +122 -1
- package/agent/offload.mjs +25 -29
- package/agent/post-turn.mjs +24 -10
- package/agent/record-results.mjs +18 -1
- package/agent/run-stages.mjs +77 -32
- package/agent/run-start.mjs +37 -0
- package/agent/setup-reminders.mjs +9 -2
- package/agent/setup.mjs +24 -11
- package/agent/spawn-child.mjs +38 -1
- package/agent/timers.mjs +5 -3
- package/agent/turn-loop.mjs +30 -5
- package/agent/turn-projection.mjs +386 -0
- package/agent/turn-task-state.mjs +274 -0
- package/agent/turn-tool-process.mjs +168 -0
- package/agent/write-gate-ledger.mjs +569 -0
- package/agent/write-gate.mjs +29 -352
- package/agent-tools/advisor-async.mjs +29 -169
- package/agent-tools/advisor-launch.mjs +178 -0
- package/agent-tools/advisor-settle.mjs +28 -1
- package/agent-tools/advisor.mjs +36 -47
- package/agent-tools/audit-block.mjs +6 -6
- package/agent-tools/batch-closeout.mjs +273 -35
- package/agent-tools/batch-gate.mjs +142 -342
- package/agent-tools/batch-ledger-bind.mjs +226 -17
- package/agent-tools/batch-ledger-view.mjs +109 -0
- package/agent-tools/batch-lifecycle.mjs +169 -46
- package/agent-tools/batch-paths.mjs +29 -8
- package/agent-tools/batch-record-write.mjs +417 -0
- package/agent-tools/batch-regions.mjs +215 -0
- package/agent-tools/batch-reopen.mjs +23 -11
- package/agent-tools/batch-segment-vocab.mjs +379 -0
- package/agent-tools/batch-skeleton.mjs +192 -239
- package/agent-tools/batch-supersede.mjs +232 -0
- package/agent-tools/batch-tier-gate.mjs +297 -0
- package/agent-tools/batch.mjs +182 -439
- package/agent-tools/consult.mjs +7 -4
- package/agent-tools/context.mjs +44 -17
- package/agent-tools/design-review-record.mjs +225 -0
- package/agent-tools/design-slots.mjs +1 -1
- package/agent-tools/design-token.mjs +279 -81
- package/agent-tools/doc-check.mjs +43 -33
- package/agent-tools/doc-graph.mjs +140 -0
- package/agent-tools/eng.mjs +9 -8
- package/agent-tools/escalate-async.mjs +2 -2
- package/agent-tools/manifest.mjs +34 -18
- package/agent-tools/read-history.mjs +112 -11
- package/agent-tools/review-facts.mjs +10 -3
- package/agent-tools/settings.mjs +23 -2
- package/agent-tools/spawn-gates.mjs +9 -8
- package/agent-tools/ssh-session.mjs +2 -2
- package/agent-tools/ssh-text.mjs +155 -0
- package/agent-tools/ssh-transport.mjs +19 -148
- package/agent-tools/subagent-actions-query.mjs +10 -6
- package/agent-tools/subagent-async.mjs +8 -9
- package/agent-tools/subagent-brief.mjs +76 -0
- package/agent-tools/subagent-design-token.mjs +168 -0
- package/agent-tools/subagent-run.mjs +1 -1
- package/agent-tools/subagent-scheduler.mjs +4 -4
- package/agent-tools/subagent-spawn.mjs +90 -110
- package/agent-tools/subagent.mjs +11 -10
- package/agent-tools/taskbook-block.mjs +94 -0
- package/agent-tools/timer.mjs +12 -8
- package/agent-tools/verify.mjs +13 -4
- package/agent-tools.mjs +7 -3
- package/agent.mjs +20 -1
- package/attachments.mjs +3 -3
- package/browser/actions.mjs +9 -3
- package/browser/cdp.mjs +45 -17
- package/browser/launch.mjs +25 -43
- package/browser/pool.mjs +299 -0
- package/browser/queue.mjs +2 -0
- package/browser/session-state.mjs +450 -0
- package/browser/session.mjs +127 -151
- package/browser/snapshot.mjs +89 -0
- package/client-identity.mjs +1 -1
- package/config-defaults.mjs +2 -1
- package/config-migrate.mjs +40 -0
- package/config-normalize.mjs +28 -2
- package/config-reload.mjs +59 -0
- package/config.mjs +62 -98
- package/context-degrade.mjs +38 -10
- package/context-echo.mjs +11 -0
- package/context.mjs +149 -83
- package/conventions.mjs +11 -9
- package/declaration.mjs +31 -5
- package/declared-repos.mjs +94 -0
- package/doc-check/doc-names.mjs +73 -0
- package/doc-check/doc-tokens.mjs +110 -0
- package/doc-check/existence.mjs +160 -0
- package/doc-check/index.mjs +309 -213
- package/doc-check/line-refs.mjs +27 -101
- package/doc-check/paragraph.mjs +218 -102
- package/doc-graph/anchors.mjs +474 -0
- package/doc-graph/doc-batch-face.mjs +59 -0
- package/doc-graph/doc-suffix.mjs +27 -0
- package/doc-graph/graph-tokens.mjs +160 -0
- package/doc-graph.mjs +778 -0
- package/explore-distill.mjs +11 -5
- package/i18n.mjs +1 -1
- package/instance-inbox-watch.mjs +272 -0
- package/instance-inbox.mjs +218 -0
- package/instance-registry.mjs +179 -0
- package/knowledge/README.md +3 -0
- package/knowledge/prompt-resources.md +6 -0
- package/ledger-close-proof.mjs +100 -49
- package/ledger-close.mjs +188 -0
- package/ledger-cmd.mjs +47 -91
- package/ledger-consistency.mjs +113 -0
- package/ledger-db.mjs +47 -15
- package/ledger-executors.mjs +1 -1
- package/ledger-tools.mjs +78 -19
- package/ledger-write-ops.mjs +130 -41
- package/ledger.mjs +1 -1
- package/manifest-discovery.mjs +3 -1
- package/manifest-schema.mjs +27 -5
- package/memory/schema.mjs +2 -2
- package/package.json +3 -1
- package/path-resolve.mjs +338 -57
- package/prompt-files.mjs +91 -1
- package/prompt-overlays.mjs +9 -6
- package/prompts/advisor-design.md +62 -21
- package/prompts/advisor-round1.md +34 -1
- package/prompts/advisor-round2.md +40 -7
- package/prompts/advisor-round3.md +39 -6
- package/prompts/common.md +14 -387
- package/prompts/consult-base.md +5 -1
- package/prompts/discipline-engineering.md +226 -51
- package/prompts/discipline-normal.md +4 -255
- package/prompts/knowledge/business-gates.md +22 -0
- package/prompts/knowledge/decision-quality.md +23 -0
- package/prompts/knowledge/doc-lookup.md +35 -0
- package/prompts/knowledge/document-writing.md +51 -0
- package/prompts/knowledge/documentation-evaluation.md +56 -0
- package/prompts/knowledge/evidence-discipline.md +57 -0
- package/prompts/knowledge/normal-coding-workflow.md +104 -0
- package/prompts/knowledge/normal-delivery-collaboration.md +108 -0
- package/prompts/knowledge/normal-work-management.md +57 -0
- package/prompts/knowledge/product-security.md +23 -0
- package/prompts/knowledge/project-records.md +62 -0
- package/prompts/knowledge/tool-advisor.md +29 -0
- package/prompts/knowledge/tool-apply-patch.md +18 -0
- package/prompts/knowledge/tool-bash.md +39 -0
- package/prompts/knowledge/tool-batch-eng-coder.md +12 -0
- package/prompts/knowledge/tool-batch-eng-designer.md +12 -0
- package/prompts/knowledge/tool-batch-review.md +12 -0
- package/prompts/knowledge/tool-batch.md +80 -0
- package/prompts/knowledge/tool-browser.md +57 -0
- package/prompts/knowledge/tool-code-search.md +4 -0
- package/prompts/knowledge/tool-consult-start.md +12 -0
- package/prompts/knowledge/tool-consult-stop.md +6 -0
- package/prompts/knowledge/tool-context.md +6 -0
- package/prompts/knowledge/tool-delete.md +17 -0
- package/prompts/knowledge/tool-doc-check.md +70 -0
- package/prompts/knowledge/tool-doc-graph-read.md +20 -0
- package/prompts/knowledge/tool-doc-graph.md +49 -0
- package/prompts/knowledge/tool-doc-search.md +6 -0
- package/prompts/knowledge/tool-edit.md +38 -0
- package/prompts/knowledge/tool-eng.md +2 -0
- package/prompts/knowledge/tool-execute.md +16 -0
- package/prompts/knowledge/tool-fetch.md +12 -0
- package/prompts/knowledge/tool-file-ops.md +16 -0
- package/prompts/knowledge/tool-get-current-time.md +7 -0
- package/prompts/knowledge/tool-git-read.md +19 -0
- package/prompts/knowledge/tool-git.md +29 -0
- package/prompts/knowledge/tool-glob.md +15 -0
- package/prompts/knowledge/tool-goal.md +8 -0
- package/prompts/knowledge/tool-grep.md +18 -0
- package/prompts/knowledge/tool-hashline-edit.md +14 -0
- package/prompts/knowledge/tool-insert-after.md +15 -0
- package/prompts/knowledge/tool-instance-list.md +6 -0
- package/prompts/knowledge/tool-instance-send.md +10 -0
- package/prompts/knowledge/tool-knowledge.md +18 -0
- package/prompts/knowledge/tool-ledger-read.md +35 -0
- package/prompts/knowledge/tool-ledger.md +42 -0
- package/prompts/knowledge/tool-lint.md +16 -0
- package/prompts/knowledge/tool-ls.md +13 -0
- package/prompts/knowledge/tool-lsp.md +11 -0
- package/prompts/knowledge/tool-main-history.md +2 -0
- package/prompts/knowledge/tool-manifest-read.md +14 -0
- package/prompts/knowledge/tool-manifest.md +31 -0
- package/prompts/knowledge/tool-memory-read.md +20 -0
- package/prompts/knowledge/tool-memory.md +15 -0
- package/prompts/knowledge/tool-notify-parent.md +12 -0
- package/prompts/knowledge/tool-operations.md +114 -0
- package/prompts/knowledge/tool-peer-instances.md +2 -0
- package/prompts/knowledge/tool-plan.md +6 -0
- package/prompts/knowledge/tool-process-read.md +13 -0
- package/prompts/knowledge/tool-process.md +15 -0
- package/prompts/knowledge/tool-question.md +16 -0
- package/prompts/knowledge/tool-read-history-batch.md +22 -0
- package/prompts/knowledge/tool-read-history.md +36 -0
- package/prompts/knowledge/tool-read-image.md +11 -0
- package/prompts/knowledge/tool-read.md +21 -0
- package/prompts/knowledge/tool-recent-changes.md +6 -0
- package/prompts/knowledge/tool-repo-outline.md +4 -0
- package/prompts/knowledge/tool-settings-read.md +12 -0
- package/prompts/knowledge/tool-settings.md +18 -0
- package/prompts/knowledge/tool-skill.md +6 -0
- package/prompts/knowledge/tool-ssh.md +52 -0
- package/prompts/knowledge/tool-subagent.md +59 -0
- package/prompts/knowledge/tool-task.md +12 -0
- package/prompts/knowledge/tool-team-ledger-read.md +11 -0
- package/prompts/knowledge/tool-team-ledger.md +11 -0
- package/prompts/knowledge/tool-timer.md +23 -0
- package/prompts/knowledge/tool-tree.md +14 -0
- package/prompts/knowledge/tool-verify.md +19 -0
- package/prompts/knowledge/tool-wait-for.md +25 -0
- package/prompts/knowledge/tool-websearch.md +19 -0
- package/prompts/knowledge/tool-write.md +9 -0
- package/prompts/knowledge/upstream-protocol.md +43 -0
- package/prompts/persona-eng-coder.md +21 -3
- package/prompts/persona-eng-designer.md +131 -169
- package/prompts/persona-engineering.md +142 -84
- package/prompts/persona-explore.md +1 -1
- package/prompts/persona-plan.md +5 -1
- package/prompts/subagent-base.md +2 -0
- package/provider/anthropic.mjs +6 -4
- package/provider/core.mjs +3 -2
- package/provider/errors.mjs +29 -4
- package/provider/google.mjs +24 -7
- package/provider/responses.mjs +3 -1
- package/provider-flows.mjs +2 -2
- package/session-index-build.mjs +1 -1
- package/session-index-pass.mjs +1 -1
- package/session-index-query.mjs +1 -1
- package/session-index.mjs +1 -1
- package/session-lifecycle.mjs +72 -17
- package/session-slot-write.mjs +37 -5
- package/session.mjs +24 -8
- package/skip-dirs.mjs +2 -2
- package/team-ledger.mjs +13 -9
- package/token-ttl.mjs +73 -4
- package/token-window.mjs +167 -33
- package/tool-docs/advisor.md +2 -27
- package/tool-docs/apply_patch.md +1 -15
- package/tool-docs/bash.md +2 -41
- package/tool-docs/batch-eng-coder.md +3 -0
- package/tool-docs/batch-eng-designer.md +3 -0
- package/tool-docs/batch-review.md +3 -0
- package/tool-docs/batch.md +2 -84
- package/tool-docs/browser.md +2 -49
- package/tool-docs/code_search.md +2 -2
- package/tool-docs/consult_start.md +2 -8
- package/tool-docs/consult_stop.md +2 -4
- package/tool-docs/context.md +1 -5
- package/tool-docs/delete.md +2 -17
- package/tool-docs/doc_check.md +2 -107
- package/tool-docs/doc_graph-read.md +3 -0
- package/tool-docs/doc_graph.md +3 -0
- package/tool-docs/doc_search.md +2 -4
- package/tool-docs/edit.md +1 -38
- package/tool-docs/eng.md +3 -1
- package/tool-docs/execute.md +2 -18
- package/tool-docs/fetch.md +2 -14
- package/tool-docs/file_ops.md +2 -18
- package/tool-docs/get_current_time.md +1 -6
- package/tool-docs/git-read.md +3 -0
- package/tool-docs/git.md +2 -35
- package/tool-docs/glob.md +2 -10
- package/tool-docs/goal.md +1 -6
- package/tool-docs/grep.md +2 -18
- package/tool-docs/hashline_edit.md +2 -15
- package/tool-docs/insert_after.md +2 -16
- package/tool-docs/instance_list.md +3 -0
- package/tool-docs/instance_send.md +3 -0
- package/tool-docs/knowledge.md +3 -0
- package/tool-docs/ledger-read.md +3 -0
- package/tool-docs/ledger.md +3 -8
- package/tool-docs/lint.md +2 -10
- package/tool-docs/ls.md +2 -11
- package/tool-docs/lsp.md +2 -9
- package/tool-docs/main_history.md +3 -1
- package/tool-docs/manifest-read.md +2 -8
- package/tool-docs/manifest.md +2 -35
- package/tool-docs/memory-read.md +3 -0
- package/tool-docs/memory.md +2 -20
- package/tool-docs/notify_parent.md +2 -13
- package/tool-docs/peer_instances.md +3 -1
- package/tool-docs/plan.md +1 -5
- package/tool-docs/process-read.md +3 -0
- package/tool-docs/process.md +2 -13
- package/tool-docs/question.md +3 -17
- package/tool-docs/read.md +2 -19
- package/tool-docs/read_history-batch.md +3 -0
- package/tool-docs/read_history.md +2 -18
- package/tool-docs/read_image.md +2 -9
- package/tool-docs/recent_changes.md +2 -2
- package/tool-docs/repo_outline.md +2 -2
- package/tool-docs/settings-read.md +3 -0
- package/tool-docs/settings.md +1 -12
- package/tool-docs/skill.md +2 -6
- package/tool-docs/ssh.md +1 -62
- package/tool-docs/subagent.md +2 -100
- package/tool-docs/task.md +1 -7
- package/tool-docs/team_ledger-read.md +3 -0
- package/tool-docs/team_ledger.md +3 -9
- package/tool-docs/timer.md +2 -19
- package/tool-docs/tree.md +2 -13
- package/tool-docs/verify.md +2 -12
- package/tool-docs/wait_for.md +2 -32
- package/tool-docs/websearch.md +2 -19
- package/tool-docs/write.md +2 -12
- package/tools/browser.mjs +52 -7
- package/tools/doc-write-gate.mjs +73 -0
- package/tools/edit-batch.mjs +170 -92
- package/tools/edit-diff.mjs +78 -62
- package/tools/edit-receipt.mjs +39 -0
- package/tools/execute.mjs +1 -1
- package/tools/file.mjs +16 -8
- package/tools/git.mjs +24 -9
- package/tools/index.mjs +6 -0
- package/tools/knowledge.mjs +143 -0
- package/tools/linter.mjs +3 -3
- package/tools/ops.mjs +3 -1
- package/tools/patch.mjs +123 -43
- package/tools/shared.mjs +28 -27
- package/tools/write-gate-params.mjs +31 -0
- package/tools/write-path.mjs +16 -4
- package/window-policy.mjs +203 -0
- package/doc-check/anchors.mjs +0 -235
package/context.mjs
CHANGED
|
@@ -13,9 +13,14 @@
|
|
|
13
13
|
|
|
14
14
|
import { chat } from "./provider/index.mjs"
|
|
15
15
|
import { buildCompressMessages } from "./compress-form.mjs"
|
|
16
|
-
import { contextUsage, estimateTokens, keepTailSize, splitHistory,
|
|
17
|
-
import { COMPACTION_PLACEHOLDER, withPlaceholderPrefix } from "./context-echo.mjs"
|
|
18
|
-
import { shrinkOversized } from "./context-degrade.mjs"
|
|
16
|
+
import { contextUsage, estimateTokens, keepTailSize, splitHistory, NOTE_ESTIMATE, rebaseMeasured, tailBudgetTokens, tokenRatioOf } from "./token-window.mjs"
|
|
17
|
+
import { COMPACTION_PREFIX, COMPACTION_PLACEHOLDER, withPlaceholderPrefix } from "./context-echo.mjs"
|
|
18
|
+
import { pruneStaleToolOutputs, shrinkOversized } from "./context-degrade.mjs"
|
|
19
|
+
// 固定开销越线判据的另一半(#2398):`limit` 单源 = `policyBudget`(有效窗口——与守卫面同一个数)。
|
|
20
|
+
import { policyBudget, resolveWorkMode } from "./config.mjs"
|
|
21
|
+
// 覆盖条数(#2399):按折叠身份账算——轮投影与压缩共用同一张账,不在本档另立一份判据。
|
|
22
|
+
// 保留窗起点(#2431):`splitHistory` 的必填第四参——切点一处收紧,压缩与 prune 同源受益(§1.2)。
|
|
23
|
+
import { coveredTurnCount, retentionWindowStart } from "./agent/turn-projection.mjs"
|
|
19
24
|
|
|
20
25
|
export const SUMMARIZE_PROMPT = `The conversation above is our work log so far — summarize it into a compact summary for use as context in the ongoing conversation.
|
|
21
26
|
Requirements:
|
|
@@ -30,33 +35,18 @@ Requirements:
|
|
|
30
35
|
- Use bullet-point output. Stay under ~1K tokens (≈1000 Chinese chars / 4000 ASCII chars) — a hard target. An oversized summary wastes window and dilutes the tail; the old unbounded-length guidance is deprecated. When over budget, trim in this order: completed recaps to one line; FILES CHANGED why-notes to bare paths; in-progress prose tightened. NEVER cut design anchors or UNRESOLVED ISSUES/TODOs — recovery depends on them.
|
|
31
36
|
`
|
|
32
37
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* 注记 + 占位的估算(§6.17 可达性门的 `note` 项):摘要正文取 `SUMMARY_TOKEN_ESTIMATE`(§6.9 的 ~1K 目标,常量单源 =
|
|
41
|
-
* `token-window.mjs`),注记前缀与占位句按 §6.3 估算式(`estimateTokens` 走同一 `estimateText`)——零新常数、零新算式。
|
|
42
|
-
* 残余方向:真实摘要超 1K 时本值低估 `post`(门可能放行一次压不到线下的压缩),不会反向误拦——守卫面仍抛三实数。
|
|
43
|
-
* 另:`applyCompression` 压完还会追加任务表回注与 plan 提醒(`agent.tasks` / `planMode` 非空时),本值同样不含——
|
|
44
|
-
* 同向低估(大任务表会话里 `post` 偏小),不会把本该压的格拦下。
|
|
45
|
-
*/
|
|
46
|
-
const NOTE_ESTIMATE = SUMMARY_TOKEN_ESTIMATE + estimateTokens([
|
|
47
|
-
{ role: "user", content: COMPACTION_PREFIX },
|
|
48
|
-
{ role: "assistant", content: COMPACTION_PLACEHOLDER },
|
|
49
|
-
])
|
|
50
|
-
|
|
51
|
-
/** After this many consecutive compaction summary failures, degrade to deterministic truncation (losing info is better than task-killing 400 errors) */
|
|
52
|
-
export const COMPRESS_FAILURE_LIMIT = 3
|
|
38
|
+
// 注记 + 占位的估算(§6.17 可达性门的 `note` 项 ∥ §4 减法链的末项)住 `token-window.mjs` 的 `NOTE_ESTIMATE`——
|
|
39
|
+
// 尾预算也要用它,而本档 import 那一档(反向就会成环)。两条固定文本的单源 = `context-echo.mjs`。
|
|
40
|
+
// 残余方向:真实摘要超 1K 时本值低估 `post`(门可能放行一次压不到线下的压缩),不会反向误拦——守卫面仍抛三实数。
|
|
41
|
+
// 另:`applyCompression` 压完还会追加任务表回注与 plan 提醒(`agent.tasks` / `planMode` 非空时),本值同样不含——
|
|
42
|
+
// 同向低估(大任务表会话里 `post` 偏小),不会把本该压的格拦下。
|
|
53
43
|
|
|
54
44
|
/** Task re-injection reminder prefix (after compaction, clear old versions from history first for a single source of truth) */
|
|
55
45
|
const TASK_REINJECT_PREFIX = "[System reminder: your current task list after compaction:"
|
|
56
46
|
|
|
57
|
-
/** Truncation fallback note (
|
|
47
|
+
/** Truncation fallback note (deterministic discard, no LLM call — §5.1 第 ⑥ 步) */
|
|
58
48
|
const FALLBACK_NOTE =
|
|
59
|
-
"[Context was truncated
|
|
49
|
+
"[Context was truncated because summarization failed. " +
|
|
60
50
|
"The middle portion of earlier work was dropped WITHOUT a summary. " +
|
|
61
51
|
"Re-verify any state you need with tools before relying on it.]\n\n"
|
|
62
52
|
|
|
@@ -84,6 +74,11 @@ function anchorText(agent) {
|
|
|
84
74
|
|
|
85
75
|
/** Replace middle with a note, then re-inject task/plan state (shared by LLM summary and truncation fallback) */
|
|
86
76
|
function applyCompression(agent, headEnd, tailStart, note) {
|
|
77
|
+
// 在途段起点(#2397):压缩重建整个机读数组,旧下标落在更短的数组上就是另一条消息——
|
|
78
|
+
// 先记下它指向的那条消息对象,重建后按身份找回下标(CONTEXT-COMPACTION.md §1.1)。
|
|
79
|
+
const inFlightAnchor = Number.isInteger(agent._turnStartLen) ? agent.history[agent._turnStartLen] : null
|
|
80
|
+
// 覆盖条数(#2399):按折叠身份账算——该轮记录消息全部落在切割点之前才算覆盖(一轮被切开不记)。
|
|
81
|
+
const turnsCovered = coveredTurnCount(agent, tailStart)
|
|
87
82
|
// _fullHistory already holds every real message (written at the source via pushReal),
|
|
88
83
|
// so compaction only shrinks the machine line — nothing to preserve here.
|
|
89
84
|
// head is normally empty (KEEP_HEAD = 0) — the summary note becomes the first message,
|
|
@@ -91,6 +86,11 @@ function applyCompression(agent, headEnd, tailStart, note) {
|
|
|
91
86
|
// possibly-completed earlier requests.
|
|
92
87
|
const head = agent.history.slice(0, headEnd)
|
|
93
88
|
const tail = agent.history.slice(tailStart)
|
|
89
|
+
// 结构编辑后的实测基线(§3.1):压缩是「替换非删除」——被改的那一段 = 中段,替换后的那一段 = 注记(+ 占位)。
|
|
90
|
+
// 编辑前的数组与它被量到的长度先记下:`_usageAtLen` 要按身份重算,不能沿用旧下标。
|
|
91
|
+
const before = agent.history
|
|
92
|
+
const measuredEnd = Number.isInteger(agent._usageAtLen) ? agent._usageAtLen : before.length
|
|
93
|
+
const estBefore = estimateTokens(before.slice(headEnd, tailStart))
|
|
94
94
|
// SESSION.md §6.9: compaction-injected messages carry a ts — Date.now() at the compaction
|
|
95
95
|
// moment (the note below; and the separate "Understood" placeholder in the non-merge branch).
|
|
96
96
|
// They are machine-only (never in _fullHistory), but the machine-line timeline stays consistent
|
|
@@ -134,9 +134,14 @@ function applyCompression(agent, headEnd, tailStart, note) {
|
|
|
134
134
|
]
|
|
135
135
|
agent._runStartHistoryLen = head.length + 2
|
|
136
136
|
}
|
|
137
|
-
//
|
|
138
|
-
|
|
139
|
-
|
|
137
|
+
// 实测基线按 §3.1 **重定,不归零**:压缩之后恰恰是最需要准确读数的时刻,而真值要等一整次往返。
|
|
138
|
+
// `estAfter` = 替换中段的那一段(注记 + 占位,归并支里占位并进了 `tail[0]`,不进这一段);重定本身
|
|
139
|
+
// 放在函数尾——上面的摘旧行与回注都会挪下标,身份扫描必须在数组定形之后。
|
|
140
|
+
const estAfter = estimateTokens(
|
|
141
|
+
tail[0]?.role === "assistant"
|
|
142
|
+
? [{ role: "user", content: note }]
|
|
143
|
+
: [{ role: "user", content: note }, { role: "assistant", content: COMPACTION_PLACEHOLDER }],
|
|
144
|
+
)
|
|
140
145
|
|
|
141
146
|
// After compaction, re-inject the task list (the agent needs to know what it was doing).
|
|
142
147
|
// Single source of truth: first remove any stale re-injections from the tail, then inject the latest version —
|
|
@@ -159,6 +164,19 @@ function applyCompression(agent, headEnd, tailStart, note) {
|
|
|
159
164
|
content: "[System reminder: plan mode is active. Explore the codebase read-only, design your solution, then call plan with action='exit' to present it for user approval.]",
|
|
160
165
|
})
|
|
161
166
|
}
|
|
167
|
+
|
|
168
|
+
// 在途段起点按消息身份重定(CONTEXT-COMPACTION.md §1.1):找不回(那条已进摘要)⇒ 取注记与占位之后的第一条
|
|
169
|
+
// 原文(= 本轮 `_runStartHistoryLen` 的口径)。终点 `_turnResponseEnd` 在轮循环返回处才采集,压缩先于它发生,不受影响。
|
|
170
|
+
// 放在函数尾:上面的摘旧行与回注都会挪下标,重定必须在数组定形之后。
|
|
171
|
+
if (Number.isInteger(agent._turnStartLen)) {
|
|
172
|
+
const at = inFlightAnchor ? agent.history.indexOf(inFlightAnchor) : -1
|
|
173
|
+
agent._turnStartLen = at >= 0 ? at : agent._runStartHistoryLen
|
|
174
|
+
}
|
|
175
|
+
// 压缩成果落内存载体(#2399):槽保存取它、恢复播种取它(SESSION.md §2 ∥ CONTEXT-COMPACTION.md §6)。
|
|
176
|
+
agent._compactCheckpoint = { note, turnsCovered }
|
|
177
|
+
// §3.1 基线重定(数组已定形):中段换成注记,`measuredEnd` 之后的消息从没被量过,故只按身份找
|
|
178
|
+
// 「旧前缀最后一个还在线上的消息」,其后第一个下标就是新的 `_usageAtLen`。
|
|
179
|
+
rebaseMeasured(agent, estBefore, estAfter, { before, measuredEnd })
|
|
162
180
|
}
|
|
163
181
|
|
|
164
182
|
/**
|
|
@@ -175,39 +193,65 @@ function postCompactionTotal(agent, usage, middle) {
|
|
|
175
193
|
}
|
|
176
194
|
|
|
177
195
|
/**
|
|
178
|
-
*
|
|
179
|
-
*
|
|
180
|
-
*
|
|
181
|
-
*
|
|
182
|
-
*
|
|
196
|
+
* 压缩链(`CONTEXT-COMPACTION.md` §5.1):越线不等于要付一次摘要请求——越线之后先做一次零成本、
|
|
197
|
+
* 确定性的 prune,再重测。裁 → 摘要 → 丢弃,三步串联,每步之后重测,够则停:
|
|
198
|
+
*
|
|
199
|
+
* ```text
|
|
200
|
+
* ① 阈值早退(total ≤ threshold,force 跳过)
|
|
201
|
+
* ② 固定开销越线门(force 跳不过)
|
|
202
|
+
* ③ prune 一次 → 重定基线(§3.1)→ 重测 contextUsage
|
|
203
|
+
* ④ 未 force 且重测后 total ≤ threshold ⇒ 停(零摘要请求)
|
|
204
|
+
* ⑤ splitHistory(尾预算 = §4 的减法链)→ 可达性门 → 摘要请求 → 重测
|
|
205
|
+
* ⑥ 摘要失败,或压后 total 仍 > threshold ⇒ compressFallback(丢弃,零网络)→ 重测
|
|
206
|
+
* ⑦ 压后 total 仍 > limit ⇒ 守卫抛三实数(`enforceContextFit`,本链之外的同一个原子)
|
|
207
|
+
* ```
|
|
208
|
+
*
|
|
209
|
+
* `force` 面也 prune,但不因 prune 就早退,也不因 ④ 就停:`/compact` 与越窗自愈要的是一次真实的压缩动作,
|
|
210
|
+
* prune 只让中段变小、摘要请求更省。第 ③ 步的射程:合格集非空的只有 §7.2 列的那两类状态(尚无一条轮记录带
|
|
211
|
+
* `toolProcess` ∥ 由 `history` 播种的旧槽);其余状态下 `tool` 消息全在保留窗内、因而全在保护尾里,prune 返回
|
|
212
|
+
* 0 条——③ 是一步 no-op,常见路径的成本落在 ⑤。
|
|
213
|
+
*
|
|
214
|
+
* 返回是否发生了压缩(摘要成功 ∥ 弃真的发生)。摘要失败一次就走到丢弃,不等连续失败——「一次网络抖动换一个
|
|
215
|
+
* 死会话」正是这条链要避开的结局;只有在丢弃也无中段可丢时才把那个错抛出去(调用点照既有失败链记一行回执)。
|
|
216
|
+
* 摘要请求是 SILENT 的(从不转 onToken/onReasoning——压缩是内部机制,不是模型回复);`onCompressStart` 在
|
|
217
|
+
* 摘要请求发出前触发(§6.8 D-C1 生命周期可见)。只在安全点调用(history 以完整交换结尾)。
|
|
183
218
|
* @param {object} agent
|
|
184
219
|
* @param {number} threshold - compaction threshold in tokens
|
|
185
|
-
* @param {object} callbacks - {
|
|
186
|
-
* generation is SILENT (never forwards onToken/onReasoning: the compaction process is an
|
|
187
|
-
* internal mechanism, not a model reply); onCompressStart fires right before the summary call
|
|
188
|
-
* (§6.8 D-C1, compression lifecycle visibility — panel start state)
|
|
220
|
+
* @param {object} callbacks - { onCompress, onCompressStart, onCompressFail }
|
|
189
221
|
* @param {object} extras - { systemPrompt?, tools?, force?, focus? } — 固定开销面(system + tools 估计)+
|
|
190
|
-
* 模型主动压缩面(§6.16.2):`force` **跳过阈值面的全部早退判据**(`total <= threshold
|
|
191
|
-
* `post > threshold
|
|
222
|
+
* 模型主动压缩面(§6.16.2):`force` **跳过阈值面的全部早退判据**(`total <= threshold`、第 ④ 步与 §6.17
|
|
223
|
+
* 可达性门的 `post > threshold`),其余全同(同切分 / 同尾部预算 / 同摘要链 / 同回注 / 同基线重定);
|
|
224
|
+
* `focus` 追加在摘要指令尾段。
|
|
192
225
|
*/
|
|
193
226
|
export async function compressIfNeeded(agent, threshold, callbacks, extras = {}, signal) {
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
const
|
|
227
|
+
// 档位 = 本 run 的策略输入(§2.3 握有 agent 的面自取):守卫、尾预算、固定开销判据全从它派生有效窗口。
|
|
228
|
+
const workMode = resolveWorkMode(agent.config?.agent)
|
|
229
|
+
const ratio = tokenRatioOf(agent)
|
|
230
|
+
// 单源(§6.16.4):total 与 stats 面同一函数(既有内联式改调 contextUsage,判定语义零改)。
|
|
231
|
+
// ① 阈值早退(force 跳过)
|
|
232
|
+
let usage = contextUsage(agent, extras)
|
|
233
|
+
if (!extras.force && usage.total <= threshold) return false
|
|
234
|
+
// ② 固定开销单独越线(#2398 · §5):history 归零后 `total` 仍等于固定开销 ⇒ 压缩无解。强压面也不放行
|
|
235
|
+
// (压一次白付一次摘要请求,压完仍抛同一个错);判据窗口 = 有效窗口(§2.2)。
|
|
236
|
+
if (usage.fixedFloor > policyBudget(agent.provider, undefined, workMode).limit) return false
|
|
237
|
+
// ③ prune 一次 → 基线按 §3.1 重定(在 prune 内部)→ 重测
|
|
238
|
+
if (pruneStaleToolOutputs(agent).pruned > 0) usage = contextUsage(agent, extras)
|
|
239
|
+
// ④ 未 force 且重测后已够 ⇒ 停:prune 换来的线下,不必再付一次摘要请求
|
|
240
|
+
if (!extras.force && usage.total <= threshold) return false
|
|
197
241
|
const tokens = usage.total
|
|
198
|
-
if (!extras.force && tokens <= threshold) return false
|
|
199
242
|
|
|
200
|
-
const keepTail = keepTailSize(agent.provider, history.length)
|
|
201
|
-
const split = splitHistory(history, keepTail, tailBudgetTokens(agent.provider))
|
|
243
|
+
const keepTail = keepTailSize(agent.provider, agent.history.length, workMode)
|
|
244
|
+
const split = splitHistory(agent.history, keepTail, tailBudgetTokens(agent.provider, workMode, usage.overhead, ratio), retentionWindowStart(agent))
|
|
202
245
|
if (!split) {
|
|
203
246
|
// History is too short (≤KEEP_HEAD+keepTail+1 messages) to find a middle section, but tokens exceed threshold — typically a single giant message
|
|
204
247
|
// (large paste / huge injection). When summarization has no room, degrade to deterministic shrinking to ensure context always reduces
|
|
205
248
|
return shrinkOversized(agent)
|
|
206
249
|
}
|
|
207
250
|
|
|
208
|
-
const middle = history.slice(split.headEnd, split.tailStart)
|
|
251
|
+
const middle = agent.history.slice(split.headEnd, split.tailStart)
|
|
209
252
|
// 可达性门(§6.17):压完落不到线下 ⇒ 不压——不为一次没有净减的摘要白付请求。`force` 全文豁免(模型主动压缩 ∥
|
|
210
253
|
// 守卫强压:模型判定优先于阈值,压后仍超由守卫面抛三实数)。到不了线下的格仍由守卫 `enforceContextFit` 兜住。
|
|
254
|
+
// 判据的输入是 prune 之后的 `usage` 与 prune 之后的 `middle`(同一次 `splitHistory` 产出),判据本身零改。
|
|
211
255
|
if (!extras.force && postCompactionTotal(agent, usage, middle) > threshold) return false
|
|
212
256
|
|
|
213
257
|
// Compression request form v2/v3 (§6.14 / D-CC20): continuation — same system + same tools declaration (the turn's own
|
|
@@ -225,57 +269,79 @@ export async function compressIfNeeded(agent, threshold, callbacks, extras = {},
|
|
|
225
269
|
const startedAt = performance.now()
|
|
226
270
|
// F-CC2 焦点块(§6.16.2):仅模型主动面携带——追加在**指令末条尾段**(`SUMMARIZE_PROMPT` 文本零改,
|
|
227
271
|
// 只追加焦点块;无 focus ⇒ 请求体逐字节同修前——compress-form.test.mjs 零回归)。
|
|
228
|
-
const messages = buildCompressMessages(history, split.tailStart, extras?.systemPrompt, SUMMARIZE_PROMPT)
|
|
272
|
+
const messages = buildCompressMessages(agent.history, split.tailStart, extras?.systemPrompt, SUMMARIZE_PROMPT)
|
|
229
273
|
if (extras.focus) {
|
|
230
274
|
const last = messages.at(-1)
|
|
231
275
|
messages[messages.length - 1] = { ...last, content: last.content + focusBlock(String(extras.focus), anchorText(agent)) }
|
|
232
276
|
}
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
277
|
+
// ⑤ 摘要请求。失败不抛给上游(除用户中止):单次失败即发 `onCompressFail`,随后走 ⑥ 的丢弃。
|
|
278
|
+
let summarized = false
|
|
279
|
+
let summaryError = null
|
|
280
|
+
try {
|
|
281
|
+
const summary = await chat({ ...agent.provider, thinking: null }, {
|
|
282
|
+
messages,
|
|
283
|
+
tools: extras?.tools,
|
|
284
|
+
signal,
|
|
285
|
+
// TRACES.md §6.1 D-TR4:轨迹元数据增补——kind=compress(上下文构建面——agent 元数据透出;
|
|
286
|
+
// depth 经 extras.traceDepth——agent.mjs 主作用域传入——compress 调用点补齐)
|
|
287
|
+
logCtx: {
|
|
288
|
+
stage: "compress", child: agent._logId, kind: "compress",
|
|
289
|
+
role: agent._role ?? null, depth: extras?.traceDepth ?? null,
|
|
290
|
+
session: agent._sessionStart ?? null, cwd: agent.cwd,
|
|
291
|
+
traces: agent.config?.traces?.enabled !== false,
|
|
292
|
+
},
|
|
293
|
+
})
|
|
294
|
+
// Blank-summary guard (§6.14 退化面 3): a blank summary would land in applyCompression as
|
|
295
|
+
// "middle dropped + empty note" and still count as success — treat it as this call failing.
|
|
296
|
+
if (!summary.content?.trim()) throw new Error("compaction summary is empty")
|
|
297
|
+
applyCompression(agent, split.headEnd, split.tailStart, COMPACTION_PREFIX + summary.content)
|
|
298
|
+
// Completion info for the compression panel (D-C2): tokens freed = the pre-compression prompt
|
|
299
|
+
// estimate (`tokens` — the value that tripped the threshold, incl. system/tools overhead on the
|
|
300
|
+
// pure-estimation path) minus the post-compression estimate on the SAME basis (`contextUsage`
|
|
301
|
+
// — a bare `estimateTokens` sum would skip the §6.17 `_tokRatio` and overstate the freed tokens).
|
|
302
|
+
// Elapsed = the summary call + splice duration. agent.mjs forwards this to onCompress unchanged.
|
|
303
|
+
agent._lastCompressInfo = {
|
|
304
|
+
mode: "summary",
|
|
305
|
+
tokensFreed: Math.max(0, Math.round(tokens - contextUsage(agent, extras).total)),
|
|
306
|
+
elapsedMs: performance.now() - startedAt,
|
|
307
|
+
}
|
|
308
|
+
summarized = true
|
|
309
|
+
} catch (e) {
|
|
310
|
+
// 用户中止不是压缩失败:原样透传(调用点据此不记账、不降级)。
|
|
311
|
+
if (e?.name === "AbortError" || signal?.aborted) throw e
|
|
312
|
+
summaryError = e
|
|
313
|
+
callbacks?.onCompressFail?.(e)
|
|
262
314
|
}
|
|
263
|
-
|
|
315
|
+
// ⑥ 摘要失败,或压后仍在线上一档之上 ⇒ 丢弃(零网络、确定性),再重测。
|
|
316
|
+
const after = contextUsage(agent, extras)
|
|
317
|
+
if (!summarized || after.total > threshold) {
|
|
318
|
+
if (compressFallback(agent)) return true
|
|
319
|
+
// 没有中段可丢:无摘要产物,把摘要那个错交回调用点(既有失败链记一行回执)。
|
|
320
|
+
if (summaryError) throw summaryError
|
|
321
|
+
}
|
|
322
|
+
return summarized
|
|
264
323
|
}
|
|
265
324
|
|
|
266
325
|
/**
|
|
267
|
-
* Deterministic truncation fallback
|
|
326
|
+
* Deterministic truncation fallback(§5.1 第 ⑥ 步):dropped without a summary, no network call.
|
|
268
327
|
* Drops the middle so the task can continue. Returns whether truncation happened.
|
|
328
|
+
* 丢弃要报量(§5.1):`discardedMessages` = 被丢弃的消息条数;`discardedTurns` = 其中全部记录消息都落在
|
|
329
|
+
* 该区间的轮次数(与 §6 的覆盖账同一本);`tailMessages` = 留下的尾部条数——只报留下的条数,读的人推不出丢了什么。
|
|
269
330
|
*/
|
|
270
331
|
export function compressFallback(agent) {
|
|
271
|
-
const
|
|
272
|
-
const
|
|
332
|
+
const workMode = resolveWorkMode(agent.config?.agent)
|
|
333
|
+
const ratio = tokenRatioOf(agent)
|
|
334
|
+
const overhead = contextUsage(agent).overhead
|
|
335
|
+
const keepTail = keepTailSize(agent.provider, agent.history.length, workMode)
|
|
336
|
+
const split = splitHistory(agent.history, keepTail, tailBudgetTokens(agent.provider, workMode, overhead, ratio), retentionWindowStart(agent))
|
|
273
337
|
if (!split) return false
|
|
274
338
|
const tailMessages = agent.history.length - split.tailStart
|
|
339
|
+
const discardedMessages = split.tailStart - split.headEnd
|
|
340
|
+
const discardedTurns = coveredTurnCount(agent, split.tailStart)
|
|
275
341
|
applyCompression(agent, split.headEnd, split.tailStart, FALLBACK_NOTE)
|
|
276
|
-
// Fallback completion info (D-C2): mode marks the deterministic-
|
|
277
|
-
//
|
|
278
|
-
agent._lastCompressInfo = { mode: "fallback", tailMessages }
|
|
342
|
+
// Fallback completion info (D-C2): mode marks the deterministic-discard path — the panel shows the
|
|
343
|
+
// degradation note on the same callback, distinguished by `mode === "fallback"` alone.
|
|
344
|
+
agent._lastCompressInfo = { mode: "fallback", discardedMessages, discardedTurns, tailMessages }
|
|
279
345
|
return true
|
|
280
346
|
}
|
|
281
347
|
|
package/conventions.mjs
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* conventions.mjs — the single authority for code / doc / temp / aux path classification,
|
|
3
|
-
* plus the project declaration surface (the
|
|
4
|
-
* `PROJECT-MANIFEST.json`: `codePaths` / `index.*`
|
|
3
|
+
* plus the project declaration surface (the declaration families of the project's
|
|
4
|
+
* `PROJECT-MANIFEST.json`: `codePaths` / `index.*` — the `advisor` family is retired and
|
|
5
|
+
* dropped on write, so it is not part of this surface).
|
|
5
6
|
*
|
|
6
7
|
* Why one module: the write-domain gates and guards (design gate, review-doc gate,
|
|
7
8
|
* mutation accounting, verify fast path) each carried their own copy of the
|
|
@@ -23,12 +24,13 @@
|
|
|
23
24
|
* visible warning per load (existence check only — zero content parsing — KD-M1-34).
|
|
24
25
|
*
|
|
25
26
|
* Classification vocabulary (PORTABILITY design §3.2):
|
|
26
|
-
* code — inside a declared code segment (default:
|
|
27
|
-
* fallback; doc — documentation extension outside any
|
|
28
|
-
* scratch; temp — tmp-* name or .tmp/.temp extension;
|
|
29
|
-
* auxiliary-path segment sequence (test / tests / scripts /
|
|
30
|
-
* that matched no code segment and neither doc nor temp;
|
|
31
|
-
* file (`PROJECT-MANIFEST.json` basename ∥
|
|
27
|
+
* code — inside a declared code segment (none by default: a project declares
|
|
28
|
+
* `codePaths`), or the fallback; doc — documentation extension outside any
|
|
29
|
+
* code segment and not scratch; temp — tmp-* name or .tmp/.temp extension;
|
|
30
|
+
* aux — a default auxiliary-path segment sequence (test / tests / scripts /
|
|
31
|
+
* .thincoder/tmp — F9) that matched no code segment and neither doc nor temp;
|
|
32
|
+
* state — a project state file (`PROJECT-MANIFEST.json` basename ∥
|
|
33
|
+
* `.thincoder/conventions.json` pair — #941).
|
|
32
34
|
* Precedence: code segment → temp → doc → aux → state → fallback code.
|
|
33
35
|
*
|
|
34
36
|
* Segment matching runs on the PROJECT-ROOT-RELATIVE FACE of a path (D17 · 2026-09-28): the
|
|
@@ -189,4 +191,4 @@ export function isStatePath(p, conv) {
|
|
|
189
191
|
// 迁出面(2026-10-01 拆分批 · #755 ∥ #786):声明装载面外提 `declaration.mjs`——本档经
|
|
190
192
|
// 转口保名(消费面 / 单元测试档 import 面零改;`DEFAULT_DECLARATION` 另供本档分类裁判缺省取用)。
|
|
191
193
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
192
|
-
export { loadProjectDeclaration, declarationForTarget, DEFAULT_DECLARATION, isExcludedRelPath, declaredIndexScope, isInDeclaredScope, declaredPublicRoots, clearDeclarationCache } from "./declaration.mjs"
|
|
194
|
+
export { loadProjectDeclaration, declarationForTarget, DEFAULT_DECLARATION, isExcludedRelPath, declaredIndexScope, isInDeclaredScope, declaredPublicRoots, declaredWritableRoots, clearDeclarationCache } from "./declaration.mjs"
|
package/declaration.mjs
CHANGED
|
@@ -49,8 +49,10 @@ function normalizeCodePaths(v) {
|
|
|
49
49
|
return out
|
|
50
50
|
}
|
|
51
51
|
|
|
52
|
-
/** 路径列表归一(单源——`index.excludePaths` §6.14 ∥ `index.publicRepos` §6.15 同款):首部 `./` 剥离 · `\`→`/` · 去尾斜杠 · 空 ∕ 非串剔除 · 去重保序。
|
|
53
|
-
|
|
52
|
+
/** 路径列表归一(单源——`index.excludePaths` §6.14 ∥ `index.publicRepos` §6.15 同款):首部 `./` 剥离 · `\`→`/` · 去尾斜杠 · 空 ∕ 非串剔除 · 去重保序。
|
|
53
|
+
* **导出**:第三个消费面 = `doc_check` 的排除面(`index.docCheckExcludePaths`——机制见 `docs/core/design/DOC-CHECK.md` §10)。
|
|
54
|
+
* 两个键各写一份归一,语义必然漂;差别只该在「谁吃这个清单」,不应在「怎么认路径」。 */
|
|
55
|
+
export function normalizePathList(v) {
|
|
54
56
|
if (!Array.isArray(v)) return []
|
|
55
57
|
const out = []
|
|
56
58
|
for (const e of v) {
|
|
@@ -75,6 +77,7 @@ function buildDeclaration(m, root = null) {
|
|
|
75
77
|
const docExtensions = normalizeExtensions(m?.index?.docExtensions)
|
|
76
78
|
const excludePaths = normalizePathList(m?.index?.excludePaths)
|
|
77
79
|
const publicRepos = normalizePathList(m?.index?.publicRepos)
|
|
80
|
+
const writableRepos = normalizePathList(m?.index?.writableRepos)
|
|
78
81
|
const batchRecords = batchSegments(m?.docRoot?.batches) // §6.14 面⑥ 声明值投影(`declared` 旗不涉——docRoot 族现状零改)
|
|
79
82
|
const defaults = normalizeCodePaths(DEFAULT_MANIFEST.codePaths) ?? []
|
|
80
83
|
const pathsDiffer = codePaths.length !== defaults.length || codePaths.some((p, i) => p !== defaults[i])
|
|
@@ -88,6 +91,9 @@ function buildDeclaration(m, root = null) {
|
|
|
88
91
|
docExtensions: Object.freeze(docExtensions),
|
|
89
92
|
excludePaths: Object.freeze(excludePaths),
|
|
90
93
|
publicRepos: Object.freeze(publicRepos),
|
|
94
|
+
// 写权声明(机制 = `docs/core/design/CROSS-REPO-WRITE.md` §2.1):投影值,`declared` 旗不涉——
|
|
95
|
+
// 与 `docCheckExcludePaths` 族同款;写名单本身不是「本仓声明偏离默认」的证据。
|
|
96
|
+
writableRepos: Object.freeze(writableRepos),
|
|
91
97
|
}),
|
|
92
98
|
root,
|
|
93
99
|
})
|
|
@@ -258,9 +264,15 @@ export function isInDeclaredScope(rel, scope, base = null) {
|
|
|
258
264
|
*/
|
|
259
265
|
export function declaredPublicRoots(cwd) {
|
|
260
266
|
const decl = loadProjectDeclaration(cwd)
|
|
261
|
-
|
|
267
|
+
return absoluteDeclaredRoots(decl?.index?.publicRepos, decl, cwd)
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** 声明项 → 绝对根集(`declaredPublicRoots` ∥ `declaredWritableRoots` 共用的**取基法**,只有一份):
|
|
271
|
+
* 值形层逐项 `resolve(声明项目的项目根, p)` ⇒ 绝对根集(去重保序);存在性判归消费面(本层不判)。
|
|
272
|
+
* 两键不同族(读名单 / 写名单),但「从哪个根解析、怎么去重」是同一条规则——写第二份就会漂。 */
|
|
273
|
+
function absoluteDeclaredRoots(list, decl, cwd) {
|
|
262
274
|
if (!Array.isArray(list) || list.length === 0) return []
|
|
263
|
-
const base = typeof decl
|
|
275
|
+
const base = typeof decl?.root === "string" && decl.root !== "" ? decl.root : resolve(cwd ?? ".")
|
|
264
276
|
const out = []
|
|
265
277
|
for (const p of list) {
|
|
266
278
|
const abs = resolve(base, p)
|
|
@@ -269,6 +281,19 @@ export function declaredPublicRoots(cwd) {
|
|
|
269
281
|
return out
|
|
270
282
|
}
|
|
271
283
|
|
|
284
|
+
/**
|
|
285
|
+
* 声明**可写外部目录**的绝对根集(机制 = `docs/core/design/CROSS-REPO-WRITE.md` §2.1 解析层):
|
|
286
|
+
* 写门的跨仓判据用它回答「这个目标在写方声明的授权面里吗」——基数 = 声明项目的项目根,
|
|
287
|
+
* 缺省 `[]` ⇒ `[]`(零行为)。与 `declaredPublicRoots` 同形同基,但两键**不互派**(读名单 ≠ 写名单)。
|
|
288
|
+
* 不判存在性:声明根不在盘时它的前缀含不住任何真实目标,存在性归消费面。
|
|
289
|
+
* @param {string} [cwd] 会话锚(项目根经 manifest.mjs 解析)
|
|
290
|
+
* @returns {string[]} 绝对路径(去重保序)
|
|
291
|
+
*/
|
|
292
|
+
export function declaredWritableRoots(cwd) {
|
|
293
|
+
const decl = loadProjectDeclaration(cwd)
|
|
294
|
+
return absoluteDeclaredRoots(decl?.index?.writableRepos, decl, cwd)
|
|
295
|
+
}
|
|
296
|
+
|
|
272
297
|
/** 引用解析单点(§6.1 口径 4/5——写门 ∥ 迁移旗同消费,不得二写):① 仓根解析 `resolve(base, part)`
|
|
273
298
|
* 为存在的档 ⇒ 命中;② 声明源前缀解析序:首段命中声明公共仓目录名(消费既有 `declaredPublicRoots`
|
|
274
299
|
* ——同名多仓 ⇒ 声明序首者)⇒ 于该声明根解析余段;未声明 ∥ 声明根缺位 ∥ 目标档缺 ⇒ `{ ok: false, abs }`。
|
|
@@ -326,7 +351,8 @@ function warnRetiredCarrier(root) {
|
|
|
326
351
|
* per cache miss (content zero-parsed, zero effect on the readings — KD-M1-34).
|
|
327
352
|
* @param {string} cwd — project dir / anchor (root resolved by manifest.mjs)
|
|
328
353
|
* @returns {Readonly<{declared: boolean, codePaths: readonly string[], batchRecords: readonly (readonly string[])[],
|
|
329
|
-
* index: {codeExtensions: string[], docExtensions: string[], excludePaths: string[], publicRepos: string[]
|
|
354
|
+
* index: {codeExtensions: string[], docExtensions: string[], excludePaths: string[], publicRepos: string[],
|
|
355
|
+
* writableRepos: string[]},
|
|
330
356
|
* root: string|null}>}
|
|
331
357
|
*/
|
|
332
358
|
export function loadProjectDeclaration(cwd) {
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* declared-repos.mjs — **声明出边图 + 环走查**(叶档:只 import `node:*` 与 `manifest.mjs` / `declaration.mjs`)。
|
|
3
|
+
*
|
|
4
|
+
* 判据单源 = `docs/core/design/PATH-RESOLUTION.md` §2.7「声明仓引用」与「环检」两段(本档只实现,不重述口径)。
|
|
5
|
+
* 两件事:
|
|
6
|
+
* · `declaredOutEdges(root)` = 本仓的**出边**(`index.publicRepos` 各项)——根集单源 = `declaration.mjs` 的
|
|
7
|
+
* `declaredPublicRoots`,本档只补它不出的三件:**目录名**(首段匹配用)· **声明项原文**(报面用)· **本机在盘与否**。
|
|
8
|
+
* 同一份声明表逐项对位,不重建第二张表。
|
|
9
|
+
* · `declaredCycles(root)` = 沿出边 DFS 的回边走查:只报**穿过起点**的环(每个仓的门报自己的环,不为别人的环背红)。
|
|
10
|
+
* 无 `PROJECT-MANIFEST.json` 的目录是**叶仓**——没有出边(规则 = `docs/core/design/PATH-RESOLUTION.md` §2.7「叶仓」)。
|
|
11
|
+
* 走查撞到**声明根不在本机**的节点 ⇒ 该节点止步,并记入 `stopped`——「没找到环」与「没看过去」因此在报面上分得开。
|
|
12
|
+
*
|
|
13
|
+
* 不缓存(§2.7 边界:同一份声明表逐项现读——`loadProjectDeclaration` 自带按档路径的同轮缓存,那是读取面相而非本档)。
|
|
14
|
+
*/
|
|
15
|
+
import { statSync } from "node:fs"
|
|
16
|
+
import { basename, join, resolve } from "node:path"
|
|
17
|
+
|
|
18
|
+
import { declaredPublicRoots, loadProjectDeclaration } from "./declaration.mjs"
|
|
19
|
+
import { MANIFEST_REL } from "./manifest.mjs"
|
|
20
|
+
|
|
21
|
+
/** 路径同一性(`win32` 大小写不敏感——同 `path-resolve.mjs` 的基根去重口径)。 */
|
|
22
|
+
const pathKey = (p) => (process.platform === "win32" ? p.toLowerCase() : p)
|
|
23
|
+
|
|
24
|
+
const isDir = (p) => { try { return statSync(p).isDirectory() } catch { return false } }
|
|
25
|
+
const isFile = (p) => { try { return statSync(p).isFile() } catch { return false } }
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* 本仓的声明出边(声明序;同名多仓各自一条,调用面取首者)。
|
|
29
|
+
* @param {string} [root] 会话锚 / 项目根(项目根经 `manifest.mjs` 解析——深 cwd 等义)
|
|
30
|
+
* @returns {{root:string, name:string, entry:string, onDisk:boolean, hasManifest:boolean}[]}
|
|
31
|
+
* `root` = 声明根绝对路径 · `name` = 其目录名(首段匹配用)· `entry` = `index.publicRepos` 里的声明项原文 ·
|
|
32
|
+
* `onDisk` = 该根在本机是否是目录 · `hasManifest` = 其下是否有 `PROJECT-MANIFEST.json`(决定它有没有出边)
|
|
33
|
+
*/
|
|
34
|
+
export function declaredOutEdges(root) {
|
|
35
|
+
const start = resolve(root ?? ".")
|
|
36
|
+
const roots = declaredPublicRoots(start)
|
|
37
|
+
if (roots.length === 0) return []
|
|
38
|
+
let decl = null
|
|
39
|
+
try { decl = loadProjectDeclaration(start) } catch { decl = null }
|
|
40
|
+
const list = Array.isArray(decl?.index?.publicRepos) ? decl.index.publicRepos : []
|
|
41
|
+
const base = typeof decl?.root === "string" && decl.root !== "" ? decl.root : start
|
|
42
|
+
const entryOf = new Map() // 声明根绝对路径 → 声明项原文(同一根重复声明 ⇒ 取首个)
|
|
43
|
+
for (const p of list) {
|
|
44
|
+
const abs = resolve(base, p)
|
|
45
|
+
if (!entryOf.has(pathKey(abs))) entryOf.set(pathKey(abs), p)
|
|
46
|
+
}
|
|
47
|
+
return roots.map((abs) => ({
|
|
48
|
+
root: abs,
|
|
49
|
+
name: basename(abs),
|
|
50
|
+
entry: entryOf.get(pathKey(abs)) ?? "",
|
|
51
|
+
onDisk: isDir(abs),
|
|
52
|
+
hasManifest: isFile(join(abs, MANIFEST_REL)),
|
|
53
|
+
}))
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* 环走查(从被判根出发,只报穿过它的环)。
|
|
58
|
+
* 终止性由 `expanded` 集保证(路径同一性;`win32` 大小写不敏感)⇒ 不设深度帽。
|
|
59
|
+
* @param {string} root 被判档的组根(环的起点——节点 = 仓根绝对路径)
|
|
60
|
+
* @returns {{cycles:{names:string[]}[], stopped:{root:string, name:string, entry:string}[]}}
|
|
61
|
+
* `cycles` = 每条环的链(目录名全写:起点 → … → 起点)· `stopped` = 走查在「声明根不在本机」处止步的节点
|
|
62
|
+
* (报面按声明根各出一行 `未核`;去重按路径同一性)
|
|
63
|
+
*/
|
|
64
|
+
export function declaredCycles(root) {
|
|
65
|
+
const start = resolve(root ?? ".")
|
|
66
|
+
const startKey = pathKey(start)
|
|
67
|
+
const cycles = []
|
|
68
|
+
const stopped = []
|
|
69
|
+
const seenCycle = new Set()
|
|
70
|
+
const seenStop = new Set()
|
|
71
|
+
const expanded = new Set([startKey])
|
|
72
|
+
const visit = (node, names) => {
|
|
73
|
+
for (const edge of declaredOutEdges(node)) {
|
|
74
|
+
if (!edge.onDisk) { // 读不到对方 manifest ⇒ 该节点止步(记入列报,不静默)
|
|
75
|
+
const key = pathKey(edge.root)
|
|
76
|
+
if (!seenStop.has(key)) { seenStop.add(key); stopped.push({ root: edge.root, name: edge.name, entry: edge.entry }) }
|
|
77
|
+
continue
|
|
78
|
+
}
|
|
79
|
+
const key = pathKey(edge.root)
|
|
80
|
+
if (key === startKey) { // 走回起点 ⇒ 一条环(链按目录名写全)
|
|
81
|
+
const chain = [...names, basename(start)]
|
|
82
|
+
const id = chain.map(pathKey).join("\u0000")
|
|
83
|
+
if (!seenCycle.has(id)) { seenCycle.add(id); cycles.push({ names: chain }) }
|
|
84
|
+
continue
|
|
85
|
+
}
|
|
86
|
+
if (!edge.hasManifest) continue // 叶仓:没有出边
|
|
87
|
+
if (expanded.has(key)) continue
|
|
88
|
+
expanded.add(key)
|
|
89
|
+
visit(edge.root, [...names, edge.name])
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
visit(start, [basename(start)])
|
|
93
|
+
return { cycles, stopped }
|
|
94
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* doc-check/doc-names.mjs — **档名豁免与 CANON 操作数**族:哪些「看起来像档名」的名字**不算指针**。
|
|
3
|
+
*
|
|
4
|
+
* 判据单源 = `docs/core/design/DOC-DISCIPLINE.md` §3.24 条目 X(档名豁免)∥ `docs/core/design/PROMPT-SYSTEM.md` §6.6
|
|
5
|
+
* 「判保留面」(操作数);本档只实现,不重述口径。
|
|
6
|
+
* **为什么单独立档**:这一族与识别面(`./doc-tokens.mjs` 的「哪些 token 算候选」)是同一层的两条腿——
|
|
7
|
+
* 一条说「这个后缀算本项目的档」,另一条说「这个名字不是指针」;判定件(解析序 ∥ 节在盘 ∥ 环走查)不因它而变。
|
|
8
|
+
* `./anchors.mjs` 再导出本档 ⇒ `./line-refs.mjs` 与 `scripts/prompt-refs-check.mjs` 的 import 行零改。
|
|
9
|
+
*/
|
|
10
|
+
import { TOKEN_LEFT_GUARD, TOKEN_RIGHT_GUARD, isExtension } from "./doc-tokens.mjs"
|
|
11
|
+
|
|
12
|
+
/** 约定文件名(**类名**——文档在描述「会读哪些文件」、黑名单名字、`files` 字段值、测试数据):不抽。
|
|
13
|
+
* 依据 = 这些名字在仓根 / 兄弟目录不一定存在,它们指的不是「某个仓内档」。 */
|
|
14
|
+
const FILENAME_CLASSES = new Set([
|
|
15
|
+
"agents.md", "claude.md", "skill.md", "project_rules.md",
|
|
16
|
+
"changelog.md", "agent.md", "advisor.md", "todo.md", "todo-archive.md",
|
|
17
|
+
])
|
|
18
|
+
|
|
19
|
+
/** 占位符词干(示例写法 / 反例样本——`X.md` / `file.md` / `docs/batches/x.md` 类):不抽。 */
|
|
20
|
+
const PLACEHOLDER_STEMS = new Set([
|
|
21
|
+
"x", "a", "b", "file", "out", "foo", "bar", "example", "sample", "name", "path",
|
|
22
|
+
])
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* 档名豁免判定(**唯一一处** · 判据单源 = `docs/core/design/DOC-DISCIPLINE.md` §3.24 条目 X):
|
|
26
|
+
* 三处消费同一个谓词——锚判(`./anchors.mjs`)∥ `scripts/prompt-refs-check.mjs`(J1 ∥ J3 命中过滤)∥ 行号坐标清单(`./line-refs.mjs`)。
|
|
27
|
+
* **入参 = 写出来的那个 token**(可含目录段),大小写不敏感。**豁免只免裸名**:带目录段的 token 一律按真路径判
|
|
28
|
+
* (`docs/batches/x.md` 不是示例;`tools/file.mjs` 是真档,不能因末段名 `file` 落占位表而整类放过)——
|
|
29
|
+
* 旧式按末段名判(消费面各自 `basename`)就是「真档被当示例」那条漏报的口子。
|
|
30
|
+
* @param {string} token 写出来的档 token(裸名 ∥ `目录段/名`)
|
|
31
|
+
* @returns {null|"filename-class"|"placeholder"} `"filename-class"` = 约定的类名(整名判,不剥后缀);
|
|
32
|
+
* `"placeholder"` = 占位词干(按清单剥后缀后取词干——剥法单源 = `isExtension`;词干 ≤ 1 字符或命中占位表);`null` = 不是豁免名
|
|
33
|
+
*/
|
|
34
|
+
export function docNameExemption(token) {
|
|
35
|
+
const bn = String(token ?? "").replace(/\\/g, "/").toLowerCase()
|
|
36
|
+
if (bn.includes("/")) return null // 带目录段 ⇒ 按真路径判(豁免只免裸名)
|
|
37
|
+
if (FILENAME_CLASSES.has(bn)) return "filename-class"
|
|
38
|
+
const dot = bn.lastIndexOf(".")
|
|
39
|
+
const ext = dot > 0 ? bn.slice(dot + 1) : ""
|
|
40
|
+
const stem = isExtension(ext) ? bn.slice(0, dot) : bn
|
|
41
|
+
if (stem.length <= 1 || PLACEHOLDER_STEMS.has(stem)) return "placeholder"
|
|
42
|
+
return null
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** CANON 操作数族(**规范豁免串** · 判据单源 = `docs/core/design/PROMPT-SYSTEM.md` §6.6「判保留面」):
|
|
46
|
+
* 七个名字在模型面是**模型要写出来 / 读写的文件名**(行为操作数 · 路径操作数),不是「去读这个档」的指针——
|
|
47
|
+
* 换个目录解析必然 `档缺`。**只对提示词面剥**(面判据 = `isPromptFace`,单源住 `./paragraph.mjs`):`docs/` 面不会因本条多放行一个名——
|
|
48
|
+
* `README.md` / `MANIFEST.md` / `RTM.md` / `.thincoder/advisor.md` 在那里仍按指针判(其余三名早已走 `FILENAME_CLASSES` 类名免,
|
|
49
|
+
* 非本条引入;末名带目录段 ⇒ 类名免够不到它——免的是裸名,口径 = `docs/core/design/DOC-DISCIPLINE.md` §3.24「入参契约」)。
|
|
50
|
+
* **一处定义、两处消费**:`scripts/prompt-refs-check.mjs` 的 J3 豁免从本档 import 本表与剥除函数(不复制);
|
|
51
|
+
* 反方向零 import——判据链自持 = `docs/core/design/DOC-DISCIPLINE.md` A-DD29 ⑤(`thincoder-core/**` 对
|
|
52
|
+
* `scripts/**` 的 import 点 = 0)。闭集外的同形 token(非操作数)照报。 */
|
|
53
|
+
export const CANON_OPERANDS = [
|
|
54
|
+
"AGENTS.md", "SKILL.md", "README.md", "MANIFEST.md",
|
|
55
|
+
".thincoder/advisor.md", "project_rules.md",
|
|
56
|
+
"RTM.md",
|
|
57
|
+
]
|
|
58
|
+
|
|
59
|
+
/** 操作数剥除:提示词面逐行先删 `CANON_OPERANDS` 的**整 token** 再抽(与 `scripts/prompt-refs-check.mjs` 的 J3 豁免同式)。
|
|
60
|
+
* **剥除面 = 整 token 边界**(与锚抽取共用同一对边界):只有左右界都成立的操作数名才被吞——名字只是更长 token
|
|
61
|
+
* 的尾段(`test/RTM.md` 里的末段名)⇒ **不剥**,该指针照常抽出、照常判存在性。
|
|
62
|
+
* 改前是子串整串删除(`out.split(s).join("")`):路径前缀留下、末段名被吃,剩下的半截不构成 token,
|
|
63
|
+
* 该指针在提示词面**不被判**(漏报方向)。 */
|
|
64
|
+
const OPERAND_STRIP_RES = CANON_OPERANDS.map((name) => new RegExp(
|
|
65
|
+
`${TOKEN_LEFT_GUARD}${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}${TOKEN_RIGHT_GUARD}`,
|
|
66
|
+
"gu",
|
|
67
|
+
))
|
|
68
|
+
|
|
69
|
+
export function stripCanonOperands(line) {
|
|
70
|
+
let out = String(line)
|
|
71
|
+
for (const re of OPERAND_STRIP_RES) out = out.replace(re, "")
|
|
72
|
+
return out
|
|
73
|
+
}
|