dsh-ai-collab 0.4.4 → 0.6.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.
@@ -0,0 +1,300 @@
1
+ /**
2
+ * Discipline registry: global modules + per-project rules.
3
+ *
4
+ * Two layers, deliberately separated:
5
+ *
6
+ * - **Global** (`$DSH_HOME\disciplines\`): modules that make up the user-level
7
+ * `$DSH_HOME\AGENTS.md`. DSH injects that file into every session, so a
8
+ * module can be enabled/disabled for all projects, but a single project
9
+ * cannot opt out of it (the injection is not mediated by this plugin).
10
+ * - **Project** (`<root>\.ai\disciplines\`): rules that are rendered into the
11
+ * `generated` zone of the project `AGENTS.md` (§8). "Enabled" means the rule
12
+ * body is inlined there, so the discipline is actually in the prompt; a
13
+ * disabled rule is only listed by id and is not in effect.
14
+ *
15
+ * The global file is generated: a marker line says so, and every render backs
16
+ * up the previous content first. The plugin never rewrites a global file that
17
+ * was not produced by this renderer unless the caller explicitly migrates it.
18
+ */
19
+ import { createHash } from 'node:crypto'
20
+ import { existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync } from 'node:fs'
21
+ import { homedir } from 'node:os'
22
+ import { basename, dirname, join } from 'node:path'
23
+ import { backupFile, readText, fileStamp, writeFileAtomic } from './atomic.js'
24
+
25
+ export const GLOBAL_MARK = 'dsh-ai-collab:global:generated'
26
+ export const PROJECT_RULE_RE = /<!-- dsh-ai-collab:discipline:([a-z0-9][a-z0-9-]*):start -->\n?([\s\S]*?)<!-- dsh-ai-collab:discipline:\1:end -->/g
27
+ export const ID_RE = /^[a-z0-9][a-z0-9-]{1,40}$/
28
+
29
+ export function globalHome() {
30
+ const env = process.env.DSH_HOME
31
+ if (env) return env
32
+ return join(homedir(), '.dsh')
33
+ }
34
+
35
+ export function globalDir() { return join(globalHome(), 'disciplines') }
36
+ export function globalAgentsPath() { return join(globalHome(), 'AGENTS.md') }
37
+ export function globalRegistryPath() { return join(globalDir(), 'disciplines.json') }
38
+ export function projectDir(root) { return join(root, '.ai', 'disciplines') }
39
+ export function projectRegistryPath(root) { return join(projectDir(root), 'disciplines.json') }
40
+ export function projectRulesDir(root) { return join(projectDir(root), 'rules') }
41
+
42
+ export function hashText(text) {
43
+ return createHash('sha256').update(String(text ?? ''), 'utf8').digest('hex').slice(0, 16)
44
+ }
45
+
46
+ function readJson(path) {
47
+ try { return JSON.parse(readText(path)) } catch { return null }
48
+ }
49
+
50
+ function asArray(value) { return Array.isArray(value) ? value : [] }
51
+
52
+ /** Validate/normalise a registry object read from disk; never throws on bad rows. */
53
+ export function normaliseRegistry(raw, kind) {
54
+ const listKey = kind === 'global' ? 'modules' : 'rules'
55
+ const rows = asArray(raw?.[listKey]).map((row, index) => {
56
+ const id = String(row?.id ?? '').trim()
57
+ if (!ID_RE.test(id)) return null
58
+ const file = String(row?.file ?? `${id}.md`).replace(/\\/g, '/')
59
+ if (file.includes('..') || file.startsWith('/') || /^[a-zA-Z]:/.test(file)) return null
60
+ return {
61
+ id,
62
+ title: String(row?.title ?? id).trim() || id,
63
+ enabled: row?.enabled !== false,
64
+ priority: Number.isFinite(Number(row?.priority)) ? Number(row.priority) : index * 10,
65
+ file,
66
+ description: String(row?.description ?? '').trim(),
67
+ }
68
+ }).filter(Boolean)
69
+ // Stable order: priority, then id. Keep duplicate ids out (first wins).
70
+ const seen = new Set()
71
+ const unique = rows.filter((row) => (seen.has(row.id) ? false : (seen.add(row.id), true)))
72
+ unique.sort((a, b) => a.priority - b.priority || a.id.localeCompare(b.id))
73
+ return { version: 1, [listKey]: unique }
74
+ }
75
+
76
+ function writeRegistry(path, registry) {
77
+ writeFileAtomic(path, `${JSON.stringify(registry, null, 2)}\n`)
78
+ }
79
+
80
+ /** Parse `## N. title` sections out of an AGENTS.md that has no registry yet. */
81
+ export function parseSections(text) {
82
+ const starts = [...String(text ?? '').matchAll(/^##[ \t]+\S/gm)].map((m) => m.index)
83
+ const sections = []
84
+ for (let i = 0; i < starts.length; i += 1) {
85
+ const start = starts[i]
86
+ const end = i + 1 < starts.length ? starts[i + 1] : text.length
87
+ const body = text.slice(start, end)
88
+ const heading = body.split('\n', 1)[0].replace(/^##\s+/, '').trim()
89
+ const m = /^(\d+)[.、]/.exec(heading)
90
+ sections.push({ id: m ? `g${m[1]}` : `g${i}`, title: heading, body })
91
+ }
92
+ return sections
93
+ }
94
+
95
+ /** Load the global registry and every module body. */
96
+ export function loadGlobal() {
97
+ const dir = globalDir()
98
+ const agentsPath = globalAgentsPath()
99
+ const rawText = readText(agentsPath)
100
+ const registryRaw = readJson(globalRegistryPath())
101
+ const registry = normaliseRegistry(registryRaw ?? {}, 'global')
102
+ const generated = rawText.includes(GLOBAL_MARK)
103
+ const modules = registry.modules.map((row) => ({
104
+ ...row,
105
+ body: readText(join(dir, row.file)),
106
+ hash: hashText(readText(join(dir, row.file))),
107
+ }))
108
+ let fallback = []
109
+ if (!registryRaw && rawText) {
110
+ fallback = parseSections(rawText).map((s) => ({
111
+ id: s.id, title: s.title, enabled: true, priority: 0, file: '', body: s.body, hash: hashText(s.body),
112
+ }))
113
+ }
114
+ return { dir, agentsPath, registry, modules, fallback, generated, exists: existsSync(agentsPath) }
115
+ }
116
+
117
+ /** Load project rules and bodies. */
118
+ export function loadProject(root) {
119
+ const registry = normaliseRegistry(readJson(projectRegistryPath(root)) ?? {}, 'project')
120
+ const rules = registry.rules.map((row) => {
121
+ const body = readText(join(projectRulesDir(root), row.file))
122
+ return { ...row, body, hash: hashText(body) }
123
+ })
124
+ return { registry, rules }
125
+ }
126
+
127
+ export function renderGlobal(preamble, modules) {
128
+ const body = modules.filter((m) => m.enabled && m.body).map((m) => m.body.replace(/\s+$/, '') + '\n').join('\n')
129
+ return `${preamble.replace(/\s+$/, '')}\n\n${body}`
130
+ }
131
+
132
+ /**
133
+ * One-time migration: split the current global AGENTS.md into modules.
134
+ * Verifies that preamble + sections reproduce the original byte-for-byte
135
+ * before writing anything; the only intended diff is the generated marker.
136
+ */
137
+ export function migrateGlobal({ force = false } = {}) {
138
+ const agentsPath = globalAgentsPath()
139
+ if (!existsSync(agentsPath)) throw new Error(`找不到全局纪律文件: ${agentsPath}`)
140
+ const dir = globalDir()
141
+ if (existsSync(globalRegistryPath()) && !force) {
142
+ throw new Error(`全局纪律模块已存在: ${globalRegistryPath()}(如需重建请传 force=true,会先备份)`)
143
+ }
144
+ const originalRaw = readText(agentsPath)
145
+ // Re-running with force must not stack markers: strip the one we added last time.
146
+ const hadMarker = originalRaw.startsWith(`<!-- ${GLOBAL_MARK}`)
147
+ const original = hadMarker
148
+ ? originalRaw.slice(originalRaw.indexOf('\n') + 1)
149
+ : originalRaw
150
+ const sections = parseSections(original)
151
+ if (sections.length === 0) throw new Error('全局 AGENTS.md 中没有 “## ” 小节,无法模块化')
152
+
153
+ const firstStart = original.indexOf(sections[0].body.slice(0, 40))
154
+ const preambleRaw = firstStart > 0 ? original.slice(0, firstStart) : ''
155
+ const rebuilt = preambleRaw + sections.map((s) => s.body).join('')
156
+ if (rebuilt !== original) throw new Error('迁移自检失败:拆分后的内容无法逐字节还原原文件,已中止')
157
+
158
+ const backupDir = join(dir, '_backup')
159
+ const backup = backupFile(agentsPath, backupDir, { prefix: 'AGENTS', keep: 20 })
160
+ mkdirSync(dir, { recursive: true })
161
+
162
+ const marker = `<!-- ${GLOBAL_MARK}; 由 ai_discipline 管理,手改会在下次渲染时被覆盖 -->\n`
163
+ const preamble = marker + preambleRaw
164
+ const modules = sections.map((section, index) => {
165
+ const id = `g${index}`
166
+ const file = `${id}.md`
167
+ writeFileAtomic(join(dir, file), section.body.replace(/\s+$/, '') + '\n')
168
+ return { id, title: section.title, enabled: true, priority: index, file }
169
+ })
170
+ writeFileAtomic(join(dir, '_preamble.md'), preamble)
171
+ writeRegistry(globalRegistryPath(), { version: 1, modules })
172
+ // First migration writes the original text plus the marker only: no
173
+ // re-serialisation difference, so `git diff` is exactly one added line.
174
+ const rendered = marker + original
175
+ writeFileAtomic(agentsPath, rendered)
176
+ return {
177
+ ok: true, dir, backup, agentsPath,
178
+ modules: modules.map((m) => m.id),
179
+ bytes: Buffer.byteLength(rendered, 'utf8'),
180
+ sameAsOriginal: !hadMarker,
181
+ }
182
+ }
183
+
184
+ /** Render the global AGENTS.md from its registry (backs up first). */
185
+ export function renderGlobalFile() {
186
+ const state = loadGlobal()
187
+ if (state.modules.length === 0) throw new Error('全局纪律模块为空或注册表不可读,拒绝重写 AGENTS.md')
188
+ const preamble = readText(join(state.dir, '_preamble.md')) || `<!-- ${GLOBAL_MARK} -->\n`
189
+ const rendered = renderGlobal(preamble, state.modules)
190
+ const backup = backupFile(state.agentsPath, join(state.dir, '_backup'), { prefix: 'AGENTS', keep: 20 })
191
+ writeFileAtomic(state.agentsPath, rendered)
192
+ return { ok: true, path: state.agentsPath, backup, bytes: Buffer.byteLength(rendered, 'utf8'), enabled: state.modules.filter((m) => m.enabled).length, disabled: state.modules.filter((m) => !m.enabled).length }
193
+ }
194
+
195
+ export function setGlobalEnabled(id, enabled) {
196
+ const state = loadGlobal()
197
+ if (state.registry.modules.length === 0) throw new Error('全局纪律尚未模块化;请先执行 global-migrate')
198
+ const target = state.registry.modules.find((m) => m.id === id)
199
+ if (!target) throw new Error(`全局纪律不存在: ${id}`)
200
+ target.enabled = Boolean(enabled)
201
+ writeRegistry(globalRegistryPath(), state.registry)
202
+ return target
203
+ }
204
+
205
+ export function addGlobalModule({ id, title, body, priority }) {
206
+ if (!ID_RE.test(String(id ?? ''))) throw new Error('id 必须为 2–41 位小写字母/数字/连字符')
207
+ if (!String(title ?? '').trim()) throw new Error('global-add 需要 title')
208
+ if (!String(body ?? '').trim()) throw new Error('global-add 需要 body')
209
+ const state = loadGlobal()
210
+ if (state.registry.modules.some((m) => m.id === id)) throw new Error(`全局纪律已存在: ${id}`)
211
+ if (state.registry.modules.length === 0) throw new Error('全局纪律尚未模块化;请先执行 global-migrate')
212
+ const file = `${id}.md`
213
+ const text = `## ${String(title).trim()}\n\n${String(body).trim()}\n`
214
+ writeFileAtomic(join(state.dir, file), text)
215
+ state.registry.modules.push({
216
+ id, title: String(title).trim(), enabled: true,
217
+ priority: Number.isFinite(Number(priority)) ? Number(priority) : state.registry.modules.length * 10,
218
+ file,
219
+ })
220
+ writeRegistry(globalRegistryPath(), state.registry)
221
+ return { id, file, title: String(title).trim() }
222
+ }
223
+
224
+ export function removeGlobalModule({ id, archive = true }) {
225
+ const state = loadGlobal()
226
+ const target = state.registry.modules.find((m) => m.id === id)
227
+ if (!target) throw new Error(`全局纪律不存在: ${id}`)
228
+ state.registry.modules = state.registry.modules.filter((m) => m.id !== id)
229
+ writeRegistry(globalRegistryPath(), state.registry)
230
+ if (archive) {
231
+ const src = join(state.dir, target.file)
232
+ if (existsSync(src)) {
233
+ const destDir = join(state.dir, '_archive')
234
+ mkdirSync(destDir, { recursive: true })
235
+ renameSync(src, join(destDir, `${basename(target.file, '.md')}.${fileStamp()}.md`))
236
+ }
237
+ }
238
+ return target
239
+ }
240
+
241
+ /** Text fragments for AGENTS.md §8 (table + inlined enabled project rules). */
242
+ export function renderProjectSection(root) {
243
+ const global = loadGlobal()
244
+ const globals = global.modules.length > 0 ? global.modules : global.fallback
245
+ const project = loadProject(root)
246
+
247
+ const rows = ['| 编号 | 范围 | 纪律 | 状态 | 来源 |', '|---|---|---|---|---|']
248
+ for (const m of globals) {
249
+ const display = `G${m.id.replace(/^g/, '')}`
250
+ const source = m.file ? `$DSH_HOME\\disciplines\\${m.file.replace(/\//g, '\\')}` : '$DSH_HOME\\AGENTS.md'
251
+ rows.push(`| ${display} | 全局 | ${m.title.replace(/\|/g, '\\|')} | ${m.enabled ? '启用' : '停用'} | \`${source}\` |`)
252
+ }
253
+ for (const r of project.rules) {
254
+ const display = `P-${r.id.replace(/^p-/, '')}`
255
+ const source = `.ai\\disciplines\\rules\\${r.file.replace(/\//g, '\\')}`
256
+ rows.push(`| ${display} | 项目 | ${r.title.replace(/\|/g, '\\|')} | ${r.enabled ? '启用' : '停用'} | \`${source}\` |`)
257
+ }
258
+ if (globals.length === 0 && project.rules.length === 0) rows.push('| — | — | (暂无纪律清单) | — | — |')
259
+
260
+ const blocks = []
261
+ for (const r of project.rules) {
262
+ if (!r.enabled) continue
263
+ const display = `P-${r.id.replace(/^p-/, '')}`
264
+ const body = r.body.replace(/\s+$/, '').replace(/^#{1,3}\s+.*\n+/, '')
265
+ blocks.push(`<!-- dsh-ai-collab:discipline:${r.id}:start -->\n### ${display} · ${r.title}\n\n${body}\n<!-- dsh-ai-collab:discipline:${r.id}:end -->`)
266
+ }
267
+ return {
268
+ table: rows.join('\n'),
269
+ rules: blocks.length > 0 ? blocks.join('\n\n') : '(暂无启用的项目纪律)',
270
+ counts: { global: globals.length, project: project.rules.length, enabled: project.rules.filter((r) => r.enabled).length },
271
+ globals: globals.map((m) => ({ id: m.id, title: m.title, enabled: m.enabled, hash: m.hash || '' })),
272
+ project: project.rules.map((r) => ({ id: r.id, title: r.title, enabled: r.enabled, hash: r.hash })),
273
+ }
274
+ }
275
+
276
+ /** Compare AGENTS.md §8 against the registry; returns drift messages. */
277
+ export function auditProject(root, agentsText) {
278
+ const drift = []
279
+ const project = loadProject(root)
280
+ const present = new Set([...String(agentsText ?? '').matchAll(PROJECT_RULE_RE)].map((m) => m[1]))
281
+ for (const rule of project.rules) {
282
+ if (rule.enabled && !present.has(rule.id)) drift.push(`规则 ${rule.id} 已启用但未内联进 AGENTS.md`)
283
+ if (!rule.enabled && present.has(rule.id)) drift.push(`规则 ${rule.id} 已停用但仍内联在 AGENTS.md`)
284
+ }
285
+ for (const id of present) {
286
+ if (!project.rules.some((r) => r.id === id)) drift.push(`AGENTS.md 内联了注册表不存在的规则 ${id}`)
287
+ }
288
+ return drift
289
+ }
290
+
291
+ export function listProject(root) {
292
+ const project = loadProject(root)
293
+ const global = loadGlobal()
294
+ return {
295
+ project: project.rules.map((r) => ({ id: r.id, title: r.title, enabled: r.enabled, file: r.file, hash: r.hash })),
296
+ global: (global.modules.length ? global.modules : global.fallback).map((m) => ({ id: m.id, title: m.title, enabled: m.enabled, file: m.file, hash: m.hash || '' })),
297
+ globalGenerated: global.generated,
298
+ globalRegistry: global.modules.length > 0,
299
+ }
300
+ }
package/lib/handoff.js ADDED
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Cross-session handoff: build `.ai\SESSION_BOOT.md`, the "接棒提示词".
3
+ *
4
+ * The project already stores the two raw roles this needs:
5
+ * - event stream -> `.ai\log.jsonl` (append-only; COMMLOG role)
6
+ * - current state -> `.ai\status.json` + `.ai\TASKS.md` (TASK_BOARD role)
7
+ * What was missing is the small, deterministic boot file that tells a new
8
+ * session what to read and what to report. This module renders it from the
9
+ * existing files; it never invents facts the log/status do not contain, and it
10
+ * never asks the model to read the whole log (only the last N records).
11
+ */
12
+ import { existsSync } from 'node:fs'
13
+ import { basename, join } from 'node:path'
14
+ import { readText, writeFileAtomic } from './atomic.js'
15
+ import { listProject } from './disciplines.js'
16
+
17
+ function readJson(path) {
18
+ try { return JSON.parse(readText(path)) } catch { return null }
19
+ }
20
+
21
+ export function readRecords(root) {
22
+ const text = readText(join(root, '.ai', 'log.jsonl'))
23
+ const out = []
24
+ for (const line of text.replace(/\r\n/g, '\n').split('\n')) {
25
+ if (!line.trim()) continue
26
+ try { out.push(JSON.parse(line)) } catch { /* ai_check reports malformed rows */ }
27
+ }
28
+ return out
29
+ }
30
+
31
+ function oneLine(value, max = 220) {
32
+ const text = String(value ?? '').replace(/\s+/g, ' ').trim()
33
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text
34
+ }
35
+
36
+ function list(value) {
37
+ if (Array.isArray(value)) return value.map((v) => oneLine(v, 120)).filter(Boolean)
38
+ if (value === undefined || value === null || value === '') return []
39
+ return [oneLine(value, 120)]
40
+ }
41
+
42
+ export function buildHandoff(root, { maxTail = 10 } = {}) {
43
+ const status = readJson(join(root, '.ai', 'status.json'))
44
+ const records = readRecords(root)
45
+ const disciplines = listProject(root)
46
+ const recent = records.slice(-Math.max(1, Math.min(Number(maxTail) || 10, 50)))
47
+ return {
48
+ root,
49
+ project: status?.project || basename(root),
50
+ generatedAt: new Date().toISOString(),
51
+ hasStatus: Boolean(status),
52
+ hasLog: records.length > 0,
53
+ status: status
54
+ ? {
55
+ phase: status.phase || '',
56
+ focus: status.focus || '',
57
+ blockers: list(status.blockers),
58
+ next: list(status.next),
59
+ updated_at: status.updated_at || '',
60
+ last_log_id: status.last_log_id || '',
61
+ }
62
+ : null,
63
+ recent: recent.map((r) => ({
64
+ id: r.id || '',
65
+ ts: r.ts || '',
66
+ action: r.action || '',
67
+ status: r.status || '',
68
+ summary: oneLine(r.summary),
69
+ })),
70
+ totalRecords: records.length,
71
+ disciplines: {
72
+ global: disciplines.global.length,
73
+ globalEnabled: disciplines.global.filter((d) => d.enabled).length,
74
+ project: disciplines.project.length,
75
+ projectEnabled: disciplines.project.filter((d) => d.enabled).length,
76
+ generated: disciplines.globalGenerated,
77
+ },
78
+ paths: {
79
+ agents: join(root, 'AGENTS.md'),
80
+ status: join(root, '.ai', 'status.json'),
81
+ log: join(root, '.ai', 'log.jsonl'),
82
+ tasks: join(root, 'TASKS.md'),
83
+ boot: join(root, '.ai', 'SESSION_BOOT.md'),
84
+ disciplines: join(root, '.ai', 'disciplines', 'disciplines.json'),
85
+ },
86
+ }
87
+ }
88
+
89
+ export function renderSessionBoot(packet) {
90
+ const s = packet.status
91
+ const lines = [
92
+ '# 接棒提示词(SESSION_BOOT)',
93
+ '',
94
+ '<!-- dsh-ai-collab:session-boot:generated; 由插件自动生成,不要手改 -->',
95
+ `> 生成时间:${packet.generatedAt};项目:**${packet.project}**。`,
96
+ '> 来源:`.ai/status.json`、`.ai/log.jsonl`、`.ai/disciplines/`。',
97
+ '> 新会话请按 §1 顺序读取,然后按 §6 输出「继承摘要」,再开始本轮任务。',
98
+ '',
99
+ '## 1. 必读顺序',
100
+ '',
101
+ '1. 本文件(`SESSION_BOOT.md`);',
102
+ '2. `AGENTS.md`:§1 项目事实、§3 权限表、§8 纪律清单;',
103
+ '3. `.ai/status.json`:当前状态快照;',
104
+ `4. \`.ai/log.jsonl\` 最近 ${packet.recent.length} 条(§3 已摘录,需要细节再回读);`,
105
+ '5. `TASKS.md`(存在时):任务记录清单;',
106
+ '6. `.ai/disciplines/disciplines.json` 与启用规则(存在时)。',
107
+ '',
108
+ '## 2. 当前状态',
109
+ '',
110
+ ]
111
+ if (!s) {
112
+ lines.push('- `.ai/status.json` 缺失或不可解析:本项目可能尚未写入第一条状态。')
113
+ lines.push('- 先跑 `.ai\\llm.cmd status` 或 `ai_init`,再做判断。')
114
+ } else {
115
+ lines.push(`- 阶段:${s.phase || '(未设置)'}`)
116
+ lines.push(`- 焦点:${s.focus || '(未设置)'}`)
117
+ lines.push(`- 阻塞:${s.blockers.length ? s.blockers.map((b) => `\`${b}\``).join(';') : '无'}`)
118
+ lines.push(`- 下一步:${s.next.length ? s.next.map((n) => `\`${n}\``).join(';') : '(未设置)'}`)
119
+ lines.push(`- 最近更新:${s.updated_at || '(未知)'}${s.last_log_id ? `(记录 \`${s.last_log_id}\`)` : ''}`)
120
+ }
121
+ if (packet.disciplines.global > 0 || packet.disciplines.project > 0) {
122
+ lines.push(`- 纪律:全局 ${packet.disciplines.globalEnabled}/${packet.disciplines.global} 启用;项目 ${packet.disciplines.projectEnabled}/${packet.disciplines.project} 启用`)
123
+ }
124
+ lines.push('', `## 3. 最近记录(倒序,共 ${packet.totalRecords} 条)`, '')
125
+ if (packet.recent.length === 0) {
126
+ lines.push('(日志为空)')
127
+ } else {
128
+ lines.push('| 时间 | 类型 | 状态 | 摘要 | 记录 id |', '|---|---|---|---|---|')
129
+ for (const r of [...packet.recent].reverse()) {
130
+ lines.push(`| ${r.ts} | ${r.action} | ${r.status} | ${oneLine(r.summary, 160)} | \`${r.id}\` |`)
131
+ }
132
+ }
133
+ lines.push('', '## 4. 纪律清单', '')
134
+ if (packet.disciplines.global === 0 && packet.disciplines.project === 0) {
135
+ lines.push('(尚未配置纪律模块;见 `AGENTS.md` §8)')
136
+ } else {
137
+ lines.push(`- 全局:${packet.disciplines.global} 个模块(${packet.disciplines.globalEnabled} 个启用),见 \`$DSH_HOME\\AGENTS.md\` 与 \`$DSH_HOME\\disciplines\\\`。`)
138
+ lines.push(`- 项目:${packet.disciplines.project} 条规则(${packet.disciplines.projectEnabled} 条启用),见 \`.ai\\disciplines\\\` 与 \`AGENTS.md\` §8。`)
139
+ lines.push('- 按项目卸载的全局纪律不会被 DSH 强制执行;项目规则只有“启用并内联”才真正生效。')
140
+ }
141
+ lines.push('', '## 5. 交接提示', '')
142
+ const open = s?.next?.length ? s.next : []
143
+ const blockers = s?.blockers?.length ? s.blockers : []
144
+ if (blockers.length) lines.push(`- **先处理阻塞**:${blockers.map((b) => `\`${b}\``).join(';')}`)
145
+ if (open.length) lines.push(`- **未完成事项**:${open.map((n) => `\`${n}\``).join(';')}`)
146
+ if (!blockers.length && !open.length) lines.push('- 没有记录的阻塞或下一步;请从 `status.json` 的 `focus` 与最近记录判断。')
147
+ lines.push('- 改文件前先确认 §3 权限表;日志只追加,不覆盖历史。')
148
+ lines.push('', '## 6. 继承摘要(新会话必须输出)', '')
149
+ lines.push('用 5–8 行回答,事实必须来自上述文件:')
150
+ lines.push('1. 这个项目做什么、当前阶段是什么;')
151
+ lines.push('2. 最近 3 条记录分别做了什么(带验证结果);')
152
+ lines.push('3. 当前阻塞、风险或未完成项;')
153
+ lines.push('4. 下一步建议(1–3 条,可执行);')
154
+ lines.push('5. 需要用户确认的问题(没有就写“无”)。')
155
+ lines.push('')
156
+ return lines.join('\n')
157
+ }
158
+
159
+ export function writeSessionBoot(root, opts = {}) {
160
+ const packet = buildHandoff(root, opts)
161
+ const text = renderSessionBoot(packet)
162
+ const path = packet.paths.boot
163
+ writeFileAtomic(path, text)
164
+ return { ok: true, path, bytes: Buffer.byteLength(text, 'utf8'), records: packet.totalRecords, recent: packet.recent.length }
165
+ }
166
+
167
+ export function inheritPrompt(root) {
168
+ const boot = join(root, '.ai', 'SESSION_BOOT.md')
169
+ return `请读取项目根 \`${root}\` 下的 \`.ai/SESSION_BOOT.md\`,按其中 §1 的顺序读取文件,然后按 §6 输出「继承摘要」;在摘要末尾列出需要我确认的问题。`
170
+ }
171
+
172
+ export function sessionBootExists(root) {
173
+ return existsSync(join(root, '.ai', 'SESSION_BOOT.md'))
174
+ }
package/lib/lock.js ADDED
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Cross-process file lock.
3
+ *
4
+ * The plugin can be loaded by several sessions of the same DSH profile, and the
5
+ * framework also runs PowerShell writers (`.ai\llm.ps1`, `install.ps1`). They
6
+ * all cooperate through a lock file created with O_EXCL (`wx`): whoever creates
7
+ * it owns the critical section, everyone else waits. A crashed owner leaves the
8
+ * file behind, so a second creator may break the lock after `staleMs`.
9
+ *
10
+ * Lock files are deliberately separate per resource (log, tasks, agents,
11
+ * ensure) so a writer never waits on a lock it already holds.
12
+ */
13
+ import { closeSync, mkdirSync, openSync, statSync, unlinkSync, writeSync } from 'node:fs'
14
+ import { dirname } from 'node:path'
15
+ import { sleepSync } from './atomic.js'
16
+
17
+ function tryCreate(path) {
18
+ const fd = openSync(path, 'wx')
19
+ try {
20
+ writeSync(fd, JSON.stringify({ pid: process.pid, ts: new Date().toISOString() }))
21
+ } finally {
22
+ closeSync(fd)
23
+ }
24
+ }
25
+
26
+ function isStale(path, staleMs) {
27
+ try {
28
+ return Date.now() - statSync(path).mtimeMs > staleMs
29
+ } catch {
30
+ return false
31
+ }
32
+ }
33
+
34
+ /**
35
+ * Run `fn` while holding `lockPath`.
36
+ * Throws when the lock cannot be acquired within `timeoutMs`; `fn` errors
37
+ * propagate after the lock is released.
38
+ */
39
+ export function withLock(lockPath, fn, { timeoutMs = 15000, staleMs = 30000, retryMs = 40 } = {}) {
40
+ mkdirSync(dirname(lockPath), { recursive: true })
41
+ const deadline = Date.now() + timeoutMs
42
+ for (;;) {
43
+ try {
44
+ tryCreate(lockPath)
45
+ break
46
+ } catch (error) {
47
+ if (error.code !== 'EEXIST') throw error
48
+ if (isStale(lockPath, staleMs)) {
49
+ try { unlinkSync(lockPath) } catch { /* someone else broke it first */ }
50
+ continue
51
+ }
52
+ if (Date.now() > deadline) throw new Error(`获取锁超时(${timeoutMs}ms): ${lockPath}`)
53
+ sleepSync(retryMs)
54
+ }
55
+ }
56
+ try {
57
+ return fn()
58
+ } finally {
59
+ try { unlinkSync(lockPath) } catch { /* already gone */ }
60
+ }
61
+ }
62
+
63
+ /** Non-blocking probe used by read-only callers that should not wait. */
64
+ export function lockHeld(lockPath, staleMs = 30000) {
65
+ try {
66
+ return !isStale(lockPath, staleMs)
67
+ } catch {
68
+ return false
69
+ }
70
+ }