dsh-ai-wiki 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +124 -2
- package/bin/aiwiki.js +92 -0
- package/cordis.patch.yml +14 -0
- package/docs/DESIGN.md +74 -0
- package/docs/RELEASE.md +51 -0
- package/lib/config.mjs +193 -0
- package/lib/errors.mjs +24 -0
- package/lib/index.js +30 -0
- package/lib/index.mjs +576 -0
- package/lib/lint.mjs +216 -0
- package/lib/schema.mjs +99 -0
- package/lib/tokenize.mjs +82 -0
- package/lib/tools.mjs +675 -0
- package/lib/vault.mjs +364 -0
- package/package.json +62 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Iosif Pravets
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,125 @@
|
|
|
1
|
-
#
|
|
1
|
+
# dsh-ai-wiki
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://github.com/pravets/dsh-ai-wiki/actions/workflows/ci.yml)
|
|
4
|
+
[](https://www.npmjs.com/package/dsh-ai-wiki)
|
|
5
|
+
|
|
6
|
+
Плагин DeepSeek Harness для чтения личной вики, собранной по шаблону [ai-wiki-template](https://github.com/pravets/ai-wiki-template): зоны, ACL-маркеры, frontmatter-контракт, wiki-ссылки и BM25-поиск. Плагин только читает вики; индекс живёт в кэше DSH.
|
|
7
|
+
|
|
8
|
+
## Зачем свой плагин
|
|
9
|
+
|
|
10
|
+
Готовые плагины решают соседние задачи, но не этот контракт:
|
|
11
|
+
|
|
12
|
+
- @pananfly/dsh-llm-wiki — OKF v0.2 со своей структурой .llm-wiki/ и своим индексом; зоны, .llm-* и BM25-веса этого шаблона не поддерживает.
|
|
13
|
+
- dsh-wiki-notes — сильный универсальный read-only шлюз к Markdown, но поиск keyword/recall, а не BM25-контракт vault; нет ACL, зон и raw-корпуса.
|
|
14
|
+
- dsh-wiki-rag — эмбеддинги, а не BM25.
|
|
15
|
+
- dsh-AIkb и dsh-knowledge-graph — про ingest/граф, а не про чтение этой вики.
|
|
16
|
+
|
|
17
|
+
Свой плагин небольшой (весь vault — около 5 МБ), зато повторяет контракт шаблона и не требует Python.
|
|
18
|
+
|
|
19
|
+
## Что даёт агенту
|
|
20
|
+
|
|
21
|
+
Шесть инструментов с префиксом aiwiki_, чтобы не пересекаться с другими wiki-плагинами:
|
|
22
|
+
|
|
23
|
+
| Инструмент | Назначение |
|
|
24
|
+
|---|---|
|
|
25
|
+
| aiwiki_search | BM25 по SQLite FTS5: веса name 5, tags/aliases 3, headings 2, kw 2, body 1; корпуса wiki/chats/raw; similarTo. |
|
|
26
|
+
| aiwiki_read | Frontmatter, тело или секция/окно строк, ACL-права, исходящие ссылки и бэклинки. |
|
|
27
|
+
| aiwiki_list | Каталог и агрегаты по зоне, типу, тегу, статусу и дате. |
|
|
28
|
+
| aiwiki_links | Исходящие ссылки, бэклинки, неразрешённые и неоднозначные wiki-ссылки. |
|
|
29
|
+
| aiwiki_status | Вики, зоны и ACL, счётчики, свежесть и размер индекса, generated index/hub, последние записи log.md, предупреждения. |
|
|
30
|
+
| aiwiki_lint | Read-only порт lint_frontmatter.py с поддержкой lint-baseline.json. |
|
|
31
|
+
|
|
32
|
+
Плюс короткая секция системного промпта и guard, который отклоняет write/edit по путям вики.
|
|
33
|
+
|
|
34
|
+
## Требования
|
|
35
|
+
|
|
36
|
+
- Node.js 22.13+ (нужен node:sqlite с FTS5); рекомендуется Node 24.
|
|
37
|
+
- DSH 0.2.2-rc.5.
|
|
38
|
+
- Vault по шаблону: AGENTS.md, каталоги зон и маркеры .llm-ro/.llm-append/.llm-rw.
|
|
39
|
+
|
|
40
|
+
Python и native-модули не нужны.
|
|
41
|
+
|
|
42
|
+
## Установка
|
|
43
|
+
|
|
44
|
+
Из каталога плагина:
|
|
45
|
+
|
|
46
|
+
dsh plugin --profile web add C:\git\dsh-ai-wiki
|
|
47
|
+
|
|
48
|
+
После публикации:
|
|
49
|
+
|
|
50
|
+
dsh plugin --profile web add dsh-ai-wiki
|
|
51
|
+
|
|
52
|
+
Откройте новую сессию. Конфиг перечитывается на каждом вызове, перезапуск DSH для добавления вики не нужен.
|
|
53
|
+
|
|
54
|
+
## Настройка
|
|
55
|
+
|
|
56
|
+
Создайте %USERPROFILE%\.dsh\dsh-wiki.json:
|
|
57
|
+
|
|
58
|
+
{
|
|
59
|
+
"vaults": [
|
|
60
|
+
{ "name": "vault", "path": "C:\\git\\vault", "includeRaw": true }
|
|
61
|
+
],
|
|
62
|
+
"indexDir": "~/.dsh/cache/dsh-ai-wiki",
|
|
63
|
+
"autoIndex": true,
|
|
64
|
+
"promptSection": true,
|
|
65
|
+
"guardWrites": true
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
Можно проще: "vaults": ["C:\\git\\vault"]. Проектный .dsh-wiki.json в каталоге сессии перекрывает пользовательский; enabled:false отключает отдельную вики. Переменные DSH_WIKI_ROOTS (пути через ;) и DSH_WIKI_INDEX_DIR тоже работают.
|
|
69
|
+
|
|
70
|
+
Если сессия открыта внутри вики (AGENTS.md + каталоги зон или .llm-*), плагин найдёт её сам.
|
|
71
|
+
|
|
72
|
+
## Примеры
|
|
73
|
+
|
|
74
|
+
aiwiki_search query="индексы postgres" limit=5
|
|
75
|
+
aiwiki_search query="контекст агента" type=concept
|
|
76
|
+
aiwiki_search similarTo="10-wiki/1c-postgres-indexes"
|
|
77
|
+
aiwiki_read path="10-wiki/1c-postgres-indexes" section="Индексы"
|
|
78
|
+
aiwiki_read path="01-raw/2026-10-08-1c-postgres-indexes-transcript" offset=1 limit=80
|
|
79
|
+
aiwiki_list type=repo status=active groupBy=role
|
|
80
|
+
aiwiki_links path="10-wiki/1c-postgres-indexes"
|
|
81
|
+
aiwiki_status rebuild=true
|
|
82
|
+
aiwiki_lint limit=20
|
|
83
|
+
|
|
84
|
+
## Как устроен поиск
|
|
85
|
+
|
|
86
|
+
Индекс — отдельная SQLite-база в indexDir, имя из хэша пути вики. Первый поиск собирает её, дальше обновляются только изменённые страницы по mtime и size. Полная пересборка — aiwiki_status rebuild=true.
|
|
87
|
+
|
|
88
|
+
Токенизация повторяет 90-meta/scripts/wiki_search.py: lower-case, [а-яёa-z0-9]+, Snowball Russian для кириллицы, латиница и цифры без стемминга. Запрос — "term"* с AND, затем OR. raw по умолчанию исключён; corpus="raw" или "all" включает транскрипты. similarTo берёт до 40 уникальных слов тела длиннее 4 символов.
|
|
89
|
+
|
|
90
|
+
Плагин не использует .wiki-index/search.db и не требует Python/snowballstemmer. Ранжирование сознательно близко к wiki_search.py; отличия: block-списки tags/aliases/kw разбираются YAML-парсером, путь БД другой, кириллические имена нормализуются в NFC.
|
|
91
|
+
|
|
92
|
+
## Права и read-only
|
|
93
|
+
|
|
94
|
+
Контракт вики: нет .llm-* — read-only; корень read-only; frontmatter llm: ro перекрывает rw зоны. aiwiki_read показывает permissions, guard отклоняет write/edit/str_replace_editor/apply_patch для путей внутри настроенной вики. Guard не разбирает произвольные shell-команды; для сессий внутри вики действуют sandbox и правила AGENTS.md.
|
|
95
|
+
|
|
96
|
+
Плагин пишет только в indexDir. В вики не создаётся даже .wiki-index.
|
|
97
|
+
|
|
98
|
+
## Диагностика
|
|
99
|
+
|
|
100
|
+
- «VAULT_NOT_CONFIGURED» — нет dsh-wiki.json и сессия вне вики; добавьте путь.
|
|
101
|
+
- «INDEX_UNAVAILABLE» — Node старше 22.13 или сборка без FTS5; проверьте node -v и node -e "require('node:sqlite')".
|
|
102
|
+
- «INDEX_STALE» — autoIndex=false и индекса нет; вызовите aiwiki_status rebuild=true.
|
|
103
|
+
- Пустой поиск — проверьте corpus (raw включается явно) и фильтры; для точной строки используйте обычный grep.
|
|
104
|
+
- Индекс устарел после ручных правок — aiwiki_search обновит его сам; при сомнении aiwiki_status.
|
|
105
|
+
- Кириллические имена и ё: стеммер приводит ё к е (Snowball), это ожидаемо.
|
|
106
|
+
|
|
107
|
+
## Разработка
|
|
108
|
+
|
|
109
|
+
npm test
|
|
110
|
+
DSH_WIKI_TEST_VAULT=C:\git\vault npm test
|
|
111
|
+
node tools/bench.mjs --vault C:\git\vault
|
|
112
|
+
node tools/compare-python.mjs --vault C:\git\vault # если есть Python+snowballstemmer и собран .wiki-index
|
|
113
|
+
|
|
114
|
+
Тесты — node:test, временные вики в tests/helpers.mjs. Реальный vault — opt-in.
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
## CI и релиз
|
|
118
|
+
|
|
119
|
+
CI на GitHub Actions собирает пакет на каждый push и pull request: тесты, проверка синтаксиса, tarball и артефакт сборки. Публикация в npm идёт отдельным workflow по тегу v*; первый 0.1.0 требует one-time bootstrap, потому что trusted publishing настраивается только для уже существующего пакета. Подробности — в docs/RELEASE.md.
|
|
120
|
+
|
|
121
|
+
Репозиторий: https://github.com/pravets/dsh-ai-wiki. Рабочая ветка — master.
|
|
122
|
+
|
|
123
|
+
## Ограничения
|
|
124
|
+
|
|
125
|
+
Первая версия только читает. Запись и ingest, правка index.md/log.md, UI-панель, слэш-команды и ambient recall не входят. ACL-aware append/create можно добавить следующим этапом.
|
package/bin/aiwiki.js
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { WikiIndex } from '../lib/index.mjs';
|
|
6
|
+
import { lintVault } from '../lib/lint.mjs';
|
|
7
|
+
import { resolvePage, parseFrontmatter, permissionsFor } from '../lib/vault.mjs';
|
|
8
|
+
|
|
9
|
+
function option(name, fallback) {
|
|
10
|
+
const index = process.argv.indexOf(name);
|
|
11
|
+
if (index < 0) return fallback;
|
|
12
|
+
return process.argv[index + 1];
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const vaultPath = option('--vault', process.env.DSH_WIKI_VAULT || process.env.DSH_WIKI_TEST_VAULT || 'C:/git/vault');
|
|
16
|
+
const indexDir = option('--index', path.join(os.homedir(), '.dsh', 'cache', 'dsh-ai-wiki'));
|
|
17
|
+
const rawArgs = process.argv.slice(2);
|
|
18
|
+
const args = [];
|
|
19
|
+
for (let index = 0; index < rawArgs.length; index += 1) {
|
|
20
|
+
const item = rawArgs[index];
|
|
21
|
+
if (item === '--vault' || item === '--index' || item === '--limit' || item === '--corpus') {
|
|
22
|
+
index += 1;
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
if (item === '--rebuild') continue;
|
|
26
|
+
args.push(item);
|
|
27
|
+
}
|
|
28
|
+
const command = args[0] || 'help';
|
|
29
|
+
const vault = { name: path.basename(vaultPath), path: vaultPath, includeRaw: true, exists: true };
|
|
30
|
+
const config = { vaults: [vault], indexDir, autoIndex: true };
|
|
31
|
+
|
|
32
|
+
async function main() {
|
|
33
|
+
if (command === 'help') {
|
|
34
|
+
console.log('aiwiki search <query> [--vault PATH] [--index DIR] [--corpus wiki|chats|raw|all] [--limit N]');
|
|
35
|
+
console.log('aiwiki read <page> [--vault PATH]');
|
|
36
|
+
console.log('aiwiki status [--vault PATH] [--index DIR] [--rebuild]');
|
|
37
|
+
console.log('aiwiki lint [--vault PATH] [--limit N]');
|
|
38
|
+
return 0;
|
|
39
|
+
}
|
|
40
|
+
if (command === 'search') {
|
|
41
|
+
const query = args.slice(1).join(' ').trim();
|
|
42
|
+
if (query === '') throw new Error('search: query is required');
|
|
43
|
+
const index = new WikiIndex(vault, config);
|
|
44
|
+
try {
|
|
45
|
+
await index.ensureFresh({ full: process.argv.includes('--rebuild') });
|
|
46
|
+
const limit = Number(option('--limit', '8')) || 8;
|
|
47
|
+
const result = index.search({ query, corpus: option('--corpus', 'wiki'), limit });
|
|
48
|
+
for (const row of result.rows) console.log(row.score.toFixed(2) + ' ' + row.path + ' — ' + row.name + (row.excerpt ? '\n ' + row.excerpt : ''));
|
|
49
|
+
if (result.rows.length === 0) console.log('no matches');
|
|
50
|
+
return 0;
|
|
51
|
+
} finally {
|
|
52
|
+
index.close();
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (command === 'read') {
|
|
56
|
+
const target = args.slice(1).join(' ').trim();
|
|
57
|
+
if (target === '') throw new Error('read: page is required');
|
|
58
|
+
const page = resolvePage(vaultPath, target);
|
|
59
|
+
const text = readFileSync(page.abs, 'utf8');
|
|
60
|
+
const fm = parseFrontmatter(text);
|
|
61
|
+
const meta = fm.data;
|
|
62
|
+
const permissions = permissionsFor(vaultPath, page.rel, meta);
|
|
63
|
+
console.log(page.rel + ' — ' + (meta.name || page.rel));
|
|
64
|
+
console.log('permissions: ' + permissions.write + ' (' + permissions.reason + ')');
|
|
65
|
+
console.log('');
|
|
66
|
+
console.log(fm.body.slice(0, 8000));
|
|
67
|
+
return 0;
|
|
68
|
+
}
|
|
69
|
+
if (command === 'status') {
|
|
70
|
+
const index = new WikiIndex(vault, config);
|
|
71
|
+
try {
|
|
72
|
+
if (process.argv.includes('--rebuild')) await index.ensureFresh({ full: true });
|
|
73
|
+
const stats = index.stats();
|
|
74
|
+
console.log(JSON.stringify(stats, null, 2));
|
|
75
|
+
return 0;
|
|
76
|
+
} finally {
|
|
77
|
+
index.close();
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
if (command === 'lint') {
|
|
81
|
+
const result = lintVault(vault, { limit: Number(option('--limit', '50')) || 50 });
|
|
82
|
+
console.log('pages: ' + result.totalPages + ' · blocking: ' + result.blocking + ' · new: ' + result.newSinceBaseline.length);
|
|
83
|
+
for (const item of result.violations) console.log(item.path + ': ' + item.codes.join(', '));
|
|
84
|
+
return 0;
|
|
85
|
+
}
|
|
86
|
+
throw new Error('unknown command: ' + command);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
main().then((code) => process.exit(code)).catch((error) => {
|
|
90
|
+
console.error('aiwiki: ' + (error && error.message ? error.message : String(error)));
|
|
91
|
+
process.exit(1);
|
|
92
|
+
});
|
package/cordis.patch.yml
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# dsh-ai-wiki: read-only BM25 gateway to an ai-wiki-template vault.
|
|
2
|
+
#
|
|
3
|
+
# The plugin is installed once in the profile and reads the vault configured in
|
|
4
|
+
# $DSH_HOME/dsh-wiki.json or <session>/.dsh-wiki.json. Vault paths may also come
|
|
5
|
+
# from DSH_WIKI_ROOTS (semicolon-separated) — useful for a first run.
|
|
6
|
+
#
|
|
7
|
+
# Without a configured vault the aiwiki_* tools are hidden and the prompt
|
|
8
|
+
# section is empty, so an unrelated project pays nothing for the plugin.
|
|
9
|
+
- insert:
|
|
10
|
+
- id: dsh-ai-wiki
|
|
11
|
+
name: 'dsh-ai-wiki'
|
|
12
|
+
config:
|
|
13
|
+
vaults: !!js 'process.env.DSH_WIKI_ROOTS ? process.env.DSH_WIKI_ROOTS.split(";").map((p) => p.trim()).filter(Boolean).map((p) => ({ path: p })) : []'
|
|
14
|
+
indexDir: !!js 'process.env.DSH_WIKI_INDEX_DIR ?? undefined'
|
package/docs/DESIGN.md
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# Design — dsh-ai-wiki
|
|
2
|
+
|
|
3
|
+
## Goal
|
|
4
|
+
|
|
5
|
+
Give a DSH agent in any project read access to a personal ai-wiki vault with the vault's own semantics: zones and ACL markers, frontmatter, wiki links, BM25, raw transcripts and lint. The vault must remain untouched; only the index cache is written.
|
|
6
|
+
|
|
7
|
+
## Non-goals (v1)
|
|
8
|
+
|
|
9
|
+
Writing, ingest, index.md/log.md regeneration, sidebar UI, slash commands, ambient recall. These are deliberate extensions, not missing plumbing.
|
|
10
|
+
|
|
11
|
+
## Data flow
|
|
12
|
+
|
|
13
|
+
Markdown files
|
|
14
|
+
-> walkMarkdown() with wiki_search.py skip rules
|
|
15
|
+
-> parseFrontmatter() (YAML, fallback line parser)
|
|
16
|
+
-> pageMeta() + normalizeList()
|
|
17
|
+
-> tokenize() (lowercase, [а-яёa-z0-9]+, Snowball Russian for Cyrillic)
|
|
18
|
+
-> SQLite FTS5 (docs, search, doc_tags, links, meta)
|
|
19
|
+
-> BM25 / filters / links / lint
|
|
20
|
+
-> canonical JSON -> tool render
|
|
21
|
+
|
|
22
|
+
The index is external to the vault: indexDir/<sha256(vault path)[0:16]>.db. The vault is read with node:fs; the plugin's own tools never write there.
|
|
23
|
+
|
|
24
|
+
## Modules
|
|
25
|
+
|
|
26
|
+
- lib/index.js — plugin entry: registration with when, prompt section, write guard, disposal.
|
|
27
|
+
- lib/config.mjs — layers: cordis config -> env -> $DSH_HOME/dsh-wiki.json -> <cwd>/.dsh-wiki.json; auto-detection of a vault from cwd.
|
|
28
|
+
- lib/vault.mjs — walking, path containment, ACL markers, frontmatter, wiki links and resolution.
|
|
29
|
+
- lib/schema.mjs — constants mirrored from lint_frontmatter.py (zones, types, tags, sizes, skips).
|
|
30
|
+
- lib/tokenize.mjs — tokenizer, Snowball stemmer, FTS query builder, body plain text and excerpt.
|
|
31
|
+
- lib/index.mjs — SQLite FTS5 schema, incremental build, BM25 search, similar, list, links, stats.
|
|
32
|
+
- lib/lint.mjs — read-only lint and baseline filtering.
|
|
33
|
+
- lib/tools.mjs — six tool definitions, runtime (config/index cache), renderers, prompt and guard helpers.
|
|
34
|
+
|
|
35
|
+
## Index schema
|
|
36
|
+
|
|
37
|
+
docs(id, path, corpus, zone, name, type, status, created, updated, tags, aliases, mtime, size, excerpt, frontmatter)
|
|
38
|
+
doc_tags(doc_id, tag)
|
|
39
|
+
search FTS5(doc_id UNINDEXED, name, tags, headings, kw, body)
|
|
40
|
+
links(from_id, target, resolved_path, alias, heading, source, candidates)
|
|
41
|
+
meta(key, value)
|
|
42
|
+
|
|
43
|
+
BM25 uses bm25(search, 0, 5, 3, 2, 2, 1), matching the vault weights. The search path first tries AND over quoted prefix terms, then OR. Raw is excluded by default and enabled explicitly.
|
|
44
|
+
|
|
45
|
+
Incremental refresh compares path+mtime+size. When any page changes, all links are re-resolved: a new target can turn an unresolved link into a resolved one, and a deleted target must disappear from backlinks. This costs a full read of the vault on change but keeps the graph correct; the real vault (547 indexed pages, 5.1 MB) builds in under 2 seconds.
|
|
46
|
+
|
|
47
|
+
## Links
|
|
48
|
+
|
|
49
|
+
Body links: [[target]], [[target|alias]], [[target#heading]], ![[...]]; fenced code is skipped. Frontmatter refs work_ref, person and project are typed edges. Resolution order: exact path -> relative path from the source directory -> unique basename -> unique name/alias -> ambiguous (candidates returned) -> unresolved. This approximates Obsidian's shortest-path rule and never silently picks among duplicates.
|
|
50
|
+
|
|
51
|
+
## ACL
|
|
52
|
+
|
|
53
|
+
Nearest .llm-ro/.llm-append/.llm-rw from the page directory up to the vault root wins. No marker means read-only; the root is read-only. Frontmatter llm: ro overrides a writable zone; llm: rw does not raise a read-only zone. Root index.md and log.md are the contract's exception (full), but the plugin still never writes. Permissions are reported to the model; a monotonic tool guard denies write/edit/str_replace_editor/apply_patch for vault paths.
|
|
54
|
+
|
|
55
|
+
The guard cannot interpret shell commands. Sessions inside the vault still rely on the DSH sandbox and the vault's AGENTS.md.
|
|
56
|
+
|
|
57
|
+
## Configuration
|
|
58
|
+
|
|
59
|
+
Vaults are user-level by default (one personal vault used from many projects), with a project-level override. Tools are registered with when: configured vaults exist, so an unrelated session pays no schema cost. The prompt section is a short static text (no dates/counters) to preserve prompt caching.
|
|
60
|
+
|
|
61
|
+
## Failure model
|
|
62
|
+
|
|
63
|
+
Expected failures are canonical values: { ok: false, error: { code, message, hint } }. Codes include VAULT_NOT_CONFIGURED, VAULT_NOT_FOUND, VAULT_NOT_A_WIKI, INDEX_UNAVAILABLE, INDEX_STALE, INDEX_BUILD_FAILED, INVALID_QUERY, INVALID_CORPUS, RAW_DISABLED, PAGE_NOT_FOUND, AMBIGUOUS_PAGE, PATH_OUTSIDE_VAULT, SECTION_NOT_FOUND. Cancellation is cooperative (exec.signal); a build aborts and rolls back its transaction.
|
|
64
|
+
|
|
65
|
+
## Testing
|
|
66
|
+
|
|
67
|
+
Fixtures build a temporary vault with all zones, markers, inline and block frontmatter, aliases, raw, unresolved links and broken YAML. Unit tests cover tokenizer, frontmatter, ACL, link resolution, index build and search, lint and baseline. Tool tests execute all six definitions through the runtime; plugin tests use a fake context for registration, when, prompt and guard. A real-vault test is opt-in via DSH_WIKI_TEST_VAULT and asserts the control queries, backlinks and a clean baseline.
|
|
68
|
+
|
|
69
|
+
## Future
|
|
70
|
+
|
|
71
|
+
1. ACL-aware append/create plus log.md/index.md regeneration.
|
|
72
|
+
2. Opt-in ambient recall (not default: it risks prompt cache and context bloat).
|
|
73
|
+
3. Bundled aiwiki-query skill mirroring skills/wiki-query.
|
|
74
|
+
4. Web sidebar panel over the same index.
|
package/docs/RELEASE.md
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# Релиз dsh-ai-wiki
|
|
2
|
+
|
|
3
|
+
## Ветки и CI
|
|
4
|
+
|
|
5
|
+
Рабочая ветка — master. CI запускается на push в master, на pull request и вручную:
|
|
6
|
+
|
|
7
|
+
- test: ubuntu-latest и windows-latest, Node 22 и 24; npm ci, npm test, npm run check;
|
|
8
|
+
- pack: ubuntu, Node 24; npm pack, npm publish --dry-run, artifact dsh-ai-wiki-tarball.
|
|
9
|
+
|
|
10
|
+
CI-сборка не требует npm-аутентификации и не публикует пакет. Артефакт tarball скачивается из run.
|
|
11
|
+
|
|
12
|
+
## Релиз по тегу
|
|
13
|
+
|
|
14
|
+
release.yml запускается на тег v* или вручную с входом tag. Он:
|
|
15
|
+
|
|
16
|
+
- проверяет, что version в package.json совпадает с тегом;
|
|
17
|
+
- гоняет тесты и синтаксис;
|
|
18
|
+
- собирает dist/dsh-ai-wiki-<version>.tgz и прикладывает к GitHub Release;
|
|
19
|
+
- публикует в npm через trusted publishing (OIDC), если версии ещё нет.
|
|
20
|
+
|
|
21
|
+
Для trusted publishing нужны npm >= 11.5.1 и Node >= 22.14.0; workflow обновляет npm до 11.15+.
|
|
22
|
+
|
|
23
|
+
## Первый 0.1.0: one-time bootstrap
|
|
24
|
+
|
|
25
|
+
Trusted publishing настраивается только для пакета, который уже существует в npm. Поэтому первый 0.1.0 публикуется один раз:
|
|
26
|
+
|
|
27
|
+
Вариант A, через GitHub Actions:
|
|
28
|
+
|
|
29
|
+
1. Создать npm automation/granular token с правом publish и bypass 2FA.
|
|
30
|
+
2. Добавить его в GitHub Secrets как NPM_TOKEN (значение не коммитить).
|
|
31
|
+
3. Запустить workflow Bootstrap publish вручную.
|
|
32
|
+
4. Убедиться, что npm view dsh-ai-wiki version возвращает 0.1.0.
|
|
33
|
+
5. Удалить bootstrap-publish.yml и секрет NPM_TOKEN.
|
|
34
|
+
|
|
35
|
+
Вариант B: один раз выполнить npm login и npm publish --access public локально, с OTP.
|
|
36
|
+
|
|
37
|
+
После появления пакета:
|
|
38
|
+
|
|
39
|
+
1. npmjs.com → пакет dsh-ai-wiki → Settings → Trusted Publisher → GitHub Actions.
|
|
40
|
+
2. Owner: pravets, repository: dsh-ai-wiki, workflow filename: release.yml.
|
|
41
|
+
3. Разрешить npm publish (allowed actions).
|
|
42
|
+
4. Проверить конфигурацию первым успешным publish в течение 2 дней: поднять версию до 0.1.1, поставить тег v0.1.1 и запустить release.yml.
|
|
43
|
+
|
|
44
|
+
Для v0.1.0 после bootstrap release.yml увидит, что версия уже есть, пропустит публикацию и создаст GitHub Release с tarball.
|
|
45
|
+
|
|
46
|
+
## Безопасность
|
|
47
|
+
|
|
48
|
+
- NPM_TOKEN живёт только до первого успешного publish; затем удаляется.
|
|
49
|
+
- В release.yml токена нет: только id-token: write и OIDC.
|
|
50
|
+
- OTP и токены не передаются в чат и не попадают в репозиторий.
|
|
51
|
+
- tarball не содержит tests, tools, package-lock, .npm-cache.
|
package/lib/config.mjs
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
function readJson(file) {
|
|
6
|
+
try {
|
|
7
|
+
if (!existsSync(file) || !statSync(file).isFile()) return { data: null, error: null };
|
|
8
|
+
const text = readFileSync(file, 'utf8');
|
|
9
|
+
return { data: JSON.parse(text), error: null };
|
|
10
|
+
} catch (error) {
|
|
11
|
+
return { data: null, error: error && error.message ? error.message : String(error) };
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function expandPath(value, cwd, env) {
|
|
16
|
+
let text = String(value === null || value === undefined ? '' : value).trim();
|
|
17
|
+
if (text === '') return text;
|
|
18
|
+
if (text === '~') text = os.homedir();
|
|
19
|
+
else if (text.startsWith('~/') || text.startsWith('~\\')) text = path.join(os.homedir(), text.slice(2));
|
|
20
|
+
text = text.replace(/%([^%]+)%/g, function (_match, name) {
|
|
21
|
+
return env[name] === undefined ? _match : env[name];
|
|
22
|
+
});
|
|
23
|
+
text = text.replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g, function (_match, name) {
|
|
24
|
+
return env[name] === undefined ? _match : env[name];
|
|
25
|
+
});
|
|
26
|
+
return path.isAbsolute(text) ? path.normalize(text) : path.resolve(cwd, text);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function samePath(left, right) {
|
|
30
|
+
const a = path.resolve(left);
|
|
31
|
+
const b = path.resolve(right);
|
|
32
|
+
if (process.platform === 'win32') return a.toLowerCase() === b.toLowerCase();
|
|
33
|
+
return a === b;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function detectVault(cwd) {
|
|
37
|
+
let dir = path.resolve(cwd);
|
|
38
|
+
for (let depth = 0; depth < 8; depth += 1) {
|
|
39
|
+
const agents = path.join(dir, 'AGENTS.md');
|
|
40
|
+
if (existsSync(agents)) {
|
|
41
|
+
let text = '';
|
|
42
|
+
try {
|
|
43
|
+
text = readFileSync(agents, 'utf8');
|
|
44
|
+
} catch {
|
|
45
|
+
text = '';
|
|
46
|
+
}
|
|
47
|
+
const looksLikeVault = text.includes('Vault Contract') || text.includes('Зоны и права') || text.includes('LLM Wiki');
|
|
48
|
+
const hasZone = existsSync(path.join(dir, '10-wiki')) || existsSync(path.join(dir, '15-precedent')) || existsSync(path.join(dir, '90-meta'));
|
|
49
|
+
const hasMarker = existsSync(path.join(dir, '.llm-ro')) || existsSync(path.join(dir, '.llm-rw')) || existsSync(path.join(dir, '.llm-append'));
|
|
50
|
+
if (looksLikeVault && (hasZone || hasMarker)) return dir;
|
|
51
|
+
}
|
|
52
|
+
const parent = path.dirname(dir);
|
|
53
|
+
if (parent === dir) break;
|
|
54
|
+
dir = parent;
|
|
55
|
+
}
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function normalizeVault(raw, context, errors) {
|
|
60
|
+
if (typeof raw === 'string') {
|
|
61
|
+
const abs = expandPath(raw, context.cwd, context.env);
|
|
62
|
+
return {
|
|
63
|
+
name: path.basename(abs),
|
|
64
|
+
path: abs,
|
|
65
|
+
includeRaw: true,
|
|
66
|
+
exists: existsSync(abs),
|
|
67
|
+
source: context.source
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
71
|
+
errors.push({ source: context.source, message: 'vault entry must be a string or an object' });
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
if (raw.enabled === false) return null;
|
|
75
|
+
const rawPath = typeof raw.path === 'string' ? raw.path : '';
|
|
76
|
+
if (rawPath === '') {
|
|
77
|
+
errors.push({ source: context.source, message: 'vault entry is missing path' });
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
const abs = expandPath(rawPath, context.cwd, context.env);
|
|
81
|
+
const name = typeof raw.name === 'string' && raw.name.trim() !== '' ? raw.name.trim() : path.basename(abs);
|
|
82
|
+
return {
|
|
83
|
+
name,
|
|
84
|
+
path: abs,
|
|
85
|
+
includeRaw: raw.includeRaw !== false,
|
|
86
|
+
exists: existsSync(abs),
|
|
87
|
+
source: context.source
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function mergeLayer(state, layer, errors) {
|
|
92
|
+
if (!layer || typeof layer !== 'object') return;
|
|
93
|
+
if (layer.vaults !== undefined) {
|
|
94
|
+
if (!Array.isArray(layer.vaults)) {
|
|
95
|
+
errors.push({ source: layer.source, message: 'vaults must be an array' });
|
|
96
|
+
} else {
|
|
97
|
+
if (layer.replaceVaults === true) state.vaults = [];
|
|
98
|
+
for (const raw of layer.vaults) {
|
|
99
|
+
const vault = normalizeVault(raw, { cwd: layer.cwd, env: layer.env, source: layer.source }, errors);
|
|
100
|
+
if (vault === null) continue;
|
|
101
|
+
const index = state.vaults.findIndex((entry) => entry.name.toLowerCase() === vault.name.toLowerCase());
|
|
102
|
+
if (index >= 0) state.vaults[index] = vault;
|
|
103
|
+
else state.vaults.push(vault);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
for (const key of ['indexDir', 'autoIndex', 'refreshSeconds', 'promptSection', 'guardWrites', 'allowNoStem', 'allowAnyMarkdown']) {
|
|
108
|
+
if (layer[key] !== undefined) state[key] = layer[key];
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function loadConfig(options) {
|
|
113
|
+
const settings = options || {};
|
|
114
|
+
const cwd = path.resolve(settings.cwd || process.cwd());
|
|
115
|
+
const env = settings.env || process.env;
|
|
116
|
+
const dshHome = expandPath(settings.dshHome || env.DSH_HOME || path.join(os.homedir(), '.dsh'), cwd, env);
|
|
117
|
+
const userFile = path.join(dshHome, 'dsh-wiki.json');
|
|
118
|
+
const projectFile = path.join(cwd, '.dsh-wiki.json');
|
|
119
|
+
const errors = [];
|
|
120
|
+
const sources = [];
|
|
121
|
+
const state = {
|
|
122
|
+
vaults: [],
|
|
123
|
+
indexDir: path.join(dshHome, 'cache', 'dsh-ai-wiki'),
|
|
124
|
+
autoIndex: true,
|
|
125
|
+
refreshSeconds: 5,
|
|
126
|
+
promptSection: true,
|
|
127
|
+
guardWrites: true,
|
|
128
|
+
allowNoStem: false,
|
|
129
|
+
allowAnyMarkdown: false
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
if (settings.base && typeof settings.base === 'object') {
|
|
133
|
+
sources.push('cordis');
|
|
134
|
+
mergeLayer(state, Object.assign({ cwd, env, source: 'cordis' }, settings.base), errors);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (env.DSH_WIKI_ROOTS !== undefined && String(env.DSH_WIKI_ROOTS).trim() !== '') {
|
|
138
|
+
sources.push('DSH_WIKI_ROOTS');
|
|
139
|
+
mergeLayer(state, {
|
|
140
|
+
cwd,
|
|
141
|
+
env,
|
|
142
|
+
source: 'DSH_WIKI_ROOTS',
|
|
143
|
+
vaults: String(env.DSH_WIKI_ROOTS).split(';').map((item) => item.trim()).filter(Boolean)
|
|
144
|
+
}, errors);
|
|
145
|
+
}
|
|
146
|
+
if (env.DSH_WIKI_INDEX_DIR !== undefined && String(env.DSH_WIKI_INDEX_DIR).trim() !== '') {
|
|
147
|
+
state.indexDir = expandPath(env.DSH_WIKI_INDEX_DIR, cwd, env);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const user = readJson(userFile);
|
|
151
|
+
if (user.error !== null) errors.push({ source: userFile, message: user.error });
|
|
152
|
+
if (user.data !== null) {
|
|
153
|
+
sources.push(userFile);
|
|
154
|
+
if (user.data.indexDir !== undefined) user.data.indexDir = expandPath(user.data.indexDir, cwd, env);
|
|
155
|
+
mergeLayer(state, Object.assign({ cwd, env, source: userFile }, user.data), errors);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const project = readJson(projectFile);
|
|
159
|
+
if (project.error !== null) errors.push({ source: projectFile, message: project.error });
|
|
160
|
+
if (project.data !== null) {
|
|
161
|
+
sources.push(projectFile);
|
|
162
|
+
if (project.data.indexDir !== undefined) project.data.indexDir = expandPath(project.data.indexDir, cwd, env);
|
|
163
|
+
mergeLayer(state, Object.assign({ cwd, env, source: projectFile }, project.data), errors);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
if (state.indexDir !== undefined && state.indexDir !== null && state.indexDir !== '') {
|
|
167
|
+
state.indexDir = expandPath(state.indexDir, cwd, env);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const detected = detectVault(cwd);
|
|
171
|
+
if (detected !== null && !state.vaults.some((entry) => samePath(entry.path, detected))) {
|
|
172
|
+
state.vaults.push({ name: path.basename(detected), path: detected, includeRaw: true, exists: true, source: 'detected' });
|
|
173
|
+
sources.push('detected:' + detected);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const seen = new Set();
|
|
177
|
+
state.vaults = state.vaults.filter((vault) => {
|
|
178
|
+
const key = vault.name.toLowerCase();
|
|
179
|
+
if (seen.has(key)) {
|
|
180
|
+
errors.push({ source: vault.source, message: 'duplicate vault name: ' + vault.name });
|
|
181
|
+
return false;
|
|
182
|
+
}
|
|
183
|
+
seen.add(key);
|
|
184
|
+
return true;
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
state.indexDir = path.resolve(state.indexDir);
|
|
188
|
+
state.errors = errors;
|
|
189
|
+
state.sources = sources;
|
|
190
|
+
state.userFile = userFile;
|
|
191
|
+
state.projectFile = projectFile;
|
|
192
|
+
return state;
|
|
193
|
+
}
|
package/lib/errors.mjs
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export class AiWikiError extends Error {
|
|
2
|
+
constructor(code, message, hint) {
|
|
3
|
+
super(message);
|
|
4
|
+
this.name = 'AiWikiError';
|
|
5
|
+
this.code = code;
|
|
6
|
+
if (hint) this.hint = hint;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function fail(code, message, hint) {
|
|
11
|
+
const error = { code, message };
|
|
12
|
+
if (hint) error.hint = hint;
|
|
13
|
+
return { ok: false, error };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function ok(data) {
|
|
17
|
+
return Object.assign({ ok: true }, data);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function clamp(value, fallback, min, max) {
|
|
21
|
+
const n = Number(value);
|
|
22
|
+
if (!Number.isFinite(n)) return fallback;
|
|
23
|
+
return Math.min(max, Math.max(min, Math.trunc(n)));
|
|
24
|
+
}
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { createRuntime, createTools } from './tools.mjs';
|
|
2
|
+
|
|
3
|
+
export const name = 'dsh-ai-wiki';
|
|
4
|
+
|
|
5
|
+
export const inject = ['tools', 'workingDirectory', 'systemPrompt'];
|
|
6
|
+
|
|
7
|
+
export function apply(ctx, config) {
|
|
8
|
+
const runtime = createRuntime(ctx, config || {});
|
|
9
|
+
|
|
10
|
+
for (const definition of createTools(runtime)) {
|
|
11
|
+
ctx.tools.register(definition, {
|
|
12
|
+
when: (context) => runtime.hasVaults(context && context.agent)
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
ctx.inject(['systemPrompt'], (inner) => {
|
|
17
|
+
inner.systemPrompt.section({
|
|
18
|
+
name: 'aiwiki:vault',
|
|
19
|
+
order: inner.systemPrompt.getSectionOrder('MCP_SERVERS') + 10,
|
|
20
|
+
interpolate: false,
|
|
21
|
+
text: (context) => runtime.promptText(context && context.agent)
|
|
22
|
+
});
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
ctx.tools.guard((exec) => runtime.writeDenial(exec));
|
|
26
|
+
|
|
27
|
+
if (typeof ctx.effect === 'function') {
|
|
28
|
+
ctx.effect(() => () => runtime.dispose());
|
|
29
|
+
}
|
|
30
|
+
}
|