opencode-wiki-historian 0.5.2 → 0.5.3
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/dist/anchor.d.ts +63 -0
- package/dist/anchor.js +186 -0
- package/dist/lint.js +17 -0
- package/dist/maintain.d.ts +22 -1
- package/dist/maintain.js +84 -4
- package/dist/migrate.js +2 -2
- package/dist/templates/genres.js +3 -3
- package/dist/templates/skeletons.js +26 -16
- package/dist/tools/anchor.d.ts +10 -0
- package/dist/tools/anchor.js +90 -0
- package/dist/tools/local.js +2 -2
- package/dist/tools.js +2 -0
- package/dist/wiki/pages.write.d.ts +6 -0
- package/dist/wiki/pages.write.js +24 -1
- package/package.json +1 -1
- package/skills/historian/SKILL.md +2 -2
- package/skills/historian/references/adapting-your-own-wiki.md +1 -1
- package/skills/historian/references/genres.md +4 -4
- package/skills/historian/references/rules.md +5 -4
package/dist/anchor.d.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
export declare const DCP_STRIP_CLOSED_LIST: readonly ["trailing <dcp-message-id…</dcp-message-id> block", "outer whitespace"];
|
|
2
|
+
export declare function sha256(text: string): string;
|
|
3
|
+
export declare function canonicalText(raw: string): string;
|
|
4
|
+
export type StoreRow = {
|
|
5
|
+
readonly messageId: string;
|
|
6
|
+
readonly ordinal: number;
|
|
7
|
+
readonly role: string;
|
|
8
|
+
readonly rawText: string;
|
|
9
|
+
};
|
|
10
|
+
export type SealReceipt = {
|
|
11
|
+
readonly kind: 'historian-anchor';
|
|
12
|
+
readonly action: 'seal';
|
|
13
|
+
readonly sessionId: string;
|
|
14
|
+
readonly messageId: string;
|
|
15
|
+
readonly ordinal: number;
|
|
16
|
+
readonly role: string;
|
|
17
|
+
readonly dbPath: string;
|
|
18
|
+
readonly raw_sha256: string;
|
|
19
|
+
readonly canon_sha256: string;
|
|
20
|
+
readonly canon_len: number;
|
|
21
|
+
readonly normalization: readonly string[];
|
|
22
|
+
readonly sealed_at: string;
|
|
23
|
+
};
|
|
24
|
+
export type AnchorError = {
|
|
25
|
+
readonly ok: false;
|
|
26
|
+
readonly error: string;
|
|
27
|
+
readonly detail?: string;
|
|
28
|
+
};
|
|
29
|
+
export declare function defaultDbPath(homeDir: string): string;
|
|
30
|
+
/** Minimal seam so the test environment (vitest cannot resolve node:sqlite)
|
|
31
|
+
* injects a fake store while production keeps the real read-only DatabaseSync. */
|
|
32
|
+
export interface DbLike {
|
|
33
|
+
prepare(sql: string): {
|
|
34
|
+
all(...a: unknown[]): unknown[];
|
|
35
|
+
get(...a: unknown[]): unknown;
|
|
36
|
+
};
|
|
37
|
+
close(): void;
|
|
38
|
+
}
|
|
39
|
+
export type DbOpener = (dbPath: string) => DbLike | AnchorError;
|
|
40
|
+
export declare function resolveSessionId(db: DbLike, sessionId: string | undefined, titleLike: string | undefined): string | AnchorError;
|
|
41
|
+
/** Locate the anchor message: by ordinal (1-based; negative counts from end) or by UNIQUE exact canonical-body match. */
|
|
42
|
+
export declare function locateMessage(db: DbLike, sessionId: string, index: number | undefined, body: string | undefined): StoreRow | AnchorError;
|
|
43
|
+
export declare function sealAnchor(opts: {
|
|
44
|
+
dbPath: string;
|
|
45
|
+
sessionId?: string | undefined;
|
|
46
|
+
sessionTitle?: string | undefined;
|
|
47
|
+
index?: number | undefined;
|
|
48
|
+
body?: string | undefined;
|
|
49
|
+
now: string;
|
|
50
|
+
open?: DbOpener | undefined;
|
|
51
|
+
}): SealReceipt | AnchorError;
|
|
52
|
+
export type VerifyVerdict = {
|
|
53
|
+
readonly verdict: 'MATCH' | 'MISMATCH' | 'ABSENT';
|
|
54
|
+
readonly stored: SealReceipt;
|
|
55
|
+
readonly current?: SealReceipt;
|
|
56
|
+
readonly drift: readonly string[];
|
|
57
|
+
};
|
|
58
|
+
export declare function verifyAnchor(stored: SealReceipt, opts: {
|
|
59
|
+
dbPath: string;
|
|
60
|
+
now: string;
|
|
61
|
+
open?: DbOpener | undefined;
|
|
62
|
+
}): VerifyVerdict | AnchorError;
|
|
63
|
+
export declare function renderSealPage(r: SealReceipt, label?: string): string;
|
package/dist/anchor.js
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Anchor sealing core (g12b-3 merged into the historian per owner order
|
|
3
|
+
* 2026-10-01T16:24): a human order/approval message living in the engine's own
|
|
4
|
+
* session store is located by (session, ordinal) or by unique exact body match,
|
|
5
|
+
* hashed two ways (raw + canonical), and the receipt is written as an
|
|
6
|
+
* _evidence/anchors page. `verify` re-reads the store and re-computes: MATCH /
|
|
7
|
+
* MISMATCH / ABSENT — never a silent repair.
|
|
8
|
+
*
|
|
9
|
+
* The canonical-text rule is a CLOSED list (mirrors L-ORACLE-INTEGRITY's
|
|
10
|
+
* normalization discipline): trailing <dcp-message-id ...>...</dcp-message-id>
|
|
11
|
+
* block and surrounding whitespace. Anything else — including the engine
|
|
12
|
+
* merging several user turns into one message while the agent is busy — is
|
|
13
|
+
* NOT normalized away: a seal is only as atomic as the store row it names, and
|
|
14
|
+
* the receipt says which row that was.
|
|
15
|
+
*/
|
|
16
|
+
import { createHash } from 'node:crypto';
|
|
17
|
+
import { createRequire } from 'node:module';
|
|
18
|
+
import { fileURLToPath } from 'node:url';
|
|
19
|
+
export const DCP_STRIP_CLOSED_LIST = ['trailing <dcp-message-id…</dcp-message-id> block', 'outer whitespace'];
|
|
20
|
+
export function sha256(text) {
|
|
21
|
+
return createHash('sha256').update(text, 'utf8').digest('hex');
|
|
22
|
+
}
|
|
23
|
+
export function canonicalText(raw) {
|
|
24
|
+
return raw.replace(/\s*<dcp-message-id[^>]*>[\s\S]*?<\/dcp-message-id>\s*$/g, '').trim();
|
|
25
|
+
}
|
|
26
|
+
export function defaultDbPath(homeDir) {
|
|
27
|
+
return process.env['OPENCODE_DB'] ?? `${homeDir}/.local/share/opencode/opencode.db`;
|
|
28
|
+
}
|
|
29
|
+
function productionOpener(dbPath) {
|
|
30
|
+
try {
|
|
31
|
+
// createRequire('node:sqlite') keeps the module out of vite's static graph
|
|
32
|
+
// (its loader cannot resolve node:sqlite); tests inject `open` and never reach here.
|
|
33
|
+
const req = createRequire(fileURLToPath(import.meta.url));
|
|
34
|
+
const mod = req('node:sqlite');
|
|
35
|
+
return new mod.DatabaseSync(dbPath, { readOnly: true });
|
|
36
|
+
}
|
|
37
|
+
catch (e) {
|
|
38
|
+
return { ok: false, error: 'store-unreadable', detail: String(e).slice(0, 200) };
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
;
|
|
42
|
+
function openRo(dbPath, open = productionOpener) {
|
|
43
|
+
return open(dbPath);
|
|
44
|
+
}
|
|
45
|
+
function messagesOf(db, sessionId) {
|
|
46
|
+
const rows = db
|
|
47
|
+
.prepare('select id, data from message where session_id = ? order by id')
|
|
48
|
+
.all(sessionId);
|
|
49
|
+
const out = [];
|
|
50
|
+
rows.forEach((r, i) => {
|
|
51
|
+
let role = '';
|
|
52
|
+
try {
|
|
53
|
+
role = JSON.parse(r.data).role ?? '';
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
role = '';
|
|
57
|
+
}
|
|
58
|
+
const parts = db.prepare('select data from part where message_id = ? order by id').all(r.id);
|
|
59
|
+
const texts = [];
|
|
60
|
+
for (const p of parts) {
|
|
61
|
+
try {
|
|
62
|
+
const d = JSON.parse(p.data);
|
|
63
|
+
if (d.type === 'text' && typeof d.text === 'string')
|
|
64
|
+
texts.push(d.text);
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
/* part shapes we do not read are skipped, not fatal */
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
out.push({ messageId: r.id, ordinal: i + 1, role, rawText: texts.join('\n') });
|
|
71
|
+
});
|
|
72
|
+
return out;
|
|
73
|
+
}
|
|
74
|
+
export function resolveSessionId(db, sessionId, titleLike) {
|
|
75
|
+
if (sessionId !== undefined) {
|
|
76
|
+
const hit = db.prepare('select id from session where id = ?').get(sessionId);
|
|
77
|
+
return hit === undefined ? { ok: false, error: 'session-absent', detail: sessionId } : hit.id;
|
|
78
|
+
}
|
|
79
|
+
if (titleLike === undefined)
|
|
80
|
+
return { ok: false, error: 'no-locator', detail: 'pass session_id or session_title' };
|
|
81
|
+
const hits = db.prepare('select id from session where title like ? order by time_updated desc').all(`%${titleLike}%`);
|
|
82
|
+
if (hits.length === 0)
|
|
83
|
+
return { ok: false, error: 'session-absent', detail: titleLike };
|
|
84
|
+
if (hits.length > 1)
|
|
85
|
+
return { ok: false, error: 'session-ambiguous', detail: `${hits.length} sessions match "${titleLike}"` };
|
|
86
|
+
return hits[0].id;
|
|
87
|
+
}
|
|
88
|
+
/** Locate the anchor message: by ordinal (1-based; negative counts from end) or by UNIQUE exact canonical-body match. */
|
|
89
|
+
export function locateMessage(db, sessionId, index, body) {
|
|
90
|
+
const rows = messagesOf(db, sessionId);
|
|
91
|
+
if (rows.length === 0)
|
|
92
|
+
return { ok: false, error: 'session-empty', detail: sessionId };
|
|
93
|
+
if (index !== undefined) {
|
|
94
|
+
// locator convention = the receipt's 1-based ordinal; negative counts from the end.
|
|
95
|
+
const i = index > 0 ? index - 1 : rows.length + index;
|
|
96
|
+
const row = i < 0 ? undefined : rows[i];
|
|
97
|
+
return row === undefined ? { ok: false, error: 'index-absent', detail: `index ${index} of ${rows.length}` } : row;
|
|
98
|
+
}
|
|
99
|
+
if (body !== undefined) {
|
|
100
|
+
const want = canonicalText(body);
|
|
101
|
+
const hits = rows.filter((r) => canonicalText(r.rawText) === want);
|
|
102
|
+
if (hits.length === 0)
|
|
103
|
+
return { ok: false, error: 'body-absent', detail: `no single message equals the claimed body (scanned ${rows.length})` };
|
|
104
|
+
if (hits.length > 1) {
|
|
105
|
+
// A repeated short order ("同意" x2) is deliberately NOT auto-picked: ambiguity names the ordinals.
|
|
106
|
+
return { ok: false, error: 'body-ambiguous', detail: `body found at ordinals ${hits.map((h) => h.ordinal).join(',')} — re-seal with explicit index` };
|
|
107
|
+
}
|
|
108
|
+
return hits[0];
|
|
109
|
+
}
|
|
110
|
+
return { ok: false, error: 'no-locator', detail: 'pass index or body' };
|
|
111
|
+
}
|
|
112
|
+
export function sealAnchor(opts) {
|
|
113
|
+
const db = openRo(opts.dbPath, opts.open);
|
|
114
|
+
if ('ok' in db)
|
|
115
|
+
return db;
|
|
116
|
+
try {
|
|
117
|
+
const sid = resolveSessionId(db, opts.sessionId, opts.sessionTitle);
|
|
118
|
+
if (typeof sid !== 'string')
|
|
119
|
+
return sid;
|
|
120
|
+
const row = locateMessage(db, sid, opts.index, opts.body);
|
|
121
|
+
if ('ok' in row)
|
|
122
|
+
return row;
|
|
123
|
+
return {
|
|
124
|
+
kind: 'historian-anchor',
|
|
125
|
+
action: 'seal',
|
|
126
|
+
sessionId: sid,
|
|
127
|
+
messageId: row.messageId,
|
|
128
|
+
ordinal: row.ordinal,
|
|
129
|
+
role: row.role,
|
|
130
|
+
dbPath: opts.dbPath,
|
|
131
|
+
raw_sha256: sha256(row.rawText),
|
|
132
|
+
canon_sha256: sha256(canonicalText(row.rawText)),
|
|
133
|
+
canon_len: canonicalText(row.rawText).length,
|
|
134
|
+
normalization: DCP_STRIP_CLOSED_LIST,
|
|
135
|
+
sealed_at: opts.now,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
finally {
|
|
139
|
+
db.close();
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
export function verifyAnchor(stored, opts) {
|
|
143
|
+
const db = openRo(opts.dbPath, opts.open);
|
|
144
|
+
if ('ok' in db)
|
|
145
|
+
return db;
|
|
146
|
+
try {
|
|
147
|
+
const rows = messagesOf(db, stored.sessionId);
|
|
148
|
+
const row = rows.find((r) => r.messageId === stored.messageId);
|
|
149
|
+
if (row === undefined)
|
|
150
|
+
return { verdict: 'ABSENT', stored, drift: ['message row gone'] };
|
|
151
|
+
const current = {
|
|
152
|
+
...stored,
|
|
153
|
+
dbPath: opts.dbPath,
|
|
154
|
+
raw_sha256: sha256(row.rawText),
|
|
155
|
+
canon_sha256: sha256(canonicalText(row.rawText)),
|
|
156
|
+
canon_len: canonicalText(row.rawText).length,
|
|
157
|
+
sealed_at: opts.now,
|
|
158
|
+
};
|
|
159
|
+
const drift = ['raw_sha256', 'canon_sha256'].filter((k) => current[k] !== stored[k]);
|
|
160
|
+
return { verdict: drift.length === 0 ? 'MATCH' : 'MISMATCH', stored, current, drift };
|
|
161
|
+
}
|
|
162
|
+
finally {
|
|
163
|
+
db.close();
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
export function renderSealPage(r, label) {
|
|
167
|
+
return [
|
|
168
|
+
`# Anchor seal: ${label ?? r.messageId}`,
|
|
169
|
+
'',
|
|
170
|
+
'| field | value |',
|
|
171
|
+
'|---|---|',
|
|
172
|
+
`| session | \`${r.sessionId}\` |`,
|
|
173
|
+
`| message | \`${r.messageId}\` (ordinal ${r.ordinal}, role ${r.role}) |`,
|
|
174
|
+
`| raw sha256 | \`${r.raw_sha256}\` |`,
|
|
175
|
+
`| canonical sha256 | \`${r.canon_sha256}\` (len ${r.canon_len}) |`,
|
|
176
|
+
`| normalization | ${r.normalization.join('; ')} |`,
|
|
177
|
+
`| store | \`${r.dbPath}\` |`,
|
|
178
|
+
`| sealed at | ${r.sealed_at} |`,
|
|
179
|
+
'',
|
|
180
|
+
'```json historian-anchor',
|
|
181
|
+
JSON.stringify(r),
|
|
182
|
+
'```',
|
|
183
|
+
'',
|
|
184
|
+
'Verify via historian_anchor action:"verify" — stored JSON above is the claim; the engine store is the truth.',
|
|
185
|
+
].join('\n');
|
|
186
|
+
}
|
package/dist/lint.js
CHANGED
|
@@ -103,6 +103,22 @@ export function statusTokenFindings(lint) {
|
|
|
103
103
|
// --- markers, headings, intro -------------------------------------------------------
|
|
104
104
|
const TODO_COMMENT_RE = /(TODO|TBD|PLACEHOLDER|占位)/i;
|
|
105
105
|
const LITERAL_TODO_RE = /\bTODO:/g;
|
|
106
|
+
/** SYN-13 enforcement: a table cell that is nothing but a placeholder token is
|
|
107
|
+
* debt (bare `TBD`/`未定` cells passed the old comment-only scan and shipped Active).
|
|
108
|
+
* `todo` is deliberately NOT in this set — it is the skeleton's legitimate status
|
|
109
|
+
* vocabulary (待办/todo), not placeholder debt. */
|
|
110
|
+
const PLACEHOLDER_CELL_RE = /^(?:TBD|TBA|未定|待定|待补充|待定日期)[::]?$/i;
|
|
111
|
+
function countPlaceholderCells(masked) {
|
|
112
|
+
let n = 0;
|
|
113
|
+
for (const line of masked.split('\n')) {
|
|
114
|
+
if (!line.trimStart().startsWith('|'))
|
|
115
|
+
continue;
|
|
116
|
+
for (const cell of line.split('|'))
|
|
117
|
+
if (PLACEHOLDER_CELL_RE.test(cell.trim()))
|
|
118
|
+
n++;
|
|
119
|
+
}
|
|
120
|
+
return n;
|
|
121
|
+
}
|
|
106
122
|
function countTodoMarkers(masked) {
|
|
107
123
|
let n = 0;
|
|
108
124
|
for (const m of masked.matchAll(COMMENT_RE)) {
|
|
@@ -112,6 +128,7 @@ function countTodoMarkers(masked) {
|
|
|
112
128
|
// literal TODO: outside comments (comments already masked to '' for this pass)
|
|
113
129
|
const noComments = masked.replace(COMMENT_RE, '');
|
|
114
130
|
n += (noComments.match(LITERAL_TODO_RE) ?? []).length;
|
|
131
|
+
n += countPlaceholderCells(masked);
|
|
115
132
|
return n;
|
|
116
133
|
}
|
|
117
134
|
const HEADING_RE = /^(#{1,6})\s+(.+?)\s*#*$/;
|
package/dist/maintain.d.ts
CHANGED
|
@@ -76,6 +76,21 @@ export interface DueForReviewRow {
|
|
|
76
76
|
/** Re-check commands parsed from the ledger's command column (empty when none). */
|
|
77
77
|
readonly verifyCommands: readonly string[];
|
|
78
78
|
}
|
|
79
|
+
/** One open action item past its due date (G1 action tables rot silently —
|
|
80
|
+
* corpus law: "an action item that ages out without completion is a red
|
|
81
|
+
* flag"). Advisory queue like dueForReview; twins dedupe by path. */
|
|
82
|
+
export interface OverdueAction {
|
|
83
|
+
readonly path: string;
|
|
84
|
+
readonly locale: Locale;
|
|
85
|
+
/** First table cell (the 措施/action text), flattened to one line, ≤80 chars. */
|
|
86
|
+
readonly action: string;
|
|
87
|
+
/** The ISO date found in the 期限/due column, verbatim. */
|
|
88
|
+
readonly due: string;
|
|
89
|
+
/** Whole days from due date to now (floored). */
|
|
90
|
+
readonly daysOverdue: number;
|
|
91
|
+
/** Status cell text, verbatim (matched open). */
|
|
92
|
+
readonly status: string;
|
|
93
|
+
}
|
|
79
94
|
export interface MaintainReport {
|
|
80
95
|
readonly schema: typeof MAINTAIN_SCHEMA;
|
|
81
96
|
readonly generatedAt: string;
|
|
@@ -127,8 +142,10 @@ export interface MaintainReport {
|
|
|
127
142
|
readonly freshness: FreshnessScan | null;
|
|
128
143
|
/** Deep-only advisory queue (null in light, like freshness). */
|
|
129
144
|
readonly dueForReview: readonly DueForReviewRow[] | null;
|
|
145
|
+
/** Deep-only advisory queue of open action items past due (null in light). */
|
|
146
|
+
readonly overdueActions: readonly OverdueAction[] | null;
|
|
130
147
|
}
|
|
131
|
-
export declare const MAINTAIN_SCHEMA = "historian.maintain.
|
|
148
|
+
export declare const MAINTAIN_SCHEMA = "historian.maintain.v3";
|
|
132
149
|
/** Trigram-Jaccard bar for calling two (different-path) titles near-duplicates. */
|
|
133
150
|
export declare const DUP_TITLE_THRESHOLD = 0.75;
|
|
134
151
|
/** Stamp label incl. the 上次验证 variant (the set lint.ts STAMP_RE tests) — one
|
|
@@ -139,6 +156,10 @@ export declare const STAMP_LINE_RE: RegExp;
|
|
|
139
156
|
* (dueForReview). Matched per stamp line, never page-wide — "baseline" is a
|
|
140
157
|
* common GPU-benchmark noun outside a stamp. */
|
|
141
158
|
export declare const CONFESSIONAL_STAMP_RE: RegExp;
|
|
159
|
+
/** Finds open action items past due in any G1-shaped action table (header must
|
|
160
|
+
* carry 措施/期限/状态 columns). Undated (TBD) rows are skipped here — they are
|
|
161
|
+
* a different defect owned by the authoring gate, not the ageing sweep. */
|
|
162
|
+
export declare function overdueActionsOf(body: string, now: Date): Omit<OverdueAction, 'path' | 'locale'>[];
|
|
142
163
|
export declare function buildMaintainReport(input: MaintainInput, opts?: MaintainOptions): Promise<MaintainReport>;
|
|
143
164
|
/** Human report + (always) a fenced machine-readable JSON block at the END —
|
|
144
165
|
* the same MaintainReport object the tool envelope carries. */
|
package/dist/maintain.js
CHANGED
|
@@ -17,7 +17,7 @@ import { classifyGenre } from './templates/genres.js';
|
|
|
17
17
|
import { isInternalPath } from './tools/shared.js';
|
|
18
18
|
import { normalize } from './migrate-score.js';
|
|
19
19
|
// --- Constants --------------------------------------------------------------
|
|
20
|
-
export const MAINTAIN_SCHEMA = 'historian.maintain.
|
|
20
|
+
export const MAINTAIN_SCHEMA = 'historian.maintain.v3';
|
|
21
21
|
/** Trigram-Jaccard bar for calling two (different-path) titles near-duplicates. */
|
|
22
22
|
export const DUP_TITLE_THRESHOLD = 0.75;
|
|
23
23
|
const DAY_MS = 86_400_000;
|
|
@@ -49,12 +49,21 @@ const CADENCE_LABEL_RE = /^(?:复核周期|复核节奏|review[-_ ]?cadence|cade
|
|
|
49
49
|
const COMMAND_COL_RE = /^(?:命令|用法\s*\/\s*命令|复核命令|验证命令|commands?|usage\s*\/\s*commands?|re[-_ ]?check[-_ ]?commands?|verify[-_ ]?commands?)$/i;
|
|
50
50
|
const DASH_CELL_RE = /^:?-{2,}:?$/;
|
|
51
51
|
const NULLISH_CELL_RE = /^(?:—|–|-|n\/?a|待补充|todo|\?)$/i;
|
|
52
|
+
/** Action-item table column labels (header-anchored; the table is identified
|
|
53
|
+
* by carrying all three of these columns — see overdueActionsOf). */
|
|
54
|
+
const ACTION_COL_RE = /^(?:\*\*)?(?:措施|action)(?:\*\*)?$/i;
|
|
55
|
+
const DUE_COL_RE = /^(?:\*\*)?(?:期限|due|deadline)(?:\*\*)?$/i;
|
|
56
|
+
const STATUS_COL_RE = /^(?:\*\*)?(?:状态|status)(?:\*\*)?$/i;
|
|
57
|
+
/** Closed first (fail-quiet on neutral cells like 未完成), then open. */
|
|
58
|
+
const CLOSED_STATUS_RE = /已完成|^完成$|已取消|不做|done|closed|resolved|cancelled|wont.?fix/i;
|
|
59
|
+
const OPEN_STATUS_RE = /待办|进行中|todo|pending|in.?progress|open/i;
|
|
52
60
|
/** Cadence floors when a stamped page carries no parseable metadata row:
|
|
53
61
|
* G5 machine-state ledgers 7d (weekly re-run — the round-1 plan supersedes the
|
|
54
62
|
* older 30d skeleton hint), G4 concepts and G6 how-tos 90d (the G6 skeleton's
|
|
55
|
-
* own 复核周期 example "如每 90 天");
|
|
56
|
-
*
|
|
57
|
-
|
|
63
|
+
* own 复核周期 example "如每 90 天"); G1 postmortems 30d — their action items
|
|
64
|
+
* carry due dates and rot inside a quarter; G2/G3 have no cadence guidance, so
|
|
65
|
+
* the conservative quarterly 90d default applies. */
|
|
66
|
+
const GENRE_CADENCE_DAYS = { G1: 30, G5: 7, G4: 90, G6: 90 };
|
|
58
67
|
const DEFAULT_CADENCE_DAYS = 90;
|
|
59
68
|
// --- Title similarity (trigram core copied from migrate-score.ts:289, where it
|
|
60
69
|
// --- is private with a 0.95 roundtrip bar; maintain needs its own threshold) ---
|
|
@@ -340,6 +349,57 @@ function dueForReviewOf(body, genre, now) {
|
|
|
340
349
|
return null;
|
|
341
350
|
return { stampAge, cadence, verifyCommands: verifyCommandsOf(body) };
|
|
342
351
|
}
|
|
352
|
+
/** Flattens a markdown cell to one ≤80-char line for report display. */
|
|
353
|
+
function flattenCell(cell) {
|
|
354
|
+
const flat = cell.replace(/[*_`]|<[^>]*>/g, '').replace(/\s+/g, ' ').trim();
|
|
355
|
+
return flat.length > 80 ? `${flat.slice(0, 77)}…` : flat;
|
|
356
|
+
}
|
|
357
|
+
/** Finds open action items past due in any G1-shaped action table (header must
|
|
358
|
+
* carry 措施/期限/状态 columns). Undated (TBD) rows are skipped here — they are
|
|
359
|
+
* a different defect owned by the authoring gate, not the ageing sweep. */
|
|
360
|
+
export function overdueActionsOf(body, now) {
|
|
361
|
+
const hits = [];
|
|
362
|
+
const lines = body.split('\n');
|
|
363
|
+
let colAction = -1, colDue = -1, colStatus = -1, inTable = false;
|
|
364
|
+
for (const line of lines) {
|
|
365
|
+
const cells = tableCells(line);
|
|
366
|
+
if (cells === null) {
|
|
367
|
+
inTable = false;
|
|
368
|
+
colAction = colDue = colStatus = -1;
|
|
369
|
+
continue;
|
|
370
|
+
}
|
|
371
|
+
if (cells.every((c) => DASH_CELL_RE.test(c.trim())))
|
|
372
|
+
continue;
|
|
373
|
+
const a = cells.findIndex((c) => ACTION_COL_RE.test(c.trim()));
|
|
374
|
+
const d = cells.findIndex((c) => DUE_COL_RE.test(c.trim()));
|
|
375
|
+
const s = cells.findIndex((c) => STATUS_COL_RE.test(c.trim()));
|
|
376
|
+
if (a !== -1 && d !== -1 && s !== -1) {
|
|
377
|
+
colAction = a;
|
|
378
|
+
colDue = d;
|
|
379
|
+
colStatus = s;
|
|
380
|
+
inTable = true;
|
|
381
|
+
continue;
|
|
382
|
+
}
|
|
383
|
+
if (!inTable || colAction < 0 || cells.length <= Math.max(colDue, colStatus))
|
|
384
|
+
continue;
|
|
385
|
+
const status = cells[colStatus].trim();
|
|
386
|
+
if (CLOSED_STATUS_RE.test(status) || !OPEN_STATUS_RE.test(status))
|
|
387
|
+
continue;
|
|
388
|
+
const dueMatch = cells[colDue].match(ISO_DATE_RE);
|
|
389
|
+
if (dueMatch === null)
|
|
390
|
+
continue;
|
|
391
|
+
const t = Date.parse(dueMatch[0]);
|
|
392
|
+
if (Number.isNaN(t) || t >= now.getTime())
|
|
393
|
+
continue;
|
|
394
|
+
hits.push({
|
|
395
|
+
action: flattenCell(cells[colAction]),
|
|
396
|
+
due: dueMatch[0],
|
|
397
|
+
daysOverdue: Math.floor((now.getTime() - t) / DAY_MS),
|
|
398
|
+
status,
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
return hits;
|
|
402
|
+
}
|
|
343
403
|
// --- buildMaintainReport --------------------------------------------------------
|
|
344
404
|
export async function buildMaintainReport(input, opts = {}) {
|
|
345
405
|
const now = opts.now ?? new Date();
|
|
@@ -359,12 +419,14 @@ export async function buildMaintainReport(input, opts = {}) {
|
|
|
359
419
|
let redirects = { available: false, count: 0, stubs: [] };
|
|
360
420
|
let freshness = null;
|
|
361
421
|
let dueForReview = null;
|
|
422
|
+
let overdueActions = null;
|
|
362
423
|
if (deep && opts.readBody !== undefined) {
|
|
363
424
|
const readBody = opts.readBody;
|
|
364
425
|
const stubs = [];
|
|
365
426
|
const missing = [];
|
|
366
427
|
const expired = [];
|
|
367
428
|
const due = [];
|
|
429
|
+
const overdue = [];
|
|
368
430
|
let scanned = 0;
|
|
369
431
|
let unreadable = 0;
|
|
370
432
|
for (const r of kept) {
|
|
@@ -383,6 +445,8 @@ export async function buildMaintainReport(input, opts = {}) {
|
|
|
383
445
|
const dfr = dueForReviewOf(body, genre, now);
|
|
384
446
|
if (dfr !== null)
|
|
385
447
|
due.push({ path: r.path, locale: r.locale, ...dfr });
|
|
448
|
+
for (const oa of overdueActionsOf(body, now))
|
|
449
|
+
overdue.push({ path: r.path, locale: r.locale, ...oa });
|
|
386
450
|
if (!FRESHNESS_GENRES.includes(genre))
|
|
387
451
|
continue;
|
|
388
452
|
if (!STAMP_RE.test(body))
|
|
@@ -398,6 +462,14 @@ export async function buildMaintainReport(input, opts = {}) {
|
|
|
398
462
|
redirects = { available: true, count: stubs.length, stubs };
|
|
399
463
|
freshness = { scanned, unreadable, missingLastVerified: missing, expiredReviewBy: expired };
|
|
400
464
|
dueForReview = due.sort((a, b) => b.stampAge - a.stampAge || cmpStr(a.path, b.path) || cmpStr(a.locale, b.locale));
|
|
465
|
+
const repByPath = new Map();
|
|
466
|
+
const overdueSorted = overdue.sort((a, b) => cmpStr(a.path, b.path) || cmpStr(a.locale, b.locale));
|
|
467
|
+
for (const o of overdueSorted)
|
|
468
|
+
if (!repByPath.has(o.path))
|
|
469
|
+
repByPath.set(o.path, o.locale);
|
|
470
|
+
overdueActions = overdueSorted
|
|
471
|
+
.filter((o) => o.locale === repByPath.get(o.path))
|
|
472
|
+
.sort((a, b) => b.daysOverdue - a.daysOverdue || cmpStr(a.path, b.path));
|
|
401
473
|
}
|
|
402
474
|
return {
|
|
403
475
|
schema: MAINTAIN_SCHEMA,
|
|
@@ -421,6 +493,7 @@ export async function buildMaintainReport(input, opts = {}) {
|
|
|
421
493
|
sections: sectionDist(kept),
|
|
422
494
|
freshness,
|
|
423
495
|
dueForReview,
|
|
496
|
+
overdueActions,
|
|
424
497
|
};
|
|
425
498
|
}
|
|
426
499
|
// --- renderMaintainMarkdown -----------------------------------------------------
|
|
@@ -504,6 +577,13 @@ export function renderMaintainMarkdown(r) {
|
|
|
504
577
|
L.push(` - \`${d.locale}/${d.path}\` — ${why}${cmds}`);
|
|
505
578
|
}
|
|
506
579
|
}
|
|
580
|
+
if (r.overdueActions !== null) {
|
|
581
|
+
L.push('', '## 逾期行动项 Overdue action items(deep,advisory)', '');
|
|
582
|
+
L.push(`- ${fmt(r.overdueActions.length)} 条开着的行动项已过期限(孪生页按路径去重,en 优先)—仅提示,处置由人或复核协议执行`);
|
|
583
|
+
for (const o of r.overdueActions) {
|
|
584
|
+
L.push(` - \`${o.locale}/${o.path}\` — "${o.action}" 期限 ${o.due}(逾期 ${fmt(o.daysOverdue)}d,状态:${o.status})`);
|
|
585
|
+
}
|
|
586
|
+
}
|
|
507
587
|
L.push('', '## Machine-readable JSON', '', '```json', JSON.stringify(r, null, 2), '```', '');
|
|
508
588
|
return L.join('\n');
|
|
509
589
|
}
|
package/dist/migrate.js
CHANGED
|
@@ -39,8 +39,8 @@ const RULES = [
|
|
|
39
39
|
'R4 句长约束: zh sentences ≤20 chars; en sentences ≤25 words.',
|
|
40
40
|
'R5 表格判据: ≥3-field structured data → table; pairs → description list.',
|
|
41
41
|
'R6 来源列: comparison/timeline tables carry a source column.',
|
|
42
|
-
'R7
|
|
43
|
-
'R8
|
|
42
|
+
'R7 时间线四列: event timelines are exactly 时间|阶段|事件|来源.',
|
|
43
|
+
'R8 行动项八列: action items use the eight columns 措施|优先级|类型|负责人|期限|验证|跟踪|状态.',
|
|
44
44
|
];
|
|
45
45
|
export function reformatSystemFor(lang) {
|
|
46
46
|
return [
|
package/dist/templates/genres.js
CHANGED
|
@@ -188,7 +188,7 @@ export function selfReviewChecklist(genre) {
|
|
|
188
188
|
const items = [
|
|
189
189
|
{
|
|
190
190
|
id: 1,
|
|
191
|
-
label: '导言占比 10–15
|
|
191
|
+
label: '导言占比 10–15% 且 3–5 句:导言 ≈ 正文的 10–15%,每个重要小节在导言至少占一句(lead ≈10–15% of body, 3–5 sentences; every major section ≥1 sentence in lead)',
|
|
192
192
|
kind: 'content',
|
|
193
193
|
appliesTo: 'all',
|
|
194
194
|
},
|
|
@@ -212,13 +212,13 @@ export function selfReviewChecklist(genre) {
|
|
|
212
212
|
},
|
|
213
213
|
{
|
|
214
214
|
id: 5,
|
|
215
|
-
label: '
|
|
215
|
+
label: '时间线每行有阶段与来源列(触发/影响/发现/缓解/恢复),仅日志可证事实(timeline rows carry phase + source columns; log-verifiable facts only)',
|
|
216
216
|
kind: 'genre-specific',
|
|
217
217
|
appliesTo: ['G1'],
|
|
218
218
|
},
|
|
219
219
|
{
|
|
220
220
|
id: 6,
|
|
221
|
-
label: '
|
|
221
|
+
label: '行动项八列 = 措施|优先级|类型|负责人|期限|验证|跟踪|状态;元数据表带复核期限(action items: eight columns with priority + tracking; metadata carries review-by)',
|
|
222
222
|
kind: 'genre-specific',
|
|
223
223
|
appliesTo: ['G1'],
|
|
224
224
|
},
|
|
@@ -44,7 +44,10 @@ export const G1_ZH = `# 页面标题(占位:写完后替换为实际标题
|
|
|
44
44
|
| --- | --- |
|
|
45
45
|
| 影响范围 | <!-- 哪些服务/用户/区域受影响 --> |
|
|
46
46
|
| 持续时间 | <!-- 起止时间,如 2026-09-01 14:02–15:47 (UTC+8) --> |
|
|
47
|
+
| 关键时间 | <!-- 影响开始 → 被发现 → 被缓解 → 已恢复(UTC);发现延迟=被发现−影响开始 --> |
|
|
48
|
+
| 发现方式 | <!-- 告警/人工/日志回放:谁、何时、如何发现 --> |
|
|
47
49
|
| 严重度 | <!-- P0/P1/P2(或 S1–S4),并写明判定依据 --> |
|
|
50
|
+
| 复核期限 | YYYY-MM-DD <!-- 行动项回查日期;到期页进入 maintain 深扫队列 --> |
|
|
48
51
|
|
|
49
52
|
## 背景
|
|
50
53
|
|
|
@@ -52,11 +55,11 @@ export const G1_ZH = `# 页面标题(占位:写完后替换为实际标题
|
|
|
52
55
|
|
|
53
56
|
## 时间线
|
|
54
57
|
|
|
55
|
-
<!-- 只记可查证事实:以日志/告警为准,不以口述为准;相邻事件 ≠
|
|
58
|
+
<!-- 只记可查证事实:以日志/告警为准,不以口述为准;相邻事件 ≠ 因果关系。每行必须填阶段与来源列;阶段取词:触发/影响/发现/缓解/恢复。 -->
|
|
56
59
|
|
|
57
|
-
| 时间 | 事件 | 来源 |
|
|
58
|
-
| --- | --- | --- |
|
|
59
|
-
| YYYY-MM-DD HH:MM | <!-- 发生了什么 --> | <!-- 告警/日志/commit 链接 --> |
|
|
60
|
+
| 时间 | 阶段 | 事件 | 来源 |
|
|
61
|
+
| --- | --- | --- | --- |
|
|
62
|
+
| YYYY-MM-DD HH:MM | <!-- 阶段 --> | <!-- 发生了什么 --> | <!-- 告警/日志/commit 链接 --> |
|
|
60
63
|
|
|
61
64
|
## 量化影响
|
|
62
65
|
|
|
@@ -75,6 +78,8 @@ export const G1_ZH = `# 页面标题(占位:写完后替换为实际标题
|
|
|
75
78
|
4. Why: <!-- 第 4 层 -->
|
|
76
79
|
5. Why: <!-- 第 5 层:收敛到根本原因 -->
|
|
77
80
|
|
|
81
|
+
**复发检查**:<!-- 检索既往事件页:同根因/同触发面是否发生过?有则链接前例;首次则明示"未见前例"。 -->
|
|
82
|
+
|
|
78
83
|
## 处置
|
|
79
84
|
|
|
80
85
|
| 类别 | 措施 | 完成时间 |
|
|
@@ -84,11 +89,11 @@ export const G1_ZH = `# 页面标题(占位:写完后替换为实际标题
|
|
|
84
89
|
|
|
85
90
|
## 行动项
|
|
86
91
|
|
|
87
|
-
| 措施 | 类型 | 负责人 | 期限 | 验证 | 状态 |
|
|
88
|
-
| --- | --- | --- | --- | --- | --- |
|
|
89
|
-
| <!-- 做什么 --> | <!-- prevent/mitigate/process --> | <!-- 负责人 --> | YYYY-MM-DD | <!-- 如何证明已完成 --> | <!-- 待办/进行中/已完成 --> |
|
|
92
|
+
| 措施 | 优先级 | 类型 | 负责人 | 期限 | 验证 | 跟踪 | 状态 |
|
|
93
|
+
| --- | --- | --- | --- | --- | --- | --- | --- |
|
|
94
|
+
| <!-- 做什么 --> | <!-- P0/P1/P2 --> | <!-- prevent/mitigate/process --> | <!-- 负责人 --> | YYYY-MM-DD | <!-- 如何证明已完成 --> | <!-- issue/页面路径,无则 — --> | <!-- 待办/进行中/已完成 --> |
|
|
90
95
|
|
|
91
|
-
<!-- 每个根因主题至少一个 prevent
|
|
96
|
+
<!-- 每个根因主题至少一个 prevent 行动项;验证列必须可检查,否则行动项不算完成;期限列必须 ISO 日期,未定先定日期再入表(TBD 项对老化清扫永久隐形);逾期的开项由 maintain 深扫点名。 -->
|
|
92
97
|
|
|
93
98
|
## 教训
|
|
94
99
|
|
|
@@ -135,7 +140,10 @@ export const G1_EN = `# Page Title (placeholder: replace with the real title, mu
|
|
|
135
140
|
| --- | --- |
|
|
136
141
|
| Blast radius | <!-- services/users/regions affected --> |
|
|
137
142
|
| Duration | <!-- start–end, e.g. 2026-09-01 14:02–15:47 (UTC+8) --> |
|
|
143
|
+
| Key timestamps | <!-- impact start → detected → mitigated → recovered (UTC); detection lag = detected − start --> |
|
|
144
|
+
| Detected by | <!-- alert / human / log replay: who, when, how --> |
|
|
138
145
|
| Severity | <!-- P0/P1/P2 (or S1–S4) with the basis for the rating --> |
|
|
146
|
+
| Review-by | YYYY-MM-DD <!-- action-item sweep date; expired pages enter the maintain deep queue --> |
|
|
139
147
|
|
|
140
148
|
## Background
|
|
141
149
|
|
|
@@ -143,11 +151,11 @@ export const G1_EN = `# Page Title (placeholder: replace with the real title, mu
|
|
|
143
151
|
|
|
144
152
|
## Timeline
|
|
145
153
|
|
|
146
|
-
<!-- Verifiable facts only: log/alert-based, not memory-based; adjacent events ≠ causation. Every row
|
|
154
|
+
<!-- Verifiable facts only: log/alert-based, not memory-based; adjacent events ≠ causation. Every row fills the phase and source columns; phase vocabulary: trigger/impact/detection/mitigation/recovery. -->
|
|
147
155
|
|
|
148
|
-
| Time | Event | Source |
|
|
149
|
-
| --- | --- | --- |
|
|
150
|
-
| YYYY-MM-DD HH:MM | <!-- what happened --> | <!-- alert/log/commit link --> |
|
|
156
|
+
| Time | Phase | Event | Source |
|
|
157
|
+
| --- | --- | --- | --- |
|
|
158
|
+
| YYYY-MM-DD HH:MM | <!-- phase --> | <!-- what happened --> | <!-- alert/log/commit link --> |
|
|
151
159
|
|
|
152
160
|
## Quantified Impact
|
|
153
161
|
|
|
@@ -166,6 +174,8 @@ export const G1_EN = `# Page Title (placeholder: replace with the real title, mu
|
|
|
166
174
|
4. Why: <!-- layer 4 -->
|
|
167
175
|
5. Why: <!-- layer 5: converges on the root cause -->
|
|
168
176
|
|
|
177
|
+
**Recurrence check**: <!-- search prior incident pages: same root cause or trigger before? Link the precedent; if first seen, say so. -->
|
|
178
|
+
|
|
169
179
|
## Remediation
|
|
170
180
|
|
|
171
181
|
| Kind | Action | Done |
|
|
@@ -175,11 +185,11 @@ export const G1_EN = `# Page Title (placeholder: replace with the real title, mu
|
|
|
175
185
|
|
|
176
186
|
## Action Items
|
|
177
187
|
|
|
178
|
-
| Action | Type | Owner | Due | Verification | Status |
|
|
179
|
-
| --- | --- | --- | --- | --- | --- |
|
|
180
|
-
| <!-- what to do --> | <!-- prevent/mitigate/process --> | <!-- owner --> | YYYY-MM-DD | <!-- how to prove it is done --> | <!-- todo/in progress/done --> |
|
|
188
|
+
| Action | Priority | Type | Owner | Due | Verification | Tracking | Status |
|
|
189
|
+
| --- | --- | --- | --- | --- | --- | --- | --- |
|
|
190
|
+
| <!-- what to do --> | <!-- P0/P1/P2 --> | <!-- prevent/mitigate/process --> | <!-- owner --> | YYYY-MM-DD | <!-- how to prove it is done --> | <!-- issue/page link, or — --> | <!-- todo/in progress/done --> |
|
|
181
191
|
|
|
182
|
-
<!-- At least one prevent item per root-cause theme; an action item without a checkable verification is not done. -->
|
|
192
|
+
<!-- At least one prevent item per root-cause theme; an action item without a checkable verification is not done; the Due column must carry an ISO date — set a date before entering the table (TBD rows are permanently invisible to the ageing sweep); open items past due are named by the maintain deep sweep. -->
|
|
183
193
|
|
|
184
194
|
## Lessons
|
|
185
195
|
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* historian_anchor — seal a human order/approval from the engine session store
|
|
3
|
+
* into an _evidence/anchors wiki page, and verify a sealed anchor later.
|
|
4
|
+
* Core logic (store reads, hashing, verdicts) lives in ../anchor.ts; this
|
|
5
|
+
* wrapper only adds the wiki persistence leg. Evidence tier ⇒ monolingual en,
|
|
6
|
+
* unpublished-friendly, per the G1 appendix contract.
|
|
7
|
+
*/
|
|
8
|
+
import { type ToolDefinition } from '@opencode-ai/plugin';
|
|
9
|
+
import { type ToolDeps } from './shared.js';
|
|
10
|
+
export declare function makeAnchorTool(deps: ToolDeps): ToolDefinition;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* historian_anchor — seal a human order/approval from the engine session store
|
|
3
|
+
* into an _evidence/anchors wiki page, and verify a sealed anchor later.
|
|
4
|
+
* Core logic (store reads, hashing, verdicts) lives in ../anchor.ts; this
|
|
5
|
+
* wrapper only adds the wiki persistence leg. Evidence tier ⇒ monolingual en,
|
|
6
|
+
* unpublished-friendly, per the G1 appendix contract.
|
|
7
|
+
*/
|
|
8
|
+
import { tool } from '@opencode-ai/plugin';
|
|
9
|
+
import { readPage } from '../wiki/pages.read.js';
|
|
10
|
+
import { createPage } from '../wiki/pages.write.js';
|
|
11
|
+
import { errEnvelope, okJson, pageDeps, URL_MANDATE } from './shared.js';
|
|
12
|
+
import { defaultDbPath, renderSealPage, sealAnchor, verifyAnchor } from '../anchor.js';
|
|
13
|
+
const s = tool.schema;
|
|
14
|
+
const ARGS = {
|
|
15
|
+
action: s.enum(['seal', 'verify']),
|
|
16
|
+
slug: s.string().optional().describe('Evidence page name under _evidence/anchors/<slug> (default: canon-sha prefix).'),
|
|
17
|
+
session_id: s.string().optional().describe('Engine session id (ses_...).'),
|
|
18
|
+
session_title: s.string().optional().describe('Unique substring of the session title when the id is unknown.'),
|
|
19
|
+
index: s.number().int().optional().describe("Message ordinal — 1-based (matches receipt ordinal); negative counts from the end."),
|
|
20
|
+
body: s.string().optional().describe('Claimed exact body text — located by unique canonical match; repeated bodies come back body-ambiguous on purpose.'),
|
|
21
|
+
label: s.string().optional().describe('Free-form label for the seal page heading.'),
|
|
22
|
+
};
|
|
23
|
+
function extractReceipt(content) {
|
|
24
|
+
const m = content.match(/```json historian-anchor\n([\s\S]*?)\n```/);
|
|
25
|
+
if (m === null)
|
|
26
|
+
return undefined;
|
|
27
|
+
try {
|
|
28
|
+
return JSON.parse(m[1]);
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return undefined;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
export function makeAnchorTool(deps) {
|
|
35
|
+
return tool({
|
|
36
|
+
description: 'Historian anchor (g12b-3 in the memory seat): action:"seal" locates a human order/approval message in the engine session store ' +
|
|
37
|
+
'(by session_id/session_title + index or unique body match), hashes it (raw + canonical, closed normalization list) and writes an ' +
|
|
38
|
+
'_evidence/anchors/<slug> receipt page; action:"verify" re-reads the store against a sealed page and returns MATCH/MISMATCH/ABSENT with drift fields. ' +
|
|
39
|
+
'Read-only against the store; the wiki page is the durable receipt. ' + URL_MANDATE,
|
|
40
|
+
args: ARGS,
|
|
41
|
+
execute: async (raw) => {
|
|
42
|
+
const a = raw;
|
|
43
|
+
const dbPath = defaultDbPath(deps.homeDir);
|
|
44
|
+
const now = new Date().toISOString();
|
|
45
|
+
const pd = pageDeps(deps);
|
|
46
|
+
try {
|
|
47
|
+
if (a.action === 'seal') {
|
|
48
|
+
const r = sealAnchor({
|
|
49
|
+
dbPath,
|
|
50
|
+
sessionId: a.session_id,
|
|
51
|
+
sessionTitle: a.session_title,
|
|
52
|
+
index: a.index,
|
|
53
|
+
body: a.body,
|
|
54
|
+
now,
|
|
55
|
+
});
|
|
56
|
+
if ('ok' in r)
|
|
57
|
+
return errEnvelope(new Error(`anchor: ${r.error}${r.detail !== undefined ? ` — ${r.detail}` : ''}`));
|
|
58
|
+
const slug = a.slug ?? r.canon_sha256.slice(0, 12);
|
|
59
|
+
const path = `_evidence/anchors/${slug}`;
|
|
60
|
+
const created = await createPage(pd, {
|
|
61
|
+
path,
|
|
62
|
+
locale: 'en',
|
|
63
|
+
title: `Anchor seal ${slug}${a.label !== undefined ? ` — ${a.label}` : ''}`,
|
|
64
|
+
content: renderSealPage(r, a.label),
|
|
65
|
+
tags: ['anchor-seal', 'g12b-3'],
|
|
66
|
+
isPublished: true,
|
|
67
|
+
twin: false,
|
|
68
|
+
});
|
|
69
|
+
return okJson({ verdict: 'SEALED', slug, receipt: r, page: { path, pageId: created.pageId } });
|
|
70
|
+
}
|
|
71
|
+
// verify
|
|
72
|
+
if (a.slug === undefined)
|
|
73
|
+
return errEnvelope(new Error('anchor: verify needs the sealed slug'));
|
|
74
|
+
const page = await readPage(pd.client, `_evidence/anchors/${a.slug}`, 'en');
|
|
75
|
+
if (page === null)
|
|
76
|
+
return errEnvelope(new Error(`anchor: seal page absent — ${a.slug}`));
|
|
77
|
+
const stored = extractReceipt(page.content);
|
|
78
|
+
if (stored === undefined)
|
|
79
|
+
return errEnvelope(new Error(`anchor: seal page unparseable — ${a.slug}`));
|
|
80
|
+
const v = verifyAnchor(stored, { dbPath, now });
|
|
81
|
+
if ('ok' in v)
|
|
82
|
+
return errEnvelope(new Error(`anchor: ${v.error}${v.detail !== undefined ? ` — ${v.detail}` : ''}`));
|
|
83
|
+
return okJson({ verdict: v.verdict, drift: v.drift, stored: v.stored, current: v.current ?? null, page: { path: `_evidence/anchors/${a.slug}` } });
|
|
84
|
+
}
|
|
85
|
+
catch (e) {
|
|
86
|
+
return errEnvelope(e instanceof Error ? e : new Error(String(e).slice(0, 300)));
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
});
|
|
90
|
+
}
|
package/dist/tools/local.js
CHANGED
|
@@ -8,7 +8,7 @@ import { tool } from '@opencode-ai/plugin';
|
|
|
8
8
|
import { TranslateError } from '../translate.js';
|
|
9
9
|
import { buildChronology, filterRowsByPath } from '../chronology.js';
|
|
10
10
|
import { getMap, refreshMapCache, CACHE_PATH } from '../map.js';
|
|
11
|
-
import { buildMaintainReport, renderMaintainMarkdown } from '../maintain.js';
|
|
11
|
+
import { buildMaintainReport, MAINTAIN_SCHEMA, renderMaintainMarkdown } from '../maintain.js';
|
|
12
12
|
import { buildSurfaceReport, renderSurfaceMarkdown } from '../surface.js';
|
|
13
13
|
import { lintBody, statusTokenFindings } from '../lint.js';
|
|
14
14
|
import { normalizeLocale, PathValidationError } from '../wiki/locale.js';
|
|
@@ -142,7 +142,7 @@ async function runMaintain(deps, mapDeps, snapshot, deep) {
|
|
|
142
142
|
'\n';
|
|
143
143
|
return {
|
|
144
144
|
action: 'maintain',
|
|
145
|
-
schema:
|
|
145
|
+
schema: MAINTAIN_SCHEMA,
|
|
146
146
|
deep: report.deep,
|
|
147
147
|
generatedAt: report.generatedAt,
|
|
148
148
|
rowCount: report.rowCount,
|
package/dist/tools.js
CHANGED
|
@@ -16,6 +16,7 @@ import { makeUpdateTool, makeAppendTool } from './tools/write.js';
|
|
|
16
16
|
import { makeReadTool, makeSearchTool } from './tools/read.js';
|
|
17
17
|
import { makeTranslateSnippetTool, makeMapTool } from './tools/local.js';
|
|
18
18
|
import { makeDeleteTool, makeMoveTool, makeMigrateTool } from './tools/mutate.js';
|
|
19
|
+
import { makeAnchorTool } from './tools/anchor.js';
|
|
19
20
|
export function buildTools(opts, deps = {}) {
|
|
20
21
|
const homeDir = deps.homeDir ?? homedir();
|
|
21
22
|
// Translator must exist with NO injected deps (production plugin path):
|
|
@@ -39,5 +40,6 @@ export function buildTools(opts, deps = {}) {
|
|
|
39
40
|
historian_migrate: makeMigrateTool(toolDeps),
|
|
40
41
|
historian_delete: makeDeleteTool(toolDeps),
|
|
41
42
|
historian_move: makeMoveTool(toolDeps),
|
|
43
|
+
historian_anchor: makeAnchorTool(toolDeps),
|
|
42
44
|
};
|
|
43
45
|
}
|
|
@@ -104,6 +104,12 @@ export declare function createPage(deps: PageDeps, input: CreateInput): Promise<
|
|
|
104
104
|
/** Full read-modify-write: the mutation payload ALWAYS carries every mutable
|
|
105
105
|
* field from the read, merged with the patch (pitfalls #1 + #2). */
|
|
106
106
|
export declare function updatePage(deps: PageDeps, id: number, patch: UpdatePatch): Promise<UpdateResult>;
|
|
107
|
+
/** Splice `section` in front of the first trailer heading, keeping the
|
|
108
|
+
* trailer block last; tail-append (pre-B1 behavior) when there is none.
|
|
109
|
+
* Separators are normalized to exactly one blank line around the inserted
|
|
110
|
+
* section; the section body and the document's trailing newline are kept
|
|
111
|
+
* byte-identical. */
|
|
112
|
+
export declare function insertSectionRespectingTrailer(content: string, section: string): string;
|
|
107
113
|
export declare function appendSection(deps: PageDeps, path: string, locale: Locale, section: string): Promise<UpdateResult>;
|
|
108
114
|
export declare function movePage(deps: PageDeps, path: string, locale: Locale, newPath: string, newLocale?: Locale, confirm?: string): Promise<WriteResult>;
|
|
109
115
|
export declare function deletePage(deps: PageDeps, path: string, locale: Locale, confirm?: string): Promise<WriteResult>;
|
package/dist/wiki/pages.write.js
CHANGED
|
@@ -168,11 +168,34 @@ export async function updatePage(deps, id, patch) {
|
|
|
168
168
|
return { ...assertLocalePair(current.path, current.locale, deps.options.baseUrl), pageId: id, page };
|
|
169
169
|
}
|
|
170
170
|
// --- appendSection -----------------------------------------------------------
|
|
171
|
+
/** B1 (doctrine S9): trailer headings that must stay at the document tail.
|
|
172
|
+
* Closed set — exact heading text only (`^#{1,6}\s+<name>\s*$`), so
|
|
173
|
+
* "## References" or "## See Also:" never match. Matching is purely
|
|
174
|
+
* line-shaped; a fence-internal "## Notes" is out of scope of the spec. */
|
|
175
|
+
const TRAILER_HEADING_RE = /^#{1,6}\s+(?:Related Pages|Related pages|Related|See Also|See also|Notes|备注|相关页面|相关)\s*$/;
|
|
176
|
+
/** Splice `section` in front of the first trailer heading, keeping the
|
|
177
|
+
* trailer block last; tail-append (pre-B1 behavior) when there is none.
|
|
178
|
+
* Separators are normalized to exactly one blank line around the inserted
|
|
179
|
+
* section; the section body and the document's trailing newline are kept
|
|
180
|
+
* byte-identical. */
|
|
181
|
+
export function insertSectionRespectingTrailer(content, section) {
|
|
182
|
+
const lines = content.split('\n');
|
|
183
|
+
const trailerIdx = lines.findIndex((line) => TRAILER_HEADING_RE.test(line));
|
|
184
|
+
if (trailerIdx === -1)
|
|
185
|
+
return `${content}\n\n${section}`;
|
|
186
|
+
const before = lines.slice(0, trailerIdx);
|
|
187
|
+
const after = lines.slice(trailerIdx);
|
|
188
|
+
while (before.length > 0 && before[before.length - 1].trim() === '')
|
|
189
|
+
before.pop();
|
|
190
|
+
return before.length === 0
|
|
191
|
+
? `${section}\n\n${after.join('\n')}`
|
|
192
|
+
: `${before.join('\n')}\n\n${section}\n\n${after.join('\n')}`;
|
|
193
|
+
}
|
|
171
194
|
export async function appendSection(deps, path, locale, section) {
|
|
172
195
|
const page = await readPage(deps.client, path, locale);
|
|
173
196
|
if (page === null)
|
|
174
197
|
throw new PageNotFoundError(`page '${path}' (${locale}) does not exist`);
|
|
175
|
-
return updatePage(deps, page.id, { content:
|
|
198
|
+
return updatePage(deps, page.id, { content: insertSectionRespectingTrailer(page.content, section) });
|
|
176
199
|
}
|
|
177
200
|
// --- movePage / deletePage ----------------------------------------------------
|
|
178
201
|
export async function movePage(deps, path, locale, newPath, newLocale, confirm) {
|
package/package.json
CHANGED
|
@@ -175,9 +175,9 @@ G5 现状卡的硬约束:状态块是机读单行(`Active` / `Superseded-by:
|
|
|
175
175
|
|
|
176
176
|
1. 每页 H1 后紧跟**状态块**(见 SYN-10)
|
|
177
177
|
2. 尾部必须有 `## Related Pages` / `## 相关页面`(见 SYN-9)
|
|
178
|
-
3.
|
|
178
|
+
3. 时间线表四列:时间 | 阶段 | 事件 | 来源(见 SYN-7)
|
|
179
179
|
4. 对比表含来源列(见 SYN-6)
|
|
180
|
-
5.
|
|
180
|
+
5. 行动项表八列:措施 | 优先级 | 类型 | 负责人 | 期限 | 验证 | 跟踪 | 状态;G1 元数据表带复核期限(见 SYN-8)
|
|
181
181
|
6. 中文句 ≤20 字,英文句 ≤25 词(见 SYN-4)
|
|
182
182
|
7. ≥3 字段入表(见 SYN-5)
|
|
183
183
|
8. 禁止 `{{toc}}`、`:::` container、YAML frontmatter
|
|
@@ -38,7 +38,7 @@ Six-step self-onboarding for pointing the historian plugin at your own Wiki.js i
|
|
|
38
38
|
|
|
39
39
|
## 5. 隐私红线与发布门 / Privacy red-lines & the pre-publish gate
|
|
40
40
|
|
|
41
|
-
-
|
|
41
|
+
- 任何进入包/文档的内容不得包含:真实主机名、真实用户路径(home 目录绝对路径,如 `~/…` 展开后的形态)、token、真实私有部署的页面标题与章节表。
|
|
42
42
|
- 硬门:`node tools/privacy-audit.mjs` 扫描 `npm pack` 全部文件(含 `dist/` 与 `skills/`)。改过任何随包文本后必须跑到 exit 0 再发布。
|
|
43
43
|
|
|
44
44
|
## 6. 机构记忆层开关与证据层 / reading-loop & capture switches, evidence tier
|
|
@@ -28,13 +28,13 @@
|
|
|
28
28
|
**固定节序**:
|
|
29
29
|
|
|
30
30
|
1. 摘要 (Summary) — 3-5 句概括事件全貌
|
|
31
|
-
2. 元数据 (Metadata) —
|
|
31
|
+
2. 元数据 (Metadata) — 日期、影响范围、严重级别、关键时间(开始→发现→缓解→恢复)、发现方式、复核期限
|
|
32
32
|
3. 背景 (Background) — 事件前的系统状态
|
|
33
|
-
4. 时间线 (Timeline) —
|
|
33
|
+
4. 时间线 (Timeline) — **四列表**:时间 | 阶段 | 事件 | 来源(阶段:触发/影响/发现/缓解/恢复)
|
|
34
34
|
5. 量化影响 (Impact) — 数字说话:持续时长、影响用户数、损失
|
|
35
|
-
6. 根因 (Root Cause) — 区分直接原因 vs 根本原因;5 Whys
|
|
35
|
+
6. 根因 (Root Cause) — 区分直接原因 vs 根本原因;5 Whys;复发检查(检索同根因前例并链接或明示未见前例)
|
|
36
36
|
7. 处置 (Remediation) — 止血 vs 根治
|
|
37
|
-
8. 行动项 (Action Items) —
|
|
37
|
+
8. 行动项 (Action Items) — **八列**:措施(行内容) | 优先级 | 类型 | 负责人 | 期限 | 验证 | 跟踪 | 状态
|
|
38
38
|
9. 教训 (Lessons Learned) — 做得好 / 做错 / 侥幸
|
|
39
39
|
10. 附录 (Appendix) — 决定性摘录(每段 ≤10 行)+ 证据页链接(`_evidence/...`)+ 外部链接(commit/PR/告警)
|
|
40
40
|
11. 相关页面 (Related Pages)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
# 写作规则
|
|
1
|
+
# 写作规则 24 条 (SYN-1..24)
|
|
2
2
|
|
|
3
|
-
> 跨文化 wiki 写作的通用合成规则。SYN-1..20 每条可在 `docs/research/cross-cultural-wiki-writing.md` 找到原始调研证据;SYN-21..23 为 v4 策展闭环新增,依据 `src/`
|
|
3
|
+
> 跨文化 wiki 写作的通用合成规则。SYN-1..20 每条可在 `docs/research/cross-cultural-wiki-writing.md` 找到原始调研证据;SYN-21..23 为 v4 策展闭环新增,依据 `src/` 已合入实现;SYN-24 由 G1 语料审计新增(更正注记惯例,事故复盘语料通行做法)。与既有认证可读性学说(R 系列)重叠处,语义以学说为唯一权威,本表只引用不复制(单一来源律)。
|
|
4
4
|
|
|
5
5
|
| # | 规则 | 要点 |
|
|
6
6
|
|---|------|------|
|
|
@@ -10,8 +10,8 @@
|
|
|
10
10
|
| SYN-4 | **句长约束** | 中文句 ≤20 字,英文句 ≤25 词。超过就拆句。 |
|
|
11
11
|
| SYN-5 | **表格判据** | ≥3 个字段的结构化数据用表格;≤2 字段用描述列表或行内文本。 |
|
|
12
12
|
| SYN-6 | **来源列** | 对比表与时间线表必须含「来源」列。无来源的断言不可信。 |
|
|
13
|
-
| SYN-7 |
|
|
14
|
-
| SYN-8 |
|
|
13
|
+
| SYN-7 | **时间线四列** | 事件时间线表固定四列:时间 \| 阶段 \| 事件 \| 来源。阶段取词:触发/影响/发现/缓解/恢复。缺来源列=不合格。 |
|
|
14
|
+
| SYN-8 | **行动项八列** | 行动项表八列:措施(行内容) \| 优先级 \| 类型 \| 负责人 \| 期限 \| 验证 \| 跟踪 \| 状态。优先级 P0–P2;期限列必须是 ISO 日期(YYYY-MM-DD),未定即先定日期再入表,禁止 TBD/未定——无日期项对老化清扫永久隐形;跟踪列指向 issue/页面路径,无则写 —;元数据表须带复核期限行。 |
|
|
15
15
|
| SYN-9 | **固定尾部** | 每页尾部必须有 `## Related Pages` / `## 相关页面` 节,挂至少一个真实链接到现存页面。 |
|
|
16
16
|
| SYN-10 | **状态块** | H1 后紧跟状态块:`> **Status**: Active | **Updated**: YYYY-MM-DD | **Scope**: 一行回答本页回答什么问题`。状态取值 `Active` / `Historical` / `Superseded`。中文页用 `状态`/`更新`/`范围`。 |
|
|
17
17
|
| SYN-11 | **无杂项筐** | 禁止「其他」「杂项」「Miscellaneous」节。归不进去的内容放别的页面或不放。 |
|
|
@@ -27,6 +27,7 @@
|
|
|
27
27
|
| SYN-21 | **撞车 advisory 必须响应** | `historian_page_create` 返回 `path exists — … prefer historian_page_update to amend it` 或 `疑似重复: … 先读再写` advisory(`src/tools/shared.ts` 的 `collisionAdvisory`)时,必须 `historian_read` 既有页后改用 `historian_page_update` 续写,禁止无视 advisory 直接重复建页。advisory 本身不拦截写入,拦截靠执行者响应——这是 GATE 环的设计(机器提示、人/agent 裁决)。 |
|
|
28
28
|
| SYN-22 | **Redirect 存根正文** | 存根正文只允许 `> Redirect: <canonical URL>` 一行,行首起始(`/^>\s*Redirect:/i` 判定),不携带其他正文。双语孪生各改一份(en→`/en/...`、zh→`/zh/...` canonical)。流程与 maintain 计数口径见 `references/genres.md` Redirect 存根规范。 |
|
|
29
29
|
| SYN-23 | **发布态流转** | capture 新建页必经 `状态: draft` → 十项自检通过 → `Active`。建页时自检 FAIL ≥3 条出 advisory `自检 N/10 未通过: … (不阻断, 发布前请补齐)`;FAIL 项用 `historian_page_update` 补齐后才可标 Active。禁止跳过自检直接把 draft 页改口成 Active。 |
|
|
30
|
+
| SYN-24 | **发表后更正注记** | 页面上线后修改事实(数字、日期、因果、行动项状态)须追加一行带日期的更正:`更正/Correction: YYYY-MM-DD — <改了什么、依据>`;纯排版/语法修改不触发。复盘页的行动项状态变化视为事实修改,一律适用。 |
|
|
30
31
|
|
|
31
32
|
## 来源
|
|
32
33
|
|