@thincoder/core 0.10.5 → 0.10.7

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.
@@ -0,0 +1,270 @@
1
+ /**
2
+ * browser/snapshot.mjs — 页面侧快照脚本 ∥ 几何 ∥ 点 / 聚焦表达式 ∥ 结果归一 ∥ 引用表 ∥ 紧凑渲染 ∥ 页摘
3
+ * (BROWSER-TOOL.md §2.3 ∥ §2.7)。
4
+ *
5
+ * 页面侧脚本一律经 `Runtime.evaluate` **一次性执行、不驻留**(§3.3);每条表达式带一个块注释标识
6
+ * 前缀(`thincoder-browser:<种类>`)——回执/调试可辨出处,单元测试假传输按此前缀派发。
7
+ * 引用表:`key = tag + "|" + selector`,跨快照复用原号(KD-1 / F-BT4「微变不全失效」)。
8
+ * 几何(F-BT14):每条记录携 `geo`(视口 CSS 像素)与 `inViewport`;`[outside]` 仅标视口外行(KD-15)。
9
+ */
10
+ export const DEFAULT_MAX = 100
11
+ export const MAX_ELEMENTS = 200
12
+ export const MAX_SNAPSHOT_CHARS = 20_000
13
+ export const COMPACT_ROWS = 30 // 失败回执的紧凑清单行数
14
+
15
+ const mark = (kind) => `/*thincoder-browser:${kind}*/`
16
+
17
+ /**
18
+ * 页面侧快照函数源串(`(opts) => 记录集`)。
19
+ * 走交互元素(§2.3):`a[href]` / `button` / `input`(非 hidden) / `select` / `textarea` /
20
+ * `[role=button]` / `[onclick]` / `[tabindex]`;`selector` = 稳定寻址链(`#id` → `[data-testid]`
21
+ * → `[name]` → `[href]` → 结构路径);password 输入**不取 value**(N-BT4)。
22
+ * 几何随记录(§2.7):`geo = {x,y,w,h}` 取整 + `inViewport`(非零面积 ∩ 视口)。
23
+ */
24
+ export const SNAPSHOT_EXPR = String.raw`function (opts) {
25
+ var SEL = 'a[href],button,input:not([type=hidden]),select,textarea,[role=button],[onclick],[tabindex]'
26
+ var norm = function (s) { return String(s == null ? '' : s).replace(/\s+/g, ' ').trim().slice(0, 60) }
27
+ var esc = function (s) {
28
+ try { return (globalThis.CSS && CSS.escape) ? CSS.escape(String(s)) : String(s).replace(/[^a-zA-Z0-9_-]/g, function (c) { return '\\' + c }) }
29
+ catch (e) { return String(s) }
30
+ }
31
+ var unique = function (sel) { try { return document.querySelectorAll(sel).length === 1 } catch (e) { return false } }
32
+ var pathOf = function (el) {
33
+ var parts = []
34
+ var cur = el
35
+ while (cur && cur.nodeType === 1 && cur !== document.documentElement) {
36
+ if (cur.id && unique('#' + esc(cur.id))) { parts.unshift('#' + esc(cur.id)); break }
37
+ var tag = cur.tagName.toLowerCase()
38
+ var parent = cur.parentElement
39
+ if (!parent) { parts.unshift(tag); break }
40
+ var same = Array.prototype.filter.call(parent.children, function (c) { return c.tagName === cur.tagName })
41
+ parts.unshift(same.length > 1 ? tag + ':nth-of-type(' + (same.indexOf(cur) + 1) + ')' : tag)
42
+ cur = parent
43
+ }
44
+ return parts.join(' > ')
45
+ }
46
+ var selectorOf = function (el) {
47
+ if (el.id && unique('#' + esc(el.id))) return '#' + esc(el.id)
48
+ var testid = el.getAttribute('data-testid')
49
+ if (testid && unique('[data-testid="' + testid + '"]')) return '[data-testid="' + testid + '"]'
50
+ var name = el.getAttribute('name')
51
+ if (name && unique('[name="' + name + '"]')) return '[name="' + name + '"]'
52
+ var href = el.getAttribute('href')
53
+ if (href && el.tagName === 'A' && unique('[href="' + href + '"]')) return '[href="' + href + '"]'
54
+ return pathOf(el)
55
+ }
56
+ var roleOf = function (el, tag) {
57
+ var t = String(el.getAttribute('type') || '').toLowerCase()
58
+ if (tag === 'a') return 'link'
59
+ if (tag === 'select') return 'select'
60
+ if (tag === 'textarea') return 'textbox'
61
+ if (tag === 'button') return 'button'
62
+ if (tag === 'input') {
63
+ if (t === 'password') return 'password'
64
+ if (t === 'checkbox') return 'checkbox'
65
+ if (t === 'radio') return 'radio'
66
+ if (t === 'submit' || t === 'button' || t === 'reset' || t === 'image') return 'button'
67
+ return 'textbox'
68
+ }
69
+ if (el.getAttribute('role') === 'button' || el.hasAttribute('onclick')) return 'button'
70
+ return 'other'
71
+ }
72
+ var nameOf = function (el) {
73
+ // 可及名取序照 §2.3:aria-label ∥ 文本 ∥ placeholder ∥ title
74
+ return norm(el.getAttribute('aria-label') || el.innerText || el.textContent || el.getAttribute('placeholder') || el.getAttribute('title') || '')
75
+ }
76
+ var rectOf = function (el) {
77
+ var r = el.getBoundingClientRect()
78
+ return { x: Math.round(r.left), y: Math.round(r.top), w: Math.round(r.width), h: Math.round(r.height) }
79
+ }
80
+ var inViewportOf = function (g) {
81
+ return g.w > 0 && g.h > 0 && g.x < innerWidth && g.y < innerHeight && g.x + g.w > 0 && g.y + g.h > 0
82
+ }
83
+ var root = (opts && opts.selector) ? document.querySelector(opts.selector) : document
84
+ if (!root) return { missing: true, url: location.href, title: document.title, elements: [], total: 0 }
85
+ var nodes = []
86
+ if (root.nodeType === 1 && root.matches && root.matches(SEL)) nodes.push(root)
87
+ var found = root.querySelectorAll ? root.querySelectorAll(SEL) : []
88
+ for (var i = 0; i < found.length; i++) nodes.push(found[i])
89
+ var max = Math.max(1, (opts && opts.max) ? opts.max : 100)
90
+ var elements = []
91
+ for (var j = 0; j < nodes.length && elements.length < max; j++) {
92
+ var el = nodes[j]
93
+ var tag = el.tagName.toLowerCase()
94
+ var role = roleOf(el, tag)
95
+ var geo = rectOf(el)
96
+ var rec = {
97
+ tag: tag,
98
+ role: role,
99
+ name: nameOf(el),
100
+ selector: selectorOf(el),
101
+ disabled: Boolean(el.disabled) || el.getAttribute('aria-disabled') === 'true',
102
+ geo: geo,
103
+ inViewport: inViewportOf(geo),
104
+ }
105
+ if (role === 'textbox' || role === 'select') rec.value = norm(el.value)
106
+ elements.push(rec)
107
+ }
108
+ return { url: location.href, title: document.title, total: nodes.length, elements: elements }
109
+ }`
110
+
111
+ /** 快照表达式(页面侧一次执行)。 */
112
+ export function snapshotExpression({ selector = null, max = DEFAULT_MAX } = {}) {
113
+ return `${mark("snapshot")}(${SNAPSHOT_EXPR})(${JSON.stringify({ selector, max })})`
114
+ }
115
+
116
+ /** 当前页信息表达式(URL ∥ title ∥ readyState)。 */
117
+ export function pageInfoExpression() {
118
+ return `${mark("pageinfo")}(function () { return { url: location.href, title: document.title, readyState: document.readyState } })()`
119
+ }
120
+
121
+ /** 点击表达式(寻址 + tag 一致校验 + disabled 判;返回 `{found, disabled, tag?}`)。 */
122
+ export function clickExpression(selector, tag) {
123
+ return `${mark("click")}(function () {
124
+ var el = document.querySelector(${JSON.stringify(selector)})
125
+ if (!el) return { found: false }
126
+ var tag = el.tagName.toLowerCase()
127
+ if (tag !== ${JSON.stringify(tag)}) return { found: false, tag: tag }
128
+ if (el.disabled) return { found: true, disabled: true }
129
+ el.scrollIntoView({ block: 'center' })
130
+ el.click()
131
+ return { found: true, disabled: false }
132
+ })()`
133
+ }
134
+
135
+ /** 输入表达式(原生 value setter + input/change 事件;回执判据 = `password` 标记)。 */
136
+ export function typeExpression(selector, tag, text, clear) {
137
+ return `${mark("type")}(function () {
138
+ var el = document.querySelector(${JSON.stringify(selector)})
139
+ if (!el) return { found: false }
140
+ var tag = el.tagName.toLowerCase()
141
+ if (tag !== ${JSON.stringify(tag)}) return { found: false, tag: tag }
142
+ if (tag !== 'input' && tag !== 'textarea') return { found: true, disabled: false, password: false, fillable: false }
143
+ var password = tag === 'input' && String(el.getAttribute('type') || '').toLowerCase() === 'password'
144
+ if (el.disabled) return { found: true, disabled: true, password: password }
145
+ var proto = tag === 'textarea' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype
146
+ var desc = Object.getOwnPropertyDescriptor(proto, 'value')
147
+ var next = ${clear ? "true" : "false"} ? ${JSON.stringify(text)} : String(el.value == null ? '' : el.value) + ${JSON.stringify(text)}
148
+ if (desc && desc.set) desc.set.call(el, next); else el.value = next
149
+ el.dispatchEvent(new Event('input', { bubbles: true }))
150
+ el.dispatchEvent(new Event('change', { bubbles: true }))
151
+ return { found: true, disabled: false, password: password }
152
+ })()`
153
+ }
154
+
155
+ /** 点表达式(ref → 真点——§2.7):`scrollIntoView({block:'center'})` → 重测 → 返回中心点与 `{found, tag?}`。 */
156
+ export function pointExpression(selector, tag) {
157
+ return `${mark("point")}(function () {
158
+ var el = document.querySelector(${JSON.stringify(selector)})
159
+ if (!el) return { found: false }
160
+ var tag = el.tagName.toLowerCase()
161
+ if (tag !== ${JSON.stringify(tag)}) return { found: false, tag: tag }
162
+ el.scrollIntoView({ block: 'center' })
163
+ var r = el.getBoundingClientRect()
164
+ return { found: true, x: r.left + r.width / 2, y: r.top + r.height / 2 }
165
+ })()`
166
+ }
167
+
168
+ /** 聚焦表达式(§2.7):`scrollIntoView` + `focus()` → `{found, tag?, focused}`;不可聚焦 ⇒ `focused:false`。 */
169
+ export function focusExpression(selector, tag) {
170
+ return `${mark("focus")}(function () {
171
+ var el = document.querySelector(${JSON.stringify(selector)})
172
+ if (!el) return { found: false }
173
+ var tag = el.tagName.toLowerCase()
174
+ if (tag !== ${JSON.stringify(tag)}) return { found: false, tag: tag }
175
+ el.scrollIntoView({ block: 'center' })
176
+ try { el.focus() } catch (e) { /* 不可聚焦元素(div 等)——focused 读回自证 */ }
177
+ return { found: true, focused: document.activeElement === el }
178
+ })()`
179
+ }
180
+
181
+ /** 等待谓词表达式(selector ∥ text ∥ url——networkIdle 走核侧事件计数)。 */
182
+ export function waitExpression(kind, value) {
183
+ const expr = kind === "selector" ? `!!document.querySelector(${JSON.stringify(value)})`
184
+ : kind === "text" ? `String((document.body && document.body.innerText) || '').includes(${JSON.stringify(value)})`
185
+ : `location.href.includes(${JSON.stringify(value)})`
186
+ return `${mark("wait")}(function () { return ${expr} })()`
187
+ }
188
+
189
+ /** 页面侧结果 → 形状归一的记录集(不可信输入:缺字段/异型一律归一,不抛)。 */
190
+ export function normalizeSnapshot(raw) {
191
+ const r = raw && typeof raw === "object" ? raw : {}
192
+ const num = (v) => (Number.isFinite(Number(v)) ? Math.round(Number(v)) : 0)
193
+ const elements = (Array.isArray(r.elements) ? r.elements : [])
194
+ .filter((e) => e && typeof e === "object" && e.selector)
195
+ .map((e) => {
196
+ const rec = {
197
+ tag: String(e.tag ?? "").toLowerCase(),
198
+ role: String(e.role ?? "other"),
199
+ name: String(e.name ?? ""),
200
+ selector: String(e.selector),
201
+ disabled: e.disabled === true,
202
+ }
203
+ if (e.value !== undefined && e.value !== null && String(e.value) !== "") rec.value = String(e.value)
204
+ if (e.geo && typeof e.geo === "object") {
205
+ rec.geo = { x: num(e.geo.x), y: num(e.geo.y), w: num(e.geo.w), h: num(e.geo.h) }
206
+ }
207
+ if (e.inViewport === false) rec.inViewport = false // 仅视口外落标记(在屏行文法零动——KD-15)
208
+ return rec
209
+ })
210
+ return {
211
+ url: String(r.url ?? ""),
212
+ title: String(r.title ?? ""),
213
+ elements,
214
+ total: Number.isInteger(r.total) ? Math.max(r.total, elements.length) : elements.length,
215
+ missing: r.missing === true,
216
+ }
217
+ }
218
+
219
+ /** 核侧引用表(会话级——`byRef` 反查、`byKey` 复用、`counter` 会话内单调)。 */
220
+ export function createRefTable() {
221
+ return { byRef: new Map(), byKey: new Map(), counter: 1 }
222
+ }
223
+
224
+ /** 记录集 → 引用行(key 已在表 ⇒ 复用原号;未见 ⇒ 新号 + `isNew`)。 */
225
+ export function assignRefs(table, elements) {
226
+ const rows = []
227
+ for (const el of elements) {
228
+ const key = `${el.tag}|${el.selector}`
229
+ let entry = table.byKey.get(key)
230
+ const isNew = !entry
231
+ if (isNew) {
232
+ entry = { ref: `e${table.counter++}`, key, selector: el.selector, tag: el.tag, name: el.name }
233
+ table.byKey.set(key, entry)
234
+ table.byRef.set(entry.ref, entry)
235
+ } else {
236
+ entry.name = el.name // 名随页面更新;号不变(F-BT4)
237
+ }
238
+ rows.push({ ...el, ref: entry.ref, isNew })
239
+ }
240
+ return rows
241
+ }
242
+
243
+ /** 结果行文法:`<ref> <role> "<name>"` + `[value=…]`(password 除外)+ `[new]` + `[disabled]` + `[outside]`。 */
244
+ export function rowLine(row) {
245
+ const marks = []
246
+ if (row.role !== "password" && row.value !== undefined && String(row.value) !== "") marks.push(`[value="${row.value}"]`)
247
+ if (row.isNew) marks.push("[new]")
248
+ if (row.disabled) marks.push("[disabled]")
249
+ if (row.inViewport === false) marks.push("[outside]")
250
+ return `${row.ref} ${row.role} "${row.name}"${marks.length ? ` ${marks.join(" ")}` : ""}`
251
+ }
252
+
253
+ /** 页摘行(内容与出处同行——N-BT2 来源标注)。 */
254
+ export function pageDigest(url, title) {
255
+ return `[page] ${url} — "${title}"`
256
+ }
257
+
258
+ /** 紧凑渲染:页摘 ∥ 计数行 ∥ 元素行 ∥ 截断标记;总文本 ≤ 20,000 字符(N-BT3)。 */
259
+ export function renderSnapshot({ url, title, rows = [], total = rows.length }) {
260
+ const lines = [pageDigest(url, title), `[${total} interactive elements (${rows.filter((r) => r.isNew).length} new)]`]
261
+ for (const row of rows) lines.push(rowLine(row))
262
+ if (total > rows.length) lines.push(`[truncated: showing ${rows.length} of ${total} — pass selector to narrow]`)
263
+ return truncateText(lines.join("\n"), MAX_SNAPSHOT_CHARS, "pass selector to narrow")
264
+ }
265
+
266
+ /** 截断(`truncate` 同款标记形态——`tools/shared.mjs:190-193`)。 */
267
+ export function truncateText(text, max, note = "narrow the request") {
268
+ if (text.length <= max) return text
269
+ return `${text.slice(0, max)}\n[... truncated: ${text.length - max} chars omitted — ${note}]`
270
+ }
package/conventions.mjs CHANGED
@@ -189,4 +189,4 @@ export function isStatePath(p, conv) {
189
189
  // 迁出面(2026-10-01 拆分批 · #755 ∥ #786):声明装载面外提 `declaration.mjs`——本档经
190
190
  // 转口保名(消费面 / 单元测试档 import 面零改;`DEFAULT_DECLARATION` 另供本档分类裁判缺省取用)。
191
191
  // ─────────────────────────────────────────────────────────────────────────────
192
- export { loadProjectDeclaration, declarationForTarget, DEFAULT_DECLARATION, isExcludedRelPath, declaredPublicRoots, clearDeclarationCache } from "./declaration.mjs"
192
+ export { loadProjectDeclaration, declarationForTarget, DEFAULT_DECLARATION, isExcludedRelPath, declaredIndexScope, isInDeclaredScope, declaredPublicRoots, clearDeclarationCache } from "./declaration.mjs"
package/declaration.mjs CHANGED
@@ -5,9 +5,10 @@
5
5
  * name / shape / defaults = schema 面 `docs/core/design/MANIFEST.md` §2.2)。迁出块逐字;
6
6
  * 原档 `conventions.mjs` 经 `export { … } from` 转口保名(消费面 / 单元测试档 import 面零改)。
7
7
  */
8
- import { existsSync, statSync } from "node:fs"
8
+ import { existsSync, readdirSync, statSync } from "node:fs"
9
9
  import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path"
10
- import { DEFAULT_MANIFEST, manifestFilePath, owningProject, readManifest } from "./manifest.mjs"
10
+ import { DEFAULT_MANIFEST, MANIFEST_REL, docRootPaths, manifestFilePath, owningProject, readManifest } from "./manifest.mjs"
11
+ import { isSkippedRelPath } from "./memory/file-walk.mjs" // 面⑦ 子目录扫描的跳过段谓词单源(零环:file-walk 不引本档)
11
12
  import { logEvent } from "./log.mjs"
12
13
 
13
14
  /** Retired declaration carrier (project-root relative). Its EXISTENCE is checked, its
@@ -78,6 +79,7 @@ function buildDeclaration(m, root = null) {
78
79
  const docExtensions = normalizeExtensions(m?.index?.docExtensions)
79
80
  const excludePaths = normalizePathList(m?.index?.excludePaths)
80
81
  const publicRepos = normalizePathList(m?.index?.publicRepos)
82
+ const batchRecords = batchSegments(m?.docRoot?.batches) // §6.14 面⑥ 声明值投影(`declared` 旗不涉——docRoot 族现状零改)
81
83
  const docMap = normalizeString(m?.advisor?.docMap)
82
84
  const standardsDoc = normalizeString(m?.advisor?.standardsDoc)
83
85
  const defaults = normalizeCodePaths(DEFAULT_MANIFEST.codePaths) ?? []
@@ -86,6 +88,7 @@ function buildDeclaration(m, root = null) {
86
88
  return Object.freeze({
87
89
  declared,
88
90
  codePaths: Object.freeze(codePaths),
91
+ batchRecords: Object.freeze(batchRecords.map((s) => Object.freeze(s))),
89
92
  index: Object.freeze({
90
93
  codeExtensions: Object.freeze(codeExtensions),
91
94
  docExtensions: Object.freeze(docExtensions),
@@ -101,25 +104,158 @@ function buildDeclaration(m, root = null) {
101
104
  * consumer gets; built from `DEFAULT_MANIFEST` so the default values stay single-source. */
102
105
  export const DEFAULT_DECLARATION = buildDeclaration(null)
103
106
 
104
- /** 排除前缀谓词(单源——§6.14 面①):`rel`(**`base` 相对**——缺省视为根相对)命中声明前缀(恰等
105
- * ∨ 后随 `/`——`openclaw` 不吞 `openclaw-fork`)⇒ true;缺省 `[]` ⇒ 恒 false(零行为变化)。
107
+ /** 段序列归一(面⑥ 目标集):值(串 ∥ 串数组——元素层归一同 `normalizePathList`)⇒ 实义段序列
108
+ * (空 ∥ `.` ∥ `..` 段剔除——空序列另剔,防恒真;去重保序)。 */
109
+ function batchSegments(v) {
110
+ const out = []
111
+ for (const e of normalizePathList(Array.isArray(v) ? v : v == null ? [] : [v])) {
112
+ const segs = e.split("/").filter((s) => s && s !== "." && s !== "..")
113
+ if (segs.length && !out.some((q) => q.length === segs.length && q.every((s, i) => s === segs[i]))) out.push(segs)
114
+ }
115
+ return out
116
+ }
117
+
118
+ /** 约定段(面⑥——`DEFAULT_MANIFEST.docRoot.batches` 单源派生;默认值改名/迁移两处同动)。 */
119
+ const DEFAULT_BATCH_SEGMENTS = batchSegments(DEFAULT_MANIFEST.docRoot.batches)
120
+
121
+ /** 排除谓词(单源——§6.14 面① 前缀 ∥ 面⑥ 批次档段序列;两族同一谓词全判,非第二判定面):
122
+ * 面⑥(2026-10-13 · 台账 #1366 · **无条件**——不看 `index.excludePaths` 是否配置):`rel` 命中
123
+ * 约定段 ∪ 声明值段序列(`decl.batchRecords`——`docRoot.batches` 投影)于**路径任意深度**
124
+ * (段边界 = 整段一致——`docs/batchesx` ∥ `doc/batches` 判假)⇒ true;`docRoot.batches: null`
125
+ * ⇒ 约定段恒在(无逃生口);`decl` 缺 ⇒ 约定段照判。
126
+ * 面①(前缀语义):`rel`(**`base` 相对**——缺省视为根相对)命中声明前缀(恰等 ∨ 后随 `/`——
127
+ * `openclaw` 不吞 `openclaw-fork`)⇒ true;缺省 `[]` ⇒ 恒 false(零行为变化)。
106
128
  * `base`(调用面 cwd/origin·#700)= `rel` 的相对基:`resolve` + `relative` 换算至 `decl.root` 根面
107
- * 再比前缀(cwd = 项目根时与既有行为逐字等义);换算越出根面(`..` 头 ∥ 根外绝对形)⇒ **不命中**
108
- * (保守不排除——沉默洞方向收窄,与 D17 aux 面「indeterminate ⇒ 不匹配」同向);`decl.root` 缺
109
- * ⇒ `rel` 原样(根起步调用面等义)。 */
129
+ * 再判(cwd = 项目根时与既有行为逐字等义);换算越出根面(`..` 头 ∥ 根外绝对形)⇒ 面① **不命中**
130
+ * (保守不排除——沉默洞方向收窄,与 D17 aux 面「indeterminate ⇒ 不匹配」同向)∥ 面⑥ 按入参
131
+ * **原样 `rel`** 判(段序列面不回退——面① 不命中口径逐字零改);`decl.root` 缺 ⇒ `rel` 原样
132
+ * (根起步调用面等义)。 */
110
133
  export function isExcludedRelPath(rel, decl, base = null) {
111
- const list = decl?.index?.excludePaths
112
- if (!Array.isArray(list) || list.length === 0) return false
113
134
  let s = String(rel ?? "").replace(/\\/g, "/")
114
135
  const root = decl?.root
136
+ let inRoot = true
115
137
  if (base != null && root) {
116
138
  const converted = relative(root, resolve(base, s)).replace(/\\/g, "/")
117
- if (converted === ".." || converted.startsWith("../") || isAbsolute(converted)) return false
118
- s = converted
139
+ if (converted === ".." || converted.startsWith("../") || isAbsolute(converted)) inRoot = false
140
+ else s = converted
119
141
  }
142
+ // 面⑥ 段序列(约定段 ∪ 声明值——任意深度连续命中);越根(`inRoot=false`)⇒ `s` 即原样 rel
143
+ const segs = s.split("/").filter(Boolean)
144
+ if ([...DEFAULT_BATCH_SEGMENTS, ...(decl?.batchRecords ?? [])].some((seq) => segs.some((_, i) => seq.every((q, j) => segs[i + j] === q)))) return true
145
+ // 面① 前缀(既有口径逐字零改:缺省 `[]` ∥ 越根 ⇒ 不命中)
146
+ const list = decl?.index?.excludePaths
147
+ if (!Array.isArray(list) || list.length === 0 || !inRoot) return false
120
148
  return list.some((p) => p && (s === p || s.startsWith(`${p}/`)))
121
149
  }
122
150
 
151
+ // ─────────────────────────────────────────────────────────────────────────────
152
+ // §6.14 面⑦ 索引范围声明化(结构门——2026-10-13 · 台账 #1367):范围 = 锚的**管辖 manifest**
153
+ // 声明目录 ∪ **一级子目录**(带档者)声明目录——「未声明 ⇒ 不进」;条目集空 ⇒ 零索引
154
+ // (不回落全树)。键面 = `docRoot.*`(五子键合并)∪ `codePaths`——两键各按自身既有语义
155
+ // (本规 = 新增消费点,键值语义零改)。写面(收录)∥ 读面(存量行准入)共用本谓词族。
156
+ // ─────────────────────────────────────────────────────────────────────────────
157
+
158
+ /** 文档面前缀集合(条目根相对——`docRoot.*` 五子键合并展开;解析单源 = `docRootPaths`,F7):
159
+ * 值 = 根相对字面前缀(恰等 ∨ 后随 `/`——路径及子树;文件值如 `docs/RELEASE.md` ⇒ 恰该文件);
160
+ * `"."` = 该条目根自身(整根面);越根值(`../` 形)剔除——条目子树内的文件永不可命中它。
161
+ * 去重保序。 */
162
+ function entryDocPaths(docRoot, root) {
163
+ const out = []
164
+ if (docRoot === null || typeof docRoot !== "object" || Array.isArray(docRoot)) return out
165
+ for (const key of Object.keys(DEFAULT_MANIFEST.docRoot)) {
166
+ for (const abs of docRootPaths(docRoot[key], root)) {
167
+ const rel = relative(root, abs).replace(/\\/g, "/")
168
+ if (rel === "" || rel === ".") { if (!out.includes(".")) out.push("."); continue }
169
+ if (rel === ".." || rel.startsWith("../") || isAbsolute(rel)) continue
170
+ if (!out.includes(rel)) out.push(rel)
171
+ }
172
+ }
173
+ return out
174
+ }
175
+
176
+ /** 段序列任意深度连续命中(面⑦ 代码面——大小写不敏感 = 既有键语义口径,同 `conventions.mjs`
177
+ * `hasSequenceIn`);`face` = 已小写化的根相对段表。 */
178
+ function hasSegmentRun(face, seq) {
179
+ const want = String(seq).replace(/\\/g, "/").split("/").filter(Boolean).map((s) => s.toLowerCase())
180
+ if (want.length === 0) return false
181
+ for (let i = 0; i + want.length <= face.length; i++) {
182
+ if (want.every((w, j) => face[i + j] === w)) return true
183
+ }
184
+ return false
185
+ }
186
+
187
+ /** 面⑦ 一条目(`root` = 仓根绝对路径;档在场 = 调用面已判):`docPaths` = 根相对字面前缀 ∥
188
+ * `codePaths` = 段名数组(既有归一单源 = `loadProjectDeclaration`——`[]` = 无段面)。档**非法**
189
+ * (坏 JSON ∥ 形态错)⇒ 两族按默认值参与 + 既有可见告警(声明链 KD-M1-32——`loadProjectDeclaration`
190
+ * 的降级告警单源,本档零第二实现)——不静默成零。 */
191
+ function scopeEntryOf(root) {
192
+ const decl = loadProjectDeclaration(root)
193
+ const r = readManifest(root)
194
+ const docRoot = r.ok ? r.manifest.docRoot : DEFAULT_MANIFEST.docRoot // 档在场才补默认(无档 = 无条目,不走本函数)
195
+ return Object.freeze({
196
+ root,
197
+ docPaths: Object.freeze(entryDocPaths(docRoot, root)),
198
+ codePaths: Object.freeze([...decl.codePaths]),
199
+ })
200
+ }
201
+
202
+ /**
203
+ * §6.14 面⑦ 范围求并(结构门——单源):① `dir` 的**管辖 manifest**(`manifestFilePath(dir)` 同一根
204
+ * 解析——最近祖先带档 ∥ 发现兜底;**可高于 `dir`** ⇒ 深 cwd 等义)在场 ⇒ 锚条目(`root` = 档所在
205
+ * 目录);② `dir` 的**直接子目录**(非跳过段——点段 ∥ 内建名单,防 `.thincoder/tmp` 类伪档)根下带档
206
+ * 者 ⇒ 各一条目(`root` = 该子目录)。**一层、纯向下、绝不向上**(发现纪律在案)。
207
+ * 冻结条目数组(按根去重保序);条目集空 ⇒ 范围空 ⇒ **零索引**(不回落全树)。
208
+ * 缓存按 `dir` 归一绝对路径(`clearDeclarationCache()` 同清——测试缝单点)。
209
+ * @param {string} [dir] 会话锚 ∕ 同步根(项目内子目录 ⇒ 管辖 manifest 生效)
210
+ * @returns {ReadonlyArray<{root: string, docPaths: readonly string[], codePaths: readonly string[]}>}
211
+ */
212
+ export function declaredIndexScope(dir) {
213
+ const key = resolve(dir ?? ".")
214
+ const hit = _scopeCache.get(key)
215
+ if (hit) return hit
216
+ const roots = []
217
+ const anchorFile = manifestFilePath(key) // 数据档路径单源(KD-M1-18)
218
+ if (existsSync(anchorFile)) roots.push(dirname(anchorFile))
219
+ let names = []
220
+ try { names = readdirSync(key, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort() } catch { /* 不可读 ⇒ 零子条目(不抛——同发现梯内核) */ }
221
+ for (const name of names) {
222
+ if (isSkippedRelPath(name)) continue
223
+ const child = join(key, name)
224
+ if (!existsSync(join(child, MANIFEST_REL)) || roots.includes(child)) continue // 发现兜底命中的子目录 = 锚条目同根 ⇒ 去重
225
+ roots.push(child)
226
+ }
227
+ const scope = Object.freeze(roots.map(scopeEntryOf))
228
+ _scopeCache.set(key, scope)
229
+ return scope
230
+ }
231
+
232
+ /**
233
+ * §6.14 面⑦ 范围谓词(纯谓词——单一实现,写面 ∥ 读面共用):`rel`(`base` 相对;缺省按进程 cwd
234
+ * 解析)经 `resolve` 绝对化 ⇒ 逐条目判归属(`abs` ∈ `root` 子树;无归属条目 = **未声明**)⇒ 两面试
235
+ * 任一命中即入范围(两层锚条目间 = 并集):
236
+ * · **文档面** = 条目根相对面**字面前缀**(恰等 ∨ 后随 `/`;`"."` = 整根);
237
+ * · **代码面** = 段序列**任意深度**命中(大小写不敏感)。
238
+ * 不在任何条目子树内(越根)⇒ 不命中。`scope` 空 ∥ 缺 ⇒ false(零索引面——未声明 ⇒ 不进)。
239
+ * @param {string} rel 路径(`base` 相对)
240
+ * @param {ReadonlyArray<object>} scope `declaredIndexScope()` 回执
241
+ * @param {string|null} [base] `rel` 的相对基(目录绝对路径;缺省 = 进程 cwd)
242
+ * @returns {boolean}
243
+ */
244
+ export function isInDeclaredScope(rel, scope, base = null) {
245
+ if (!Array.isArray(scope) || scope.length === 0) return false
246
+ const abs = resolve(base ?? ".", String(rel ?? "").replace(/\\/g, "/"))
247
+ for (const entry of scope) {
248
+ const relFromRoot = relative(entry.root, abs).replace(/\\/g, "/")
249
+ if (relFromRoot === "" || relFromRoot === ".." || relFromRoot.startsWith("../") || isAbsolute(relFromRoot)) continue
250
+ if (entry.docPaths.some((p) => p === "." || relFromRoot === p || relFromRoot.startsWith(`${p}/`))) return true
251
+ if (entry.codePaths.length > 0) {
252
+ const face = relFromRoot.split("/").filter(Boolean).map((s) => s.toLowerCase())
253
+ if (entry.codePaths.some((seq) => hasSegmentRun(face, seq))) return true
254
+ }
255
+ }
256
+ return false
257
+ }
258
+
123
259
  /**
124
260
  * 声明公共仓**绝对根集**(§6.15 解析层——检索同步 ∥ 读面 origin 集 ∥ 引用解析三消费面共用的单一定义,
125
261
  * 不得二写):值形层逐项 `resolve(decl.root, p)` ⇒ 绝对根集(去重保序);存在性判归消费面(本层不判)。
@@ -165,10 +301,14 @@ export function resolveDeclaredRef(base, part) {
165
301
  const isFile = (p) => { try { return statSync(p).isFile() } catch { return false } }
166
302
 
167
303
  const _cache = new Map()
304
+ /** 面⑦ 范围缓存(按 `dir` 归一绝对路径——子目录档 ∥ 声明变更后经本缝同清)。 */
305
+ const _scopeCache = new Map()
168
306
 
169
- /** Drop the per-data-file-path cache (test seam — declarations are read once per path). */
307
+ /** Drop the per-data-file-path cache (test seam — declarations are read once per path).
308
+ * #1367:面⑦ 范围缓存同清(「声明 ∥ 一级子目录档」变更后同一条测试缝)。 */
170
309
  export function clearDeclarationCache() {
171
310
  _cache.clear()
311
+ _scopeCache.clear()
172
312
  }
173
313
 
174
314
  /** Retired-carrier warning (existence check only — zero content parsing, zero fallback). */
@@ -188,7 +328,7 @@ function warnRetiredCarrier(root) {
188
328
  * A retired `.thincoder/conventions.json` at the manifest's project root → one warning
189
329
  * per cache miss (content zero-parsed, zero effect on the readings — KD-M1-34).
190
330
  * @param {string} cwd — project dir / anchor (root resolved by manifest.mjs)
191
- * @returns {Readonly<{declared: boolean, codePaths: readonly string[],
331
+ * @returns {Readonly<{declared: boolean, codePaths: readonly string[], batchRecords: readonly (readonly string[])[],
192
332
  * index: {codeExtensions: string[], docExtensions: string[], excludePaths: string[], publicRepos: string[]},
193
333
  * advisor: {docMap: string, standardsDoc: string}, root: string|null}>}
194
334
  */
@@ -8,7 +8,7 @@
8
8
  import { embed, embedTolerant, cosine, toBlob, fromBlob } from "../embedding.mjs"
9
9
  import { scanVectors, createTopK } from "./scan.mjs"
10
10
  import { normalizeOrigin } from "./origin.mjs"
11
- import { declaredPublicRoots } from "../conventions.mjs"
11
+ import { declaredPublicRoots, loadProjectDeclaration, isExcludedRelPath, declaredIndexScope, isInDeclaredScope } from "../conventions.mjs"
12
12
  import { buildFtsQuery, ensureEmbeddings, EMBED_TEXT_MAX_LEN } from "./core.mjs"
13
13
  import { safeSliceUTF16 } from "../text-budget.mjs"
14
14
  import { DESC } from "../tools/shared.mjs" // #15 描述外置:文本单点 = tool-docs/code_search.md
@@ -35,13 +35,28 @@ export async function codeSearch(memory, query, { limit = 5 } = {}) {
35
35
  const origins = searchOrigins(memory)
36
36
  const ftsOriginFilter = origins.length === 1 ? `AND c.origin = ?` : origins.length > 1 ? `AND c.origin IN (${origins.map(() => "?").join(", ")})` : ""
37
37
  const originParams = origins
38
+ // §6.14 读面准入过滤(FTS 列表建成后 ∥ 向量 top-K push 前;两判据并列互不吞):排除谓词(面①∪面⑥,
39
+ // 行 origin 为 `base`)∪ 声明范围门(面⑦——`isInDeclaredScope(path, declaredIndexScope(origin), origin)`,
40
+ // 逐 origin 预载一次)⇒「批次档 ∥ 范围外路径从未入索引」等价检索;存量行不删(收尾保护位);窗口欠额接受。
41
+ const declCache = new Map()
42
+ const scopeCache = new Map()
43
+ const rowHidden = (origin, path) => {
44
+ const d = declCache.get(origin) ?? loadProjectDeclaration(origin)
45
+ declCache.set(origin, d)
46
+ if (isExcludedRelPath(path, d, origin)) return true
47
+ let scope = scopeCache.get(origin)
48
+ if (scope === undefined) { scope = declaredIndexScope(origin); scopeCache.set(origin, scope) }
49
+ return !isInDeclaredScope(path, scope, origin)
50
+ }
51
+ const ftsNeedOrigin = origins.length !== 1 // 单 origin 形 SQL 零改;多 origin ∥ 无过滤形补 `origin` 列(行 origin 随行可得)
38
52
 
39
53
  const ftsList = ftsQuery ? memory.db.prepare(`
40
- SELECT c.rowid, c.path, c.language, c.symbol_name, c.content, c.line_start, c.line_end, bm25(code_chunks_fts) AS rank
54
+ SELECT c.rowid, c.path, c.language, c.symbol_name, c.content, c.line_start, c.line_end, bm25(code_chunks_fts) AS rank${ftsNeedOrigin ? ", c.origin" : ""}
41
55
  FROM code_chunks_fts JOIN code_chunks c ON c.rowid = code_chunks_fts.rowid
42
56
  WHERE code_chunks_fts MATCH ? ${ftsOriginFilter}
43
57
  ORDER BY rank LIMIT ?
44
- `).all(ftsQuery, ...originParams, Math.max(limit * 4, 20)) : []
58
+ `).all(ftsQuery, ...originParams, Math.max(limit * 4, 20))
59
+ .filter((r) => !rowHidden(origins.length === 1 ? origins[0] : r.origin, r.path)) : []
45
60
 
46
61
  if (!memory.embedder) return ftsList.slice(0, limit)
47
62
 
@@ -70,7 +85,9 @@ export async function codeSearch(memory, query, { limit = 5 } = {}) {
70
85
  for (const origin of origins.length ? origins : [null]) {
71
86
  await scanVectors(memory.db, vecSql, origin ? [origin] : [], {
72
87
  cursorKey,
73
- onRow: (r) => top.push({ id: r.rowid, rowid: r.rowid, score: cosine(qvec, fromBlob(r.embedding)) }),
88
+ onRow: (r) => { // §6.14 面⑥∪面⑦ 准入(top-K push 前;无过滤形行 origin = 游标键 `origin` 列)
89
+ if (!rowHidden(origin ?? r.origin, r.path)) top.push({ id: r.rowid, rowid: r.rowid, score: cosine(qvec, fromBlob(r.embedding)) })
90
+ },
74
91
  })
75
92
  }
76
93
  const vecList = top.list().map((c) => ({ rowid: c.id, score: c.score }))
@@ -11,7 +11,7 @@ import { ensureEmbeddings, invalidateStaleEmbeddings } from "./core.mjs"
11
11
  import { detectLanguage, _upsertCodeFile, _upsertDocFile, yieldTick } from "./code-index.mjs"
12
12
  import { isSkippedRelPath, extensionOf } from "./file-walk.mjs"
13
13
  import { createRowBudget, rowCountOfPath, sweepStaleRows } from "./sync-tail.mjs"
14
- import { loadProjectDeclaration, isExcludedRelPath, declaredPublicRoots } from "../conventions.mjs"
14
+ import { loadProjectDeclaration, isExcludedRelPath, declaredPublicRoots, declaredIndexScope, isInDeclaredScope } from "../conventions.mjs"
15
15
  import { logEvent } from "../log.mjs"
16
16
  import { indexExtensions, listProjectFiles } from "./file-list.mjs"
17
17
 
@@ -53,6 +53,7 @@ export async function gitSync(memory, dir, opts = {}) {
53
53
  async function gitSyncDir(memory, dir, { onProgress } = {}) {
54
54
  const origin = normalizeOrigin(dir) // §6.11 写缝归一(git / 文件 I/O 用原样 dir;库面 origin 一律归一值)
55
55
  const decl = loadProjectDeclaration(dir)
56
+ const scope = declaredIndexScope(dir) // §6.14 面⑦ 范围门(diff 缝逐行判——见下)
56
57
  const { execFile: _execFile } = await import("node:child_process")
57
58
  const { code: codeExts, doc: docExts } = indexExtensions(dir)
58
59
  const gitRun = (args) => new Promise((resolve, reject) => {
@@ -95,7 +96,8 @@ async function gitSyncDir(memory, dir, { onProgress } = {}) {
95
96
  const abs = join(dir, rel)
96
97
  const ext = extensionOf(rel)
97
98
 
98
- if (isSkippedRelPath(rel) || isExcludedRelPath(rel, decl, dir)) continue
99
+ // §6.14 准入三族同判(面④ 跳过段 ∥ 面①∪面⑥ 排除谓词 ∥ 面⑦ 声明范围):范围外 = 不收录
100
+ if (isSkippedRelPath(rel) || isExcludedRelPath(rel, decl, dir) || !isInDeclaredScope(rel, scope, dir)) continue
99
101
 
100
102
  if (!codeExts.has(ext) && !docExts.has(ext)) { skipped++; continue }
101
103
 
@@ -210,8 +212,8 @@ async function codeSyncDir(memory, dir, { onProgress, yieldFn = yieldTick, nowFn
210
212
  }
211
213
  }
212
214
 
213
- // §6.14 B6 ∕ M3:收尾 stale 循环(同款让出 + 面① 收尾保护位)——机制单源 = `sync-tail.mjs`
214
- removed = await sweepStaleRows(memory, { table: "code_chunks", origin, indexed, seen, decl, base: dir, yieldFn, nowFn, yieldMs })
215
+ // §6.14 B6 ∕ M3:收尾 stale 循环(同款让出 + 收尾保护位:面①∪面⑥ 排除 ∪ 面⑦ 范围)——机制单源 = `sync-tail.mjs`
216
+ removed = await sweepStaleRows(memory, { table: "code_chunks", origin, indexed, seen, decl, base: dir, scope: declaredIndexScope(dir), yieldFn, nowFn, yieldMs })
215
217
 
216
218
  onProgress?.({ phase: "done", total: files.length, updated, removed, skipped, failed, overSizeSkipped, budgetSkipped: budgetSkipped.length })
217
219
  // §6.14 B7 维护口:模型键失配的失效**执行**(读面只判定降级——执行住同步尾;覆盖 /reindex ∕ 桌面 ∕ VSC 构建)
@@ -248,6 +250,7 @@ export async function reindexFile(memory, cwd, absPath) {
248
250
  if (rel === ".." || rel.startsWith("../")) return
249
251
  if (isSkippedRelPath(rel)) return
250
252
  if (isExcludedRelPath(rel, loadProjectDeclaration(cwd), cwd)) return // §6.14 面① 第三起效点(单文件缝零写)
253
+ if (!isInDeclaredScope(rel, declaredIndexScope(cwd), cwd)) return // §6.14 面⑦ 同址第三起效点(范围外单文件零写)
251
254
  // Declared extensions count for the single-file path too (union with built-ins).
252
255
  const { code: codeExts, doc: docExts } = indexExtensions(cwd)
253
256