Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 20 additions & 10 deletions apps/web/installedLibrary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ import { WebStorageError } from './storage';
import { installedLibraryLabels } from './installedLibraryLabels';
import { matchesInstalledLibraryModuleAlias } from './installedLibrarySearch';
import { installedLibraryDeclarations } from './installedLibraryDefinitions';
import { installedLibraryInterfaceSearchText, matchesInstalledLibrarySearchText } from './installedLibraryInterfaceSearch';
import { installedLibraryInterfaceSearchText } from './installedLibraryInterfaceSearch';
import { frozenLibraryQuery, matchFrozenLibraryEntry } from '../../src/math/frozenLibraryQuery';
import { installedLibraryMathematics } from './installedLibraryMathematics';
import { installedLibrarySearchData } from './installedLibrarySearchData';
import { installedLibrarySearchData } from '../../src/math/frozenLibrarySearchData';
import type { InstalledLibraryDetail, InstalledLibraryDirectory, InstalledLibraryInfo, InstalledLibraryModule,
InstalledLibraryModuleSummary, InstalledLibrarySource } from './installedLibraryTypes';

Expand Down Expand Up @@ -33,24 +34,33 @@ export function installedLibraryDirectory(options: {
const catalog = installedCatalog(), all = catalog.moduleFiles.map(file => moduleInfo(catalog, file));
const tokens = (options.q ?? '').toLocaleLowerCase().trim().split(/\s+/u).filter(Boolean);
const matches = (text: string) => tokens.every(token => text.toLocaleLowerCase().includes(token));
const matchInterface = frozenLibraryQuery(options.q ?? '');
const interfaceMatches = new Map<string, InstalledLibraryModuleSummary['matchingInterfaces']>();
const rank = new Map<string, { exactInterface: boolean; moduleAlias: boolean }>();
const filtered = all.filter(module => {
const labels = installedLibraryLabels(module.name);
if (options.area && !module.area.toLocaleLowerCase().includes(options.area.toLocaleLowerCase())
|| options.environment && options.environment !== catalog.environment) return false;
const indexed = installedLibrarySearchData.catalogDigest === catalog.identity.catalogDigest
&& installedLibrarySearchData.modules[module.file]?.sha256 === module.sha256 ? installedLibrarySearchData.modules[module.file].entries : undefined;
const matching = tokens.length ? module.entries.flatMap(entry => {
const value = indexed?.[entry.name] ?? { text: installedLibraryInterfaceSearchText(entry, module.import),
summary: installedLibraryMathematics(entry, module.import).summary };
return matchesInstalledLibrarySearchText(value.text, options.q ?? '') ? [{ name: entry.name, summary: value.summary }] : [];
const matchesWithScores = tokens.length ? module.entries.flatMap(entry => {
const value = indexed?.[entry.name];
const score = value ? matchFrozenLibraryEntry(matchInterface, value, entry.name)
: matchInterface(installedLibraryInterfaceSearchText(entry, module.import), entry.name);
return score ? [{ name: entry.name, score, summary: value?.summary ?? installedLibraryMathematics(entry, module.import).summary }] : [];
}) : [];
interfaceMatches.set(module.file, matching);
return matching.length > 0 || matchesInstalledLibraryModuleAlias(module.name, options.q ?? '')
const exactInterface = matchesWithScores.some(hit => hit.score === 3);
const moduleAlias = matchesInstalledLibraryModuleAlias(module.name, options.q ?? '');
rank.set(module.file, { exactInterface, moduleAlias });
interfaceMatches.set(module.file, matchesWithScores.sort((a, b) => Number(b.score === 3) - Number(a.score === 3))
.map(({ score: _score, ...entry }) => entry));
return matchesWithScores.length > 0 || moduleAlias
|| matches([module.name, module.file, labels?.zh.title, labels?.zh.description, labels?.en.title, labels?.en.description,
...module.declarations, ...module.entries.map(entry => `${entry.name} ${entry.type} ${entry.description}`)].filter(Boolean).join('\n'));
}).sort((left, right) => Number(matchesInstalledLibraryModuleAlias(right.name, options.q ?? ''))
- Number(matchesInstalledLibraryModuleAlias(left.name, options.q ?? '')));
}).sort((left, right) => {
const a = rank.get(left.file)!, b = rank.get(right.file)!;
return Number(b.exactInterface) - Number(a.exactInterface) || Number(b.moduleAlias) - Number(a.moduleAlias);
});
const offset = options.offset ?? 0, limit = options.limit ?? 24;
const items: InstalledLibraryModuleSummary[] = filtered.slice(offset, offset + limit).map(module => {
const { entries, declarations, ...metadata } = module;
Expand Down
7 changes: 2 additions & 5 deletions apps/web/installedLibraryInterfaceSearch.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { frozenLibraryQuery } from '../../src/math/frozenLibraryQuery';
import type { InstalledLibraryDeclarationContext, InstalledLibraryDefinition, InstalledLibraryEntry } from './installedLibraryTypes';
import { installedLibraryMathematics } from './installedLibraryMathematics';

Expand All @@ -11,13 +12,9 @@ export function installedLibraryInterfaceSearchText(entry: InstalledLibraryEntry
condition.meaning.en, condition.expression])].join('\n').toLocaleLowerCase();
}

export function matchesInstalledLibrarySearchText(searchable: string, query: string): boolean {
return query.trim().toLocaleLowerCase().split(/\s+/u).filter(Boolean).every(token => searchable.includes(token));
}

/** Search the same frozen interface and mathematical explanation that the reader can see. */
export function matchesInstalledLibraryInterface(entry: InstalledLibraryEntry, moduleImport: string, query: string,
definition?: InstalledLibraryDefinition, sourceContext?: InstalledLibraryDeclarationContext): boolean {
if (!query.trim()) return true;
return matchesInstalledLibrarySearchText(installedLibraryInterfaceSearchText(entry, moduleImport, definition, sourceContext), query);
return frozenLibraryQuery(query)(installedLibraryInterfaceSearchText(entry, moduleImport, definition, sourceContext), entry.name) > 0;
}
3 changes: 3 additions & 0 deletions apps/web/installedLibraryMathematics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ const text = (zh: string, en: string): Text => ({ zh, en });

// These statements describe the exact named declarations, not whole theorem families.
const explanations: Record<string, Text> = {
'TheoremOS.BooleanCube.parseval': text('布尔立方体上的帕塞瓦尔恒等式:傅里叶系数的平方和等于函数平方的平均值。', 'Parseval’s identity on the Boolean cube: the sum of squares of Fourier coefficients equals the mean square of the function.'),
'TheoremOS.BooleanCube.plancherel': text('布尔立方体上的普朗歇尔恒等式:两个函数的乘积的平均值等于对应傅里叶系数的乘积之和。', 'Plancherel’s identity on the Boolean cube: the average of the product of two functions equals the sum of the products of their Fourier coefficients.'),
'TheoremOS.Analysis.integral_norm_sq_trigpoly': text('三角多项式的帕塞瓦尔恒等式:模的平方的积分等于系数模的平方之和。', 'Parseval’s identity for finite trigonometric polynomials: the integral of the squared modulus equals the sum of the squared moduli of the coefficients.'),
'TheoremOS.Algebra.FiniteSums.sum_forward_differences': text('望远镜求和:前 n 个相邻差之和等于第 n 项减去首项。', 'Telescoping: the first n successive differences sum to the nth term minus the initial term.'),
'TheoremOS.Algebra.FiniteSums.sum_shifted_differences': text('从给定下标开始的相邻差之和,由区间两端的函数值确定。', 'A sum of successive differences starting at a given index is determined by its endpoint values.'),
'TheoremOS.Algebra.FiniteSums.geometric_sum': text('公比不等于 1 时,给出前 n 项等比和的闭式。', 'For a ratio other than 1, gives a closed formula for the first n powers.'),
Expand Down
5 changes: 0 additions & 5 deletions apps/web/installedLibraryTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,6 @@ export type InstalledLibraryModuleSummary = Omit<InstalledLibraryModule, 'entrie
matchingInterfaces: { name: string; summary: { zh: string; en: string } }[];
matchingInterfaceCount: number;
};
/** Generated from one pinned release; contains searchable display text, never theorem proof bodies. */
export type InstalledLibrarySearchIndex = {
catalogDigest: string;
modules: Record<string, { sha256: string; entries: Record<string, { summary: { zh: string; en: string }; text: string }> }>;
};
export type InstalledLibraryDirectory = {
library: InstalledLibraryInfo;
items: InstalledLibraryModuleSummary[];
Expand Down
2 changes: 2 additions & 0 deletions docs/library-catalog.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ theorem-os library get --worktree WORKTREE --name '完整限定名' --max-bytes
theorem-os library request --worktree WORKTREE --name '完整限定名' --reason '具体用途及待关闭前提'
```

默认发行版的 Web 库目录和显式 `library search` 共用与目录摘要、模块摘要绑定的双语接口说明。输入数学名称或中英文命题描述时,可通过说明、源码注释和 Lean 类型召回候选。名称精确命中优先,候选是否适用由当前 Lean 环境检查。自定义目录可按自己的声明名和类型检索。

搜索结果以 `installed-frozen` / `not-installed` 标明当前安装状态。`get` 按需读取对应源码对象,返回完整模块的有界分页;用 `source.nextOffset` 继续读取,直到 `source.complete`,以保留 section 参数、实例和假设。每页完整 JSON 的 UTF-8 大小受 `--max-bytes` 限制。只允许定位公开声明,类型或结构也可按完整限定名定位;搜索不需要打开源码对象。

Web 的 Agent 活动把 `search`、`get`、`request` 的工具输出显示为库版本、候选声明、安装状态、源码分页和请求状态,复用现有活动存储。源码正文与宿主路径不进入卡片摘要;排队请求不显示为已安装或已引用。源码页的 `complete` 只说明该页已到模块末尾,不表示此前所有页都已读取。
Expand Down
11 changes: 10 additions & 1 deletion docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -387,11 +387,20 @@ bun run math bootstrap-lean-eval --help
| `compare` | 读取和检查已保存的对照实验报告 |
| `check-lean` | 获取局部诊断、预检闭合类型或具体应用表达式 |
| `continuation` | 按摘要及附件 ID 分页读取冻结的续跑材料 |
| `search-lean` | 检索已验证的本地 Lean 包声明 |
| `search-lean` | 用 Lean 声明名、常见定理别名、中英文数学描述或 Lean 目标检索已验证的本地 Lean 包声明 |
| `knowledge` | [导入、搜索和读取历史已检查定理](theorem-knowledge.md);显式 enrich 补采类型与引用,consumers 回读历史应用链 |
| `freeze-retrieval` | 冻结允许检索的本地源码语料 |
| `summarize` | 汇总保存的实验记录 |

`search-lean --goal` 会匹配方向相反的等式和等价命题。结果中的 `"application": "symm"`
表示可尝试用 `exact (定理名 实参).symm`,具体实参和前提由 Lean 检查。

`search-lean` 也会检索与当前 Mathlib 提交和源文件哈希相符的 `@[to_additive]` 生成定理。
这类结果的 `generation.type` 是 Lean 导出的定理类型,`generation.from` 和 `sourceLine` 指向生成它的原声明。
更新 Mathlib 时,用该版本的 Lean 和已编译依赖运行 [导出程序](../scripts/mathematics/exportMathlibAdditive.lean),再用
`bun scripts/mathematics/packMathlibAdditive.ts WORKSPACE mathlib-additive-types.json src/math/mathlibAdditiveData.json`
重新生成索引。索引数据来自 [Mathlib,Apache 2.0](../third_party/Mathlib-APACHE-2.0.txt)。

例如,检查指定 Lean 文件并设置 90 秒超时:

```bash
Expand Down
7 changes: 4 additions & 3 deletions scripts/generate-web-library-search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import { fileURLToPath } from 'node:url';
import { installedLibraryDeclarations } from '../apps/web/installedLibraryDefinitions';
import { installedLibraryInterfaceSearchText } from '../apps/web/installedLibraryInterfaceSearch';
import { installedLibraryMathematics } from '../apps/web/installedLibraryMathematics';
import type { InstalledLibraryEntry, InstalledLibrarySearchIndex } from '../apps/web/installedLibraryTypes';
import type { InstalledLibraryEntry } from '../apps/web/installedLibraryTypes';
import type { InstalledLibrarySearchIndex } from '../src/math/frozenLibrarySearchTypes';
import { readLibraryCatalog } from '../src/solver/libraryCatalog';

const catalog = readLibraryCatalog(fileURLToPath(new URL('../resources/theorem-os-library/release/catalog.json', import.meta.url)));
Expand All @@ -19,8 +20,8 @@ for (const file of catalog.moduleFiles) {
text: installedLibraryInterfaceSearchText(entry, moduleImport, definitions[entry.name], contexts[entry.name]),
}])) };
}
const output = fileURLToPath(new URL('../apps/web/installedLibrarySearchData.ts', import.meta.url));
const output = fileURLToPath(new URL('../src/math/frozenLibrarySearchData.ts', import.meta.url));
fs.writeFileSync(output, '// Generated by bun scripts/generate-web-library-search.ts. Do not edit.\n'
+ 'import type { InstalledLibrarySearchIndex } from \'./installedLibraryTypes\';\n\n'
+ 'import type { InstalledLibrarySearchIndex } from \'./frozenLibrarySearchTypes\';\n\n'
+ `export const installedLibrarySearchData: InstalledLibrarySearchIndex = ${JSON.stringify(index, null, 2)};\n`);
console.log(`Generated search metadata for ${catalog.moduleCount} modules / ${catalog.declarationCount} interfaces (${index.catalogDigest}).`);
Loading
Loading