opencode-wiki-historian 0.6.3 → 0.7.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.
Files changed (56) hide show
  1. package/README.en.md +156 -42
  2. package/README.md +127 -360
  3. package/dist/anchor.js +4 -4
  4. package/dist/config.d.ts +3 -3
  5. package/dist/config.js +3 -3
  6. package/dist/index.d.ts +14 -4
  7. package/dist/index.js +21 -52
  8. package/dist/lint.d.ts +2 -2
  9. package/dist/lint.js +2 -2
  10. package/dist/maintain.d.ts +2 -2
  11. package/dist/maintain.js +7 -7
  12. package/dist/map.d.ts +1 -1
  13. package/dist/map.js +1 -1
  14. package/dist/migrate-apply.d.ts +1 -1
  15. package/dist/migrate-apply.js +1 -1
  16. package/dist/migrate-score.d.ts +2 -2
  17. package/dist/migrate-score.js +3 -3
  18. package/dist/migrate-store.d.ts +1 -1
  19. package/dist/migrate-store.js +1 -1
  20. package/dist/migrate.d.ts +2 -2
  21. package/dist/migrate.js +2 -2
  22. package/dist/prompts.d.ts +20 -0
  23. package/dist/prompts.js +46 -0
  24. package/dist/skills.d.ts +33 -0
  25. package/dist/skills.js +88 -0
  26. package/dist/surface.d.ts +1 -1
  27. package/dist/surface.js +2 -2
  28. package/dist/templates/evidence.d.ts +1 -1
  29. package/dist/templates/evidence.js +1 -1
  30. package/dist/templates/genres.d.ts +5 -5
  31. package/dist/templates/genres.js +7 -7
  32. package/dist/templates/skeletons.d.ts +3 -3
  33. package/dist/templates/skeletons.js +3 -3
  34. package/dist/tools/anchor.js +2 -2
  35. package/dist/tools/create.js +1 -1
  36. package/dist/tools/local.js +1 -1
  37. package/dist/tools/mutate.d.ts +1 -1
  38. package/dist/tools/mutate.js +1 -1
  39. package/dist/tools/shared.d.ts +3 -3
  40. package/dist/tools/shared.js +10 -10
  41. package/dist/tools.d.ts +2 -2
  42. package/dist/tools.js +2 -2
  43. package/dist/translate.d.ts +1 -1
  44. package/dist/translate.js +1 -1
  45. package/dist/v2.d.ts +114 -0
  46. package/dist/v2.js +249 -0
  47. package/dist/wiki/assets.d.ts +1 -1
  48. package/dist/wiki/assets.js +1 -1
  49. package/dist/wiki/client.d.ts +2 -3
  50. package/dist/wiki/client.js +2 -3
  51. package/dist/wiki/locale.d.ts +1 -1
  52. package/dist/wiki/locale.js +3 -3
  53. package/dist/wiki/pages.read.d.ts +1 -1
  54. package/dist/wiki/pages.write.d.ts +1 -1
  55. package/package.json +1 -1
  56. package/skills/historian/SKILL.md +2 -2
package/dist/v2.js ADDED
@@ -0,0 +1,249 @@
1
+ /**
2
+ * V2 plugin generation: `setup(ctx)` adapter for the opencode v2 host
3
+ * (engine >= 2.2, default export `{id, setup, server}`).
4
+ *
5
+ * Ground truth for every host call below was probed against the installed
6
+ * engine binary (2.2.7/2.3.0), not against the v1-shaped public SDK:
7
+ * - ctx.tool.transform(editor => editor.add({name, description, input:
8
+ * <JSON Schema>, execute: async (args) => ({content})})) — registered and
9
+ * model-invocable (smoke-verified 11/11).
10
+ * - ctx.command.transform: editor exposes add() only; same-name add would
11
+ * shadow a user command, so the list-first check preserves the V1 ??=
12
+ * semantics (user-defined /historian-capture wins).
13
+ * - ctx.skill.transform: editor.add requires {id,name,description,path,
14
+ * content} (host throws SchemaError Missing key ["id"] otherwise).
15
+ * - ctx.session.hook('context', ev => ev.system is an array of typed
16
+ * parts): the advisory is merged into the LAST text part — the block
17
+ * count never grows, keeping strict chat templates (vLLM) happy, same
18
+ * invariant as the V1 system.transform hook.
19
+ * - ctx.event.subscribe({types}) returns an async iterable.
20
+ *
21
+ * Named gaps vs V1 (failures are logged, never silent):
22
+ * - Capture reminder: the v2 server surface has no toast channel (ctx.rpc
23
+ * is a definition factory, not a caller; there is no ctx.tui/client), so
24
+ * the idle reminder degrades to a one-time console.error per session.
25
+ * `session.idle` fires on busy→idle transitions (TUI sessions); headless
26
+ * `opencode run` streams do not emit it — same limitation class as V1.
27
+ * - skills.paths has no v2 config hook; skills ship through skill.transform
28
+ * instead (probe-verified surface).
29
+ *
30
+ * Options fail-closed: invalid/missing options log once and register
31
+ * NOTHING (no half-wired tool surface aimed at an unresolvable wiki key) —
32
+ * matching the sibling sibyl-system plugin's v2 precedent and stricter than
33
+ * V1's empty-hooks return.
34
+ */
35
+ import { fileURLToPath } from 'url';
36
+ import { homedir } from 'node:os';
37
+ import { tool } from '@opencode-ai/plugin';
38
+ import { resolveOptions } from './config.js';
39
+ import { isReadingLoopConfirmed, loopStatePath } from './loop-state.js';
40
+ import { buildTools } from './tools.js';
41
+ import { collectSkillEntries } from './skills.js';
42
+ import { READING_LOOP_ADVISORY, CAPTURE_COMMAND_DESCRIPTION, CAPTURE_COMMAND_TEMPLATE, CAPTURE_TOAST_MESSAGE, } from './prompts.js';
43
+ const PLUGIN_ID = 'opencode-wiki-historian';
44
+ const CAPTURE_COMMAND_NAME = 'historian-capture';
45
+ const skillsDir = fileURLToPath(new URL('../skills/', import.meta.url));
46
+ /** Convert a V1 tool's zod raw arg shape to JSON Schema through the SDK's
47
+ * nested zod (tool.schema) — single source, no per-tool schema duplicates.
48
+ * On conversion failure, a permissive object schema is registered and
49
+ * logged; execute still validates with the strict zod parse inside the V1
50
+ * tool body, so a loose registration can never corrupt inputs. */
51
+ export function argsToJsonSchema(args) {
52
+ try {
53
+ return tool.schema.toJSONSchema(tool.schema.object(args ?? {}), { io: 'input' });
54
+ }
55
+ catch (err) {
56
+ return {
57
+ __permissive: true,
58
+ __reason: err instanceof Error ? err.message : String(err),
59
+ type: 'object',
60
+ additionalProperties: true,
61
+ };
62
+ }
63
+ }
64
+ export async function setup(ctx, deps = {}) {
65
+ const log = deps.log ?? ((m) => console.error(m));
66
+ const homeDir = deps.homeDir ?? homedir();
67
+ let opts;
68
+ try {
69
+ opts = resolveOptions((ctx.options ?? {}), deps.env ?? process.env, homeDir);
70
+ }
71
+ catch (err) {
72
+ log(`[${PLUGIN_ID}] V2 setup: invalid plugin options; plugin disabled. ${err instanceof Error ? err.message : String(err)}`);
73
+ return;
74
+ }
75
+ // Tool surface.
76
+ if (!ctx.tool?.transform) {
77
+ log(`[${PLUGIN_ID}] V2 host exposes no tool.transform; tools NOT registered.`);
78
+ }
79
+ else {
80
+ const tools = buildTools(opts, deps.buildDeps ?? {});
81
+ try {
82
+ await ctx.tool.transform((editor) => {
83
+ for (const [name, def] of Object.entries(tools)) {
84
+ let input;
85
+ try {
86
+ input = argsToJsonSchema(def.args);
87
+ }
88
+ catch (err) {
89
+ log(`[${PLUGIN_ID}] schema conversion skipped ${name}: ${err instanceof Error ? err.message : String(err)}`);
90
+ continue;
91
+ }
92
+ if (input.__permissive) {
93
+ log(`[${PLUGIN_ID}] tool ${name}: zod→JSON Schema failed (${String(input.__reason)}); permissive registration, execute still strict-parses.`);
94
+ }
95
+ editor.add({
96
+ name,
97
+ description: def.description,
98
+ input,
99
+ execute: async (args, tctx) => {
100
+ try {
101
+ const res = await def.execute(args, { sessionID: tctx?.sessionID ?? '', abort: tctx?.abort });
102
+ // V1 tools return plain JSON-string envelopes (not v1
103
+ // ToolResult objects): strings pass through untouched;
104
+ // anything else is serialized for the host channel.
105
+ const out = typeof res === 'string'
106
+ ? res
107
+ : res?.output;
108
+ return { content: typeof out === 'string' ? out : JSON.stringify(res ?? null) };
109
+ }
110
+ catch (err) {
111
+ // Tools are engineered to envelope their errors; this net is
112
+ // for host-shape surprises — a throw must never kill the run.
113
+ return { content: `[${PLUGIN_ID}] ${name} failed: ${err instanceof Error ? err.stack ?? err.message : String(err)}` };
114
+ }
115
+ },
116
+ });
117
+ }
118
+ });
119
+ }
120
+ catch (err) {
121
+ log(`[${PLUGIN_ID}] tool.transform failed: ${err instanceof Error ? err.message : String(err)}`);
122
+ }
123
+ }
124
+ // Command surface — ??= semantics: a user-defined command of the same name
125
+ // wins (editor only offers add(), so check list() first).
126
+ if (!ctx.command?.transform) {
127
+ log(`[${PLUGIN_ID}] V2 host exposes no command.transform; /${CAPTURE_COMMAND_NAME} NOT registered.`);
128
+ }
129
+ else {
130
+ try {
131
+ const existing = await ctx.command.list?.();
132
+ if (existing?.some((c) => c.name === CAPTURE_COMMAND_NAME)) {
133
+ log(`[${PLUGIN_ID}] /${CAPTURE_COMMAND_NAME} already defined by user config; plugin default NOT registered.`);
134
+ }
135
+ else {
136
+ await ctx.command.transform((editor) => {
137
+ editor.add({
138
+ name: CAPTURE_COMMAND_NAME,
139
+ description: CAPTURE_COMMAND_DESCRIPTION,
140
+ template: CAPTURE_COMMAND_TEMPLATE,
141
+ });
142
+ });
143
+ }
144
+ }
145
+ catch (err) {
146
+ log(`[${PLUGIN_ID}] command registration failed: ${err instanceof Error ? err.message : String(err)}`);
147
+ }
148
+ }
149
+ // Skill surface — bundled SKILL.md packages registered individually (V2 has
150
+ // no config hook for skills.paths).
151
+ if (!ctx.skill?.transform) {
152
+ log(`[${PLUGIN_ID}] V2 host exposes no skill.transform; bundled skills NOT registered.`);
153
+ }
154
+ else {
155
+ try {
156
+ const entries = collectSkillEntries(skillsDir, { log });
157
+ if (entries.length > 0) {
158
+ await ctx.skill.transform((editor) => {
159
+ for (const entry of entries) {
160
+ try {
161
+ editor.add(entry);
162
+ }
163
+ catch (err) {
164
+ log(`[${PLUGIN_ID}] skill ${entry.id} rejected by host: ${err instanceof Error ? err.message : String(err)}`);
165
+ }
166
+ }
167
+ });
168
+ }
169
+ }
170
+ catch (err) {
171
+ log(`[${PLUGIN_ID}] skill collection failed: ${err instanceof Error ? err.message : String(err)}`);
172
+ }
173
+ }
174
+ // Reading-loop advisory — same double gate as V1 (option AND per-request
175
+ // sentinel re-read), merged into the LAST text part so the system block
176
+ // count never grows (strict chat templates).
177
+ if (opts.readingLoop === true && !isReadingLoopConfirmed(homeDir)) {
178
+ log(`[${PLUGIN_ID}] readingLoop enabled in config but not confirmed on this machine; to activate, create ` +
179
+ loopStatePath(homeDir) +
180
+ ' with {"version":1,"confirmed":true}');
181
+ }
182
+ if (!ctx.session?.hook) {
183
+ if (opts.readingLoop === true) {
184
+ log(`[${PLUGIN_ID}] V2 host exposes no session.hook; readingLoop advisory NOT wired.`);
185
+ }
186
+ }
187
+ else {
188
+ try {
189
+ ctx.session.hook('context', (ev) => {
190
+ try {
191
+ if (opts.readingLoop !== true)
192
+ return;
193
+ if (!isReadingLoopConfirmed(homeDir))
194
+ return;
195
+ const parts = ev?.system;
196
+ if (!Array.isArray(parts))
197
+ return;
198
+ const textOf = (p) => (typeof p?.text === 'string' ? p.text : '');
199
+ if (parts.some((p) => textOf(p).includes('historian_search')))
200
+ return;
201
+ for (let i = parts.length - 1; i >= 0; i--) {
202
+ if (parts[i]?.type === 'text' && typeof parts[i].text === 'string') {
203
+ parts[i].text = textOf(parts[i]) + '\n\n' + READING_LOOP_ADVISORY;
204
+ return;
205
+ }
206
+ }
207
+ }
208
+ catch (err) {
209
+ log(`[${PLUGIN_ID}] reading-loop advisory skipped: ${err instanceof Error ? err.message : String(err)}`);
210
+ }
211
+ });
212
+ }
213
+ catch (err) {
214
+ log(`[${PLUGIN_ID}] session.hook('context') registration failed: ${err instanceof Error ? err.message : String(err)}`);
215
+ }
216
+ }
217
+ // Capture reminder — session.idle subscription; NO toast channel on the v2
218
+ // server surface (named gap), so this logs once per session. Mirrors V1's
219
+ // once-per-session-per-load discipline.
220
+ if (opts.capture.enabled === true) {
221
+ const eventApi = ctx.event;
222
+ if (!eventApi?.subscribe) {
223
+ log(`[${PLUGIN_ID}] V2 host exposes no event.subscribe; capture reminder NOT wired.`);
224
+ }
225
+ else {
226
+ const reminded = new Set();
227
+ void (async () => {
228
+ const stream = eventApi.subscribe({ types: ['session.idle'] });
229
+ for await (const ev of stream) {
230
+ try {
231
+ if (ev?.type !== 'session.idle')
232
+ continue;
233
+ const sessionID = ev.properties?.sessionID;
234
+ if (!sessionID || reminded.has(sessionID))
235
+ continue;
236
+ reminded.add(sessionID);
237
+ // Named gap: v2 server surface has no toast API — console is the
238
+ // honest fallback; the /historian-capture command remains the
239
+ // contract surface either way.
240
+ log(`[${PLUGIN_ID}] capture reminder: ${CAPTURE_TOAST_MESSAGE}`);
241
+ }
242
+ catch (err) {
243
+ log(`[${PLUGIN_ID}] capture reminder skipped: ${err instanceof Error ? err.message : String(err)}`);
244
+ }
245
+ }
246
+ })().catch((err) => log(`[${PLUGIN_ID}] event stream ended: ${err instanceof Error ? err.message : String(err)}`));
247
+ }
248
+ }
249
+ }
@@ -4,7 +4,7 @@
4
4
  * Body: FormData, field `mediaUpload` (filename = sanitizeAssetName(filename)).
5
5
  * Optional `parent` field carries numeric folderId for folder-scoped uploads.
6
6
  * Auth: Bearer token. Api key is INJECTED via `deps.apiKey` — resolution
7
- * lives in the caller (tools layer, todo 11, via readWikiApiKey), so this
7
+ * lives in the caller (tools layer, via readWikiApiKey), so this
8
8
  * module stays network- and config-free (pure + injected, trivially testable).
9
9
  *
10
10
  * Response JSON: `{type:'success', location}` or `{type:'error', msg}`.
@@ -4,7 +4,7 @@
4
4
  * Body: FormData, field `mediaUpload` (filename = sanitizeAssetName(filename)).
5
5
  * Optional `parent` field carries numeric folderId for folder-scoped uploads.
6
6
  * Auth: Bearer token. Api key is INJECTED via `deps.apiKey` — resolution
7
- * lives in the caller (tools layer, todo 11, via readWikiApiKey), so this
7
+ * lives in the caller (tools layer, via readWikiApiKey), so this
8
8
  * module stays network- and config-free (pure + injected, trivially testable).
9
9
  *
10
10
  * Response JSON: `{type:'success', location}` or `{type:'error', msg}`.
@@ -8,8 +8,7 @@
8
8
  * 2. Body that is not parseable JSON -> HttpError ('non-json response')
9
9
  * 3. Top-level GraphQL `errors[]` -> GraphQLError
10
10
  * 4. Payload `responseResult.succeeded === false` -> WikiError (permission-ish
11
- * errorCode/message -> PermissionError, the class the plan's R-b contract
12
- * refers to). The responseResult lookup is field-name agnostic: wiki.js
11
+ * errorCode/message -> PermissionError). The responseResult lookup is field-name agnostic: wiki.js
13
12
  * wraps every pages.* operation's result key, so we inspect the first key
14
13
  * of `data` (pitfall #3).
15
14
  *
@@ -49,7 +48,7 @@ export declare class WikiError extends Error {
49
48
  constructor(errorCode: string, slug: string, message: string);
50
49
  }
51
50
  /** Permission failures from either layer — HTTP 401/403 or a permission-ish
52
- * payload errorCode/message. Named per plan R-b (wiki token scope shortage). */
51
+ * payload errorCode/message — the wiki token scope shortage class. */
53
52
  export declare class PermissionError extends WikiError {
54
53
  constructor(errorCode: string, slug: string, message: string);
55
54
  }
@@ -8,8 +8,7 @@
8
8
  * 2. Body that is not parseable JSON -> HttpError ('non-json response')
9
9
  * 3. Top-level GraphQL `errors[]` -> GraphQLError
10
10
  * 4. Payload `responseResult.succeeded === false` -> WikiError (permission-ish
11
- * errorCode/message -> PermissionError, the class the plan's R-b contract
12
- * refers to). The responseResult lookup is field-name agnostic: wiki.js
11
+ * errorCode/message -> PermissionError). The responseResult lookup is field-name agnostic: wiki.js
13
12
  * wraps every pages.* operation's result key, so we inspect the first key
14
13
  * of `data` (pitfall #3).
15
14
  *
@@ -61,7 +60,7 @@ export class WikiError extends Error {
61
60
  }
62
61
  }
63
62
  /** Permission failures from either layer — HTTP 401/403 or a permission-ish
64
- * payload errorCode/message. Named per plan R-b (wiki token scope shortage). */
63
+ * payload errorCode/message — the wiki token scope shortage class. */
65
64
  export class PermissionError extends WikiError {
66
65
  constructor(errorCode, slug, message) {
67
66
  super(errorCode, slug, message);
@@ -23,7 +23,7 @@ export declare class PathValidationError extends Error {
23
23
  * 6. any segment is length 1 (wiki.js rejects single-char path components)
24
24
  * 7. any segment contains characters outside `[A-Za-z0-9._-]`
25
25
  * 8. any segment is a reserved word (wiki.js endpoint collision), except the
26
- * exact top-level 'home' (a live published path — see D9 note at the check)
26
+ * exact top-level 'home' (a live published path — see the note at the check below)
27
27
  *
28
28
  * Order matters: cheap substring checks first, then per-segment rules.
29
29
  * Every rejection names the offending segment + the rule in the message.
@@ -45,7 +45,7 @@ const SEGMENT_CHARS = /^[A-Za-z0-9._-]+$/;
45
45
  * 6. any segment is length 1 (wiki.js rejects single-char path components)
46
46
  * 7. any segment contains characters outside `[A-Za-z0-9._-]`
47
47
  * 8. any segment is a reserved word (wiki.js endpoint collision), except the
48
- * exact top-level 'home' (a live published path — see D9 note at the check)
48
+ * exact top-level 'home' (a live published path — see the note at the check below)
49
49
  *
50
50
  * Order matters: cheap substring checks first, then per-segment rules.
51
51
  * Every rejection names the offending segment + the rule in the message.
@@ -85,8 +85,8 @@ export function validatePath(p) {
85
85
  if (!SEGMENT_CHARS.test(seg)) {
86
86
  throw new PathValidationError(`segment '${seg}' contains invalid characters (allowed: [A-Za-z0-9._-])`);
87
87
  }
88
- // D9 bypass (probe p1): wiki.js 2.5.314 hosts a live published page at
89
- // path=home (id48, en+zh) — the reserved-word block was plugin-side
88
+ // Probed against the live instance (wiki.js 2.5.314): it hosts a published
89
+ // page at path=home (id48, en+zh) — the reserved-word block was plugin-side
90
90
  // folklore, not a server limit. Allow the EXACT top-level segment 'home'
91
91
  // only; nested 'home' (foo/home) and case variants (HOME) stay rejected.
92
92
  const isExactTopLevelHome = segments.length === 1 && seg === 'home';
@@ -12,7 +12,7 @@
12
12
  */
13
13
  import { type GqlClient } from './client.js';
14
14
  export type Locale = 'en' | 'zh';
15
- /** Port for todo 8 (real translation engine); pages.write injects it. */
15
+ /** Translation-engine port (src/translate.ts); pages.write injects it. */
16
16
  export type TranslateFn = (text: string, from: Locale, to: Locale) => Promise<string>;
17
17
  export interface PageRecord {
18
18
  readonly id: number;
@@ -92,7 +92,7 @@ interface MutableState {
92
92
  readonly editor: string;
93
93
  }
94
94
  /** Full mutable state of one page (single(id)) — exported for the migrate
95
- * engine (todo 14), whose pre-image backup must capture publishStartDate/
95
+ * engine, whose pre-image backup must capture publishStartDate/
96
96
  * publishEndDate alongside the readPage fields (the pilot restore replays
97
97
  * the backup through updatePage; RMW needs the write-side field contract). */
98
98
  export type { MutableState };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-wiki-historian",
3
- "version": "0.6.3",
3
+ "version": "0.7.0",
4
4
  "description": "opencode plugin that manages a wiki.js knowledge base with bilingual pages, genre templates, and migration tooling.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -376,13 +376,13 @@ light 扫在 maintain 行之外附带 **surface-light** 三类:`coverage`(li
376
376
 
377
377
  ### 重构冻结协议 (Reorg Freeze)
378
378
 
379
- 批量迁移/章节重组作业期间,执行 K2 交接沉淀的 6 条纪律:
379
+ 批量迁移/章节重组作业期间,执行以下 6 条冻结纪律:
380
380
 
381
381
  1. **冻结窗口**:迁移作业进行时,普通会话对涉及的页**只读不写**,避免入链改写与移动互相赛跑。
382
382
  2. **PageNotFound 即停**:任何一步报 PageNotFound,立即停止该页操作、回地图重查——多半路径已变,不盲目重试。
383
383
  3. **按 id 重定位**:重定位页面用返回的页面 id(不假设路径稳定);路径是易变的展示位,id 是身份。
384
384
  4. **preimage 先落 evidence**:动任何页之前,把原文快照先写入 `_evidence/`(`tier:"evidence"`),每步可回滚。
385
- 5. **Redirect 存根规范**:wiki.js 无原生重定向。旧路径改写为存根页——正文以 `> Redirect:` 行首标记开头、指向规范页(D10 约定);双语孪生腿同样处理;deep maintain 负责统计存根图。
385
+ 5. **Redirect 存根规范**:wiki.js 无原生重定向。旧路径改写为存根页——正文以 `> Redirect:` 行首标记开头、指向规范页(本仓存根约定);双语孪生腿同样处理;deep maintain 负责统计存根图。
386
386
  6. **入链改写仅 URL 机械改动**:批量修引用只替换 URL/路径本身,不改一字正文;任何语义级修订退出冻结区、走正常策展回路。
387
387
 
388
388
  ### Opportunistic backfill(顺手补骨架)