aodw-skill 0.11.0 → 0.13.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 (48) hide show
  1. package/.aodw-next/01-core/ai-knowledge-rules.md +35 -2
  2. package/.aodw-next/01-core/aodw-constitution.md +22 -3
  3. package/.aodw-next/01-core/git-discipline.md +11 -0
  4. package/.aodw-next/01-core/test-discipline.md +2 -0
  5. package/.aodw-next/02-workflow/autopilot-protocol.md +4 -1
  6. package/.aodw-next/02-workflow/environment-roles.md +106 -0
  7. package/.aodw-next/02-workflow/orca-multi-session.md +4 -4
  8. package/.aodw-next/02-workflow/rt-manager.md +64 -0
  9. package/.aodw-next/02-workflow/shared-verification-host.md +103 -0
  10. package/.aodw-next/02-workflow/sub-agent-driven-profile.md +2 -1
  11. package/.aodw-next/04-auditors/aodw-development-auditor-rules.md +2 -6
  12. package/.aodw-next/04-auditors/aodw-full-auditor-rules.md +2 -6
  13. package/.aodw-next/README.md +168 -7
  14. package/.aodw-next/SKILL.md +4 -1
  15. package/.aodw-next/manifest.yaml +19 -1
  16. package/.aodw-next/templates/environments.template.md +54 -0
  17. package/.aodw-next/templates/lessons.template.md +7 -0
  18. package/.aodw-next/templates/orca-handoff-template.md +2 -1
  19. package/.aodw-next/templates/release/checklist.template.md +29 -0
  20. package/.aodw-next/templates/release/notes.template.md +22 -0
  21. package/.aodw-next/templates/release/plan.template.md +15 -0
  22. package/.aodw-next/templates/release/retro-index.template.md +8 -0
  23. package/.aodw-next/templates/release/retro-topic.template.md +33 -0
  24. package/.aodw-next/templates/rt-lite.template.md +1 -0
  25. package/.aodw-next/templates/shared-verification-host-profile.template.md +50 -0
  26. package/.aodw-next/tools/rel-plan.mjs +203 -0
  27. package/AODW_Adapters/README.md +22 -126
  28. package/AODW_Adapters/agents/AGENTS.md +11 -0
  29. package/AODW_Adapters/antigravity/.agent/rules/aodw-next.md +2 -72
  30. package/AODW_Adapters/claude/CLAUDE.md +2 -72
  31. package/AODW_Adapters/copilot/.github/copilot-instructions.md +3 -0
  32. package/AODW_Adapters/cursor/.cursor/rules/aodw-next.mdc +3 -75
  33. package/AODW_Adapters/openclaw/SKILL.md +3 -106
  34. package/README.md +60 -22
  35. package/bin/aodw.js +351 -333
  36. package/bin/commands/update.js +387 -0
  37. package/bin/commands/verify.js +420 -0
  38. package/bin/utils/lock.js +343 -0
  39. package/bin/utils/path-guard.js +449 -0
  40. package/bin/utils/release.js +36 -0
  41. package/bin/utils/tool-entries.js +506 -0
  42. package/package.json +8 -2
  43. package/.aodw-next/templates/aodw-kernel-loader-template.md +0 -71
  44. package/AODW_Adapters/cursor/.cursor/commands/README.md +0 -37
  45. package/AODW_Adapters/cursor/.cursor/rules/aodw-autopilot-continue.mdc +0 -42
  46. package/AODW_Adapters/openclaw/AGENTS.md +0 -142
  47. package/bin/processors/index.js +0 -98
  48. package/bin/update-adapters-from-template.js +0 -76
package/bin/aodw.js CHANGED
@@ -10,12 +10,13 @@ import { createRequire } from 'module';
10
10
  import { fileURLToPath } from 'url';
11
11
 
12
12
  import {
13
- AntigravityProcessor,
14
- CursorProcessor,
15
- ClaudeProcessor,
16
- OpenClawProcessor,
17
- BaseProcessor
18
- } from './processors/index.js';
13
+ checkProjectChannel,
14
+ claimProjectChannel,
15
+ entryWriteTargets,
16
+ syncToolEntries,
17
+ uninstallProject,
18
+ validateUninstallCore
19
+ } from './utils/tool-entries.js';
19
20
 
20
21
  import { serve } from './commands/serve.js';
21
22
  import { createNewRT } from './commands/new.js';
@@ -23,6 +24,33 @@ import { initTools } from './commands/init-tools.js';
23
24
  import { guardDocTrace, auditDocTrace } from './commands/trace-guard.js';
24
25
  import { enableGuardHook } from './commands/install-guard-hook.js';
25
26
  import { saveProjectConfig, saveUserConfig, getProjectConfig, getUserConfig } from './utils/config.js';
27
+ import {
28
+ LOCK_FILENAME,
29
+ assertSafeWriteTargets,
30
+ buildAndWriteLock,
31
+ collectUpstreamFiles,
32
+ hasExistingUpstreamFiles,
33
+ onDiskCorePath,
34
+ planReleaseIdentities,
35
+ replaceFileEntry,
36
+ resolveSafeFileInDir,
37
+ validateLockRelPath,
38
+ verifyCoreLock,
39
+ walkRealPath
40
+ } from './utils/lock.js';
41
+ import {
42
+ ORCA_GUIDE,
43
+ ORCA_RULE,
44
+ ORCA_UPSTREAM_FILES,
45
+ collectReleaseFiles,
46
+ readReleaseFile
47
+ } from './utils/release.js';
48
+ import {
49
+ printUpdatePreflightError,
50
+ printWriteBoundaryError,
51
+ runVerify
52
+ } from './commands/verify.js';
53
+ import { runUpdate } from './commands/update.js';
26
54
  import {
27
55
  detectTechStack,
28
56
  analyzeDirectoryStructure,
@@ -37,96 +65,23 @@ const packageJson = require('../package.json');
37
65
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
38
66
  const program = new Command();
39
67
 
40
- // AODW Next 版本 - 固定配置
41
- const CORE_DIRNAME = '.aodw-next';
68
+ // AODW Next 版本 - 默认 .aodw-next,允许通过环境变量指定仓内合法通道目录
69
+ const CORE_DIRNAME = process.env.AODW_CORE_DIR || '.aodw-next';
42
70
  const PACKAGE_NAME = packageJson.name || 'aodw-skill';
43
71
 
44
72
  process.env.AODW_CORE_DIR = CORE_DIRNAME;
45
73
  process.env.AODW_PACKAGE_NAME = PACKAGE_NAME;
46
74
 
47
- // Define source paths (Next version - fixed paths)
48
- // Support both development (from source) and production (from npm package) environments
49
- function getSourcePaths() {
50
- const packageRoot = path.join(__dirname, '..'); // cli/ or node_modules/aodw-skill/
51
-
52
- // Try npm package paths first (production)
53
- const npmCore = path.join(packageRoot, '.aodw-next');
54
- const npmAdapters = path.join(packageRoot, 'AODW_Adapters');
55
-
56
- // Try development paths (from source)
57
- const devCore = path.join(packageRoot, '../templates/.aodw-next');
58
- const devAdapters = path.join(packageRoot, '../templates/AODW_Adapters');
59
-
60
- // Use npm package paths if they exist, otherwise use development paths
61
- const SOURCE_CORE = fs.existsSync(npmCore) ? npmCore : devCore;
62
- const SOURCE_ADAPTERS = fs.existsSync(npmAdapters) ? npmAdapters : devAdapters;
63
-
64
- return { SOURCE_CORE, SOURCE_ADAPTERS };
65
- }
66
-
67
- const { SOURCE_CORE, SOURCE_ADAPTERS } = getSourcePaths();
68
- const SOURCE_TEMPLATE = path.join(SOURCE_CORE, 'templates/aodw-kernel-loader-template.md');
69
- const ORCA_RULE = '02-workflow/orca-multi-session.md';
70
- const ORCA_GUIDE = '06-project/dev-session-guide.md';
71
- const ORCA_FILES = [
72
- ORCA_RULE,
73
- 'templates/orca-handoff-template.md',
74
- 'templates/dev-session-guide-template.md',
75
- 'templates/main-session-handover-template.md'
76
- ];
75
+ // 优先使用 npm 包中的内核;源码工作区回退到发布模板。
76
+ const npmCore = path.resolve(__dirname, '../.aodw-next');
77
+ const SOURCE_CORE = fs.existsSync(npmCore) ? npmCore : path.resolve(__dirname, '../../templates/.aodw-next');
77
78
 
78
79
  program
79
80
  .version(packageJson.version)
80
81
  .description('Initialize AODW-Next in your project');
81
82
 
82
- // Helper: Install file with processor
83
- async function installFile(source, target, processorClass = BaseProcessor) {
84
- const processor = new processorClass(source, target);
85
- await processor.process();
86
- }
87
-
88
- // Helper: Recursive copy with processing
89
- async function copyRecursive(sourceDir, targetDir, processorClass, renameFn = null) {
90
- // Files to exclude from distribution (maintainer-only tools)
91
- const excludeFiles = [
92
- 'aodw-governance.md', // AODW-Next 治理检查(仅维护者)
93
- 'aodw-init.md' // 初始化(CLI 已处理)
94
- ];
95
-
96
- const entries = await fs.readdir(sourceDir, { withFileTypes: true });
97
- for (const entry of entries) {
98
- // Skip excluded files
99
- if (!entry.isDirectory() && excludeFiles.includes(entry.name)) {
100
- console.log(chalk.gray(` ⊖ 跳过 ${entry.name} (仅供维护者使用)`));
101
- continue;
102
- }
103
-
104
- const srcPath = path.join(sourceDir, entry.name);
105
- const destName = renameFn ? renameFn(entry.name) : entry.name;
106
- const destPath = path.join(targetDir, destName);
107
-
108
- if (entry.isDirectory()) {
109
- await fs.ensureDir(destPath);
110
- await copyRecursive(srcPath, destPath, processorClass, renameFn);
111
- } else {
112
- await installFile(srcPath, destPath, processorClass);
113
- }
114
- }
115
- }
116
-
117
- // Helper: Check if a file is a user-generated file (not a template)
118
- function isUserGeneratedFile(filePath, coreDir) {
119
- const relativePath = path.relative(coreDir, filePath);
120
-
121
- // User-generated files that should be preserved
122
- const userGeneratedFiles = [
123
- '06-project/ai-overview.md',
124
- '06-project/modules-index.yaml',
125
- 'tools-status.yaml'
126
- ];
127
-
128
- return userGeneratedFiles.some(pattern => relativePath === pattern || relativePath.endsWith(pattern));
129
- }
83
+ // 初始化使用的项目缺省模板不是发行上游,由 init 管理,不进入上游路径计划或锁。
84
+ const PROJECT_DEFAULTS = ['project.yaml', 'config.yaml', 'tools-status.yaml'];
130
85
 
131
86
  // Helper: Check if a file is still a template (has template markers)
132
87
  async function isTemplateFile(filePath) {
@@ -152,56 +107,113 @@ async function isTemplateFile(filePath) {
152
107
  return hasOnlyComments;
153
108
  }
154
109
 
155
- // tools-status.yaml is always user-generated if it exists
156
- if (filePath.endsWith('tools-status.yaml')) {
157
- return false; // If it exists, it's user-generated
158
- }
159
-
160
110
  return false;
161
111
  } catch (e) {
162
112
  return false;
163
113
  }
164
114
  }
165
115
 
166
- // Helper: Smart copy that preserves user-generated files
167
- async function copyCoreWithPreservation(sourceDir, targetDir, isUpdate, excluded) {
168
- const entries = await fs.readdir(sourceDir, { withFileTypes: true });
169
-
170
- for (const entry of entries) {
171
- const srcPath = path.join(sourceDir, entry.name);
172
- if (excluded.has(srcPath)) continue;
173
- const destPath = path.join(targetDir, entry.name);
174
-
175
- if (entry.isDirectory()) {
176
- await fs.ensureDir(destPath);
177
- await copyCoreWithPreservation(srcPath, destPath, isUpdate, excluded);
116
+ async function copyCoreRelease(targetCore, { releaseFiles, entries }, devEnv) {
117
+ for (const rel of releaseFiles) {
118
+ const source = path.join(SOURCE_CORE, rel);
119
+ const target = path.join(targetCore, rel);
120
+ const existing = entries.get(rel);
121
+ if ((existing !== null && existing !== rel) || (devEnv === 'none' && rel === 'manifest.yaml')) {
122
+ // 同一目录项的新版拼写也由复制计划保留;按发行文件的权限和字节写入。
123
+ const mode = (await fs.stat(source)).mode & 0o777;
124
+ replaceFileEntry(target, readReleaseFile(SOURCE_CORE, rel, devEnv), mode);
178
125
  } else {
179
- // Check if this is a user-generated file
180
- if (isUserGeneratedFile(destPath, targetDir)) {
181
- if (isUpdate) {
182
- // During update, check if file exists and is not a template
183
- if (fs.existsSync(destPath)) {
184
- const isTemplate = await isTemplateFile(destPath);
185
- if (!isTemplate) {
186
- // File exists and is user-generated, skip overwriting
187
- console.log(chalk.gray(` ⊖ 保留用户文件: ${path.relative(process.cwd(), destPath)}`));
188
- continue;
189
- } else {
190
- // File exists but is still a template, can be overwritten
191
- console.log(chalk.yellow(` ↻ 更新模板文件: ${path.relative(process.cwd(), destPath)}`));
192
- }
193
- }
194
- }
195
- // During init, always copy (first time)
196
- }
197
-
198
- // Copy the file
199
- await fs.ensureDir(path.dirname(destPath));
200
- await fs.copy(srcPath, destPath);
126
+ await fs.copy(source, target);
127
+ }
128
+ }
129
+ for (const rel of PROJECT_DEFAULTS) {
130
+ const target = path.join(targetCore, rel);
131
+ if (rel === 'tools-status.yaml' && fs.existsSync(target)) {
132
+ console.log(chalk.gray(` ⊖ 保留用户文件: ${path.relative(process.cwd(), target)}`));
133
+ } else {
134
+ await fs.copy(path.join(SOURCE_CORE, rel), target);
201
135
  }
202
136
  }
203
137
  }
204
138
 
139
+ // 在发行计划探测新增落点(需要临时目录)之前,先只读检查现存目标的归属。
140
+ function findUnregisteredTargets(coreDir, releaseFiles, lockedFiles) {
141
+ let registered;
142
+ const conflicts = [];
143
+ for (const rel of releaseFiles) {
144
+ if (Object.prototype.hasOwnProperty.call(lockedFiles, rel)) continue;
145
+ const identity = onDiskCorePath(coreDir, rel);
146
+ if (identity === null) continue;
147
+ // 锁已校验。只有请求拼写不在锁里、但目标确实存在时,才需按实际目录项身份比较。
148
+ registered ??= new Set(Object.keys(lockedFiles).map(key => onDiskCorePath(coreDir, key)));
149
+ if (!registered.has(identity)) conflicts.push(rel);
150
+ }
151
+ return conflicts;
152
+ }
153
+
154
+ function planInitRelease(core, releaseFiles) {
155
+ const options = { coreDirName: CORE_DIRNAME };
156
+ if (core.ok) return planReleaseIdentities(core.absPath, releaseFiles, options);
157
+
158
+ // absPath 是首个不存在的路径段。在其现存父目录的卷上模拟空通道,不创建或认领真实通道目录。
159
+ let held;
160
+ try {
161
+ held = fs.mkdtempSync(path.join(path.dirname(core.absPath), '.aodw-init-'));
162
+ } catch (err) {
163
+ if (!err.syscall) throw err;
164
+ return { errors: [`无法为 ${CORE_DIRNAME}/ 建立空通道探测目录:${err.message}`] };
165
+ }
166
+ let plan;
167
+ try {
168
+ plan = planReleaseIdentities(held, releaseFiles, options);
169
+ } finally {
170
+ try {
171
+ fs.rmdirSync(held);
172
+ } catch (err) {
173
+ if (!plan || !err.syscall) throw err;
174
+ plan.errors.push(`没能清除本次空通道探测目录 ${held}:${err.message}`);
175
+ }
176
+ }
177
+ return plan;
178
+ }
179
+
180
+ function planOrcaRetirement(core, releaseEntries, preflight, errors) {
181
+ const wanted = new Set(releaseEntries.values());
182
+ const retired = new Map();
183
+ for (const rel of ORCA_UPSTREAM_FILES) {
184
+ const display = `${CORE_DIRNAME}/${rel}`;
185
+ const local = resolveSafeFileInDir(core.absPath, core.realPath, rel);
186
+ if (!local.ok) {
187
+ if (local.code !== 'missing') errors.push(`不能安全移除 Orca 上游文件 (${display}):${local.reason}`);
188
+ continue;
189
+ }
190
+ const identity = onDiskCorePath(core.absPath, rel);
191
+ if (identity === null) errors.push(`不能确认 Orca 上游文件的目录项 (${display})`);
192
+ else if (!wanted.has(identity)) retired.set(identity, local.absPath);
193
+ }
194
+ if (retired.size === 0) return [];
195
+
196
+ // 用旧锁的逐项检查结果证明归属,而不是把历史文件名、目录内容或 --force 当删除授权。
197
+ const proven = new Map();
198
+ if (preflight.lock) {
199
+ const rejected = new Set(preflight.missing);
200
+ for (const item of [...preflight.boundaryErrors, ...preflight.invalidPaths, ...preflight.modified]) {
201
+ rejected.add(item.path);
202
+ }
203
+ for (const key of Object.keys(preflight.lock.files)) {
204
+ if (!validateLockRelPath(key).ok) continue;
205
+ const identity = onDiskCorePath(core.absPath, key);
206
+ if (retired.has(identity)) proven.set(identity, !proven.has(identity) && !rejected.has(key));
207
+ }
208
+ }
209
+ const removals = [];
210
+ for (const [identity, abs] of retired) {
211
+ if (proven.get(identity)) removals.push(abs);
212
+ else errors.push(`不能安全移除 Orca 上游文件 (${CORE_DIRNAME}/${identity}):无可信旧锁登记或内容已修改,请先备份并移走后重跑 init`);
213
+ }
214
+ return removals;
215
+ }
216
+
205
217
  // Helper: Return to menu pause
206
218
  async function returnToMenu() {
207
219
  console.log(); // empty line
@@ -213,7 +225,25 @@ async function returnToMenu() {
213
225
  }]);
214
226
  }
215
227
 
216
- async function runInit({ devEnv, updating = false } = {}) {
228
+ // 入口薄壳按完整集合做写前检查(含可选的 OpenClaw 入口),在任何写入之前一次查完。
229
+ function checkInstallWriteBoundary(cwd, options) {
230
+ const channel = checkProjectChannel(cwd, CORE_DIRNAME, options);
231
+ if (!channel.ok) return channel;
232
+ const targets = [
233
+ CORE_DIRNAME,
234
+ `${CORE_DIRNAME}/${LOCK_FILENAME}`,
235
+ ...PROJECT_DEFAULTS.map(rel => `${CORE_DIRNAME}/${rel}`),
236
+ `${CORE_DIRNAME}/06-project/ai-overview.md`,
237
+ `${CORE_DIRNAME}/06-project/modules-index.yaml`,
238
+ `${CORE_DIRNAME}/06-project/ai-init-prompt.md`,
239
+ `${CORE_DIRNAME}/06-project/dev-session-guide.md`,
240
+ ...collectUpstreamFiles(SOURCE_CORE).map(rel => `${CORE_DIRNAME}/${rel}`),
241
+ ...entryWriteTargets(CORE_DIRNAME, ['openclaw'])
242
+ ];
243
+ return assertSafeWriteTargets(cwd, targets);
244
+ }
245
+
246
+ async function runInit({ devEnv, force = false, confirmNewChannel = false } = {}) {
217
247
  console.log(chalk.blue('🚀 正在初始化 AODW-Next...'));
218
248
 
219
249
  // --- Safeguard: Prevent running in AODW-Next Source Repo ---
@@ -225,9 +255,78 @@ async function runInit({ devEnv, updating = false } = {}) {
225
255
  return;
226
256
  }
227
257
 
258
+ const cwd = process.cwd();
259
+ const channelOptions = { confirmNewChannel };
260
+ const boundary = checkInstallWriteBoundary(cwd, channelOptions);
261
+ if (!boundary.ok) {
262
+ printWriteBoundaryError(boundary.errors);
263
+ process.exitCode = 1;
264
+ return;
265
+ }
266
+
267
+ const targetCore = path.join(cwd, CORE_DIRNAME);
268
+ const core = walkRealPath(cwd, CORE_DIRNAME);
269
+ if (core.ok ? !core.stat.isDirectory() : core.code !== 'missing') {
270
+ printWriteBoundaryError([`${CORE_DIRNAME}/ 不是可安装的通道目录:${core.reason ?? '落点不是目录'}`]);
271
+ process.exitCode = 1;
272
+ return;
273
+ }
274
+ let preflight;
275
+ if (!force && core.ok && (fs.existsSync(path.join(targetCore, LOCK_FILENAME)) || hasExistingUpstreamFiles(targetCore))) {
276
+ preflight = verifyCoreLock(cwd, CORE_DIRNAME, { scanUntracked: false });
277
+ if (!preflight.ok) {
278
+ printUpdatePreflightError(preflight, CORE_DIRNAME, { command: 'init' });
279
+ process.exitCode = 1;
280
+ return;
281
+ }
282
+ }
283
+
228
284
  // --- Step 1: Project Identity ---
229
285
  const existingProjectConfig = getProjectConfig();
286
+ if (devEnv === undefined && (existingProjectConfig.dev_env === 'orca' || existingProjectConfig.dev_env === 'none')) {
287
+ devEnv = existingProjectConfig.dev_env;
288
+ } else if (devEnv === undefined && preflight?.ok) {
289
+ // none 不写入 project.yaml;已加锁的安装可按实际记录在提问前预检。
290
+ devEnv = preflight.lock.dev_env === 'orca' ? 'orca' : 'none';
291
+ }
292
+ let installPlan;
293
+ let previousDevEnv;
294
+ const planInstall = () => {
295
+ const releaseFiles = collectReleaseFiles(SOURCE_CORE, devEnv);
296
+ if (preflight?.ok) {
297
+ const conflicts = findUnregisteredTargets(core.absPath, releaseFiles, preflight.lock.files);
298
+ if (conflicts.length > 0) {
299
+ console.error('❌ 拒绝初始化:上游目标未登记,未写入任何文件。');
300
+ for (const rel of conflicts) console.error(` - 上游新增路径已被未登记的本地文件占用: ${CORE_DIRNAME}/${rel}`);
301
+ console.error('请先备份并移走占位后重跑 init;若明确要直接覆盖占位文件,可使用 init --force(不做备份)。');
302
+ process.exitCode = 1;
303
+ return false;
304
+ }
305
+ }
306
+ const { entries, errors } = planInitRelease(core, releaseFiles);
307
+ let removals = [];
308
+ if (errors.length === 0 && core.ok) {
309
+ const lock = walkRealPath(core.absPath, LOCK_FILENAME, { allowMissing: true });
310
+ if (!lock.ok || (lock.exists && !lock.stat.isFile())) {
311
+ errors.push(`${CORE_DIRNAME}/${LOCK_FILENAME} 不能安全写入:${lock.reason ?? '落点不是普通文件'}`);
312
+ } else if (devEnv === 'none') {
313
+ preflight ??= verifyCoreLock(cwd, CORE_DIRNAME, { scanUntracked: false });
314
+ previousDevEnv = preflight.lock?.dev_env ?? existingProjectConfig.dev_env;
315
+ if (previousDevEnv === 'orca') removals = planOrcaRetirement(core, entries, preflight, errors);
316
+ }
317
+ }
318
+ if (errors.length === 0) {
319
+ installPlan = { releaseFiles, entries, removals };
320
+ return true;
321
+ }
322
+ console.error('❌ 拒绝写入:无法安全安装发行文件或移除已停用的 Orca 文件;--force 不绕过路径和归属检查。');
323
+ for (const error of errors) console.error(` - ${error}`);
324
+ process.exitCode = 1;
325
+ return false;
326
+ };
327
+ if (devEnv !== undefined && !planInstall()) return;
230
328
  let projectName = path.basename(process.cwd());
329
+ let saveProjectName = false;
231
330
 
232
331
  // Try to get name from package.json
233
332
  try {
@@ -259,7 +358,7 @@ async function runInit({ devEnv, updating = false } = {}) {
259
358
  suffix: chalk.gray(' (提示: 如果是加入团队项目, 请先 git pull!)')
260
359
  }]);
261
360
  projectName = answers.projectName;
262
- await saveProjectConfig({ project_name: projectName });
361
+ saveProjectName = true;
263
362
  }
264
363
  } else {
265
364
  const answers = await inquirer.prompt([{
@@ -270,67 +369,54 @@ async function runInit({ devEnv, updating = false } = {}) {
270
369
  suffix: chalk.gray(' (提示: 如果是加入团队项目, 请先 git pull!)')
271
370
  }]);
272
371
  projectName = answers.projectName;
273
- await saveProjectConfig({ project_name: projectName });
372
+ saveProjectName = true;
274
373
  }
275
374
 
276
- // --- Step 2: Normalize legacy user config (no mode prompt) ---
277
- const userConfig = getUserConfig();
278
- if (userConfig.mode !== 'independent' || userConfig.server_url) {
279
- await saveUserConfig({ mode: 'independent', server_url: '' });
280
- }
375
+ // --- Step 3: Optional OpenClaw entry (the standard entry shells are always installed) ---
376
+ const { openclaw } = await inquirer.prompt([{
377
+ type: 'confirm',
378
+ name: 'openclaw',
379
+ message: '是否安装 OpenClaw 入口 (根目录 SKILL.md,选否不卸载已有入口)?',
380
+ default: false
381
+ }]);
281
382
 
282
- // --- Step 3: Platform Selection (Multi-select) ---
283
- const { platforms } = await inquirer.prompt([
284
- {
285
- type: 'checkbox',
286
- name: 'platforms',
287
- message: '选择要支持的 AI 平台 (空格选择, 回车确认):',
383
+ if (devEnv === undefined) {
384
+ ({ devEnv } = await inquirer.prompt([{
385
+ type: 'list',
386
+ name: 'devEnv',
387
+ message: '请选择开发环境:',
288
388
  choices: [
289
- { name: 'Cursor (IDE with AI)', value: 'cursor', checked: true },
290
- { name: 'Antigravity (Google Gemini)', value: 'antigravity', checked: true },
291
- { name: 'Claude Desktop', value: 'claude', checked: false },
292
- { name: 'OpenClaw (AI Agent Orchestration)', value: 'openclaw', checked: false }
389
+ { name: 'Orca 多会话协作', value: 'orca' },
390
+ { name: '其他', value: 'none' }
293
391
  ],
294
- validate: (answer) => {
295
- if (answer.length < 1) {
296
- return '必须至少选择一个平台。';
297
- }
298
- return true;
299
- }
300
- }
301
- ]);
302
-
303
- if (devEnv === undefined) {
304
- const previous = existingProjectConfig.dev_env;
305
- if (previous === 'orca' || previous === 'none') {
306
- devEnv = previous;
307
- } else if (!updating) {
308
- ({ devEnv } = await inquirer.prompt([{
309
- type: 'list',
310
- name: 'devEnv',
311
- message: '请选择开发环境:',
312
- choices: [
313
- { name: 'Orca 多会话协作', value: 'orca' },
314
- { name: '其他', value: 'none' }
315
- ],
316
- default: 'none'
317
- }]));
318
- }
392
+ default: 'none'
393
+ }]));
394
+ if (!planInstall()) return;
319
395
  }
320
396
  const useOrca = devEnv === 'orca';
321
397
 
322
- // 1. Install Core Rules (channel-aware core dir)
323
- const targetCore = path.join(process.cwd(), CORE_DIRNAME);
324
- const isUpdate = fs.existsSync(targetCore);
325
- const excluded = new Set(useOrca ? [] : ORCA_FILES.map(file => path.join(SOURCE_CORE, file)));
398
+ if (force && installPlan.releaseFiles.some(rel => installPlan.entries.get(rel) !== null)) {
399
+ console.warn(chalk.yellow('⚠️ init --force 将直接覆盖既有上游落点,不做备份。'));
400
+ }
326
401
 
327
- if (isUpdate) {
328
- console.log(chalk.blue('正在更新核心规则(保留用户生成的文件)...'));
329
- await copyCoreWithPreservation(SOURCE_CORE, targetCore, true, excluded);
330
- } else {
331
- console.log(chalk.blue('正在安装核心规则...'));
332
- await fs.copy(SOURCE_CORE, targetCore, { filter: source => !excluded.has(source) });
402
+ const claimed = claimProjectChannel(cwd, CORE_DIRNAME, channelOptions);
403
+ if (!claimed.ok) {
404
+ for (const error of claimed.errors) console.error(`❌ ${error}`);
405
+ process.exitCode = 1;
406
+ return;
333
407
  }
408
+ if (saveProjectName) await saveProjectConfig({ project_name: projectName });
409
+
410
+ // Normalize legacy user config (no mode prompt).
411
+ const userConfig = getUserConfig();
412
+ if (userConfig.mode !== 'independent' || userConfig.server_url) {
413
+ await saveUserConfig({ mode: 'independent', server_url: '' });
414
+ }
415
+
416
+ // 1. Install Core Rules (channel-aware core dir)
417
+ console.log(chalk.blue(core.ok ? '正在更新核心规则(保留用户生成的文件)...' : '正在安装核心规则...'));
418
+ await copyCoreRelease(targetCore, installPlan, devEnv);
419
+ for (const abs of installPlan.removals) await fs.unlink(abs);
334
420
 
335
421
  // 开发环境说明只留在源模板,安装产物保留原有 YAML 字节和注释。
336
422
  const projectConfigPath = path.join(targetCore, 'project.yaml');
@@ -338,16 +424,7 @@ async function runInit({ devEnv, updating = false } = {}) {
338
424
  .replace(/^# ── 开发环境(可选).*\n(?:# .+\n)+\n/m, '');
339
425
  await fs.writeFile(projectConfigPath, useOrca ? projectConfig + 'dev_env: orca\n' : projectConfig, 'utf8');
340
426
 
341
- if (!useOrca) {
342
- const manifestPath = path.join(targetCore, 'manifest.yaml');
343
- const manifest = await fs.readFile(manifestPath, 'utf8');
344
- await fs.writeFile(manifestPath, manifest.replace(/^ - id: orca-multi-session\n(?: .+\n)+\n/m, ''), 'utf8');
345
- if (existingProjectConfig.dev_env === 'orca') {
346
- for (const file of ORCA_FILES) await fs.remove(path.join(targetCore, file));
347
- }
348
- }
349
-
350
- // 2. Initialize project files from templates (for both init and update)
427
+ // 2. Initialize project files from templates (missing or still placeholders)
351
428
  console.log(chalk.blue('正在初始化项目文件...'));
352
429
  const projectDir = path.join(targetCore, '06-project');
353
430
  const aiOverviewPath = path.join(projectDir, 'ai-overview.md');
@@ -403,168 +480,86 @@ async function runInit({ devEnv, updating = false } = {}) {
403
480
  await fs.writeFile(guidePath, guide, 'utf8');
404
481
  }
405
482
 
406
- // 3. Install Adapters based on selected platforms
407
- console.log(chalk.blue('正在安装适配器...'));
408
-
409
- // Cursor
410
- if (platforms.includes('cursor')) {
411
- console.log(chalk.yellow(' • 安装 Cursor 适配器...'));
412
- const targetCursor = path.join(process.cwd(), '.cursor/rules');
413
- await fs.ensureDir(targetCursor);
414
- if (fs.existsSync(SOURCE_TEMPLATE)) {
415
- await installFile(SOURCE_TEMPLATE, path.join(targetCursor, 'aodw-next.mdc'), CursorProcessor);
483
+ // 3. Install tool entries: AGENTS.md plus one thin shell per AI tool, all pointing to AGENTS.md
484
+ console.log(chalk.blue('正在安装入口薄壳...'));
485
+ const entries = syncToolEntries(process.cwd(), {
486
+ coreDirName: CORE_DIRNAME,
487
+ devEnv,
488
+ extras: openclaw ? ['openclaw'] : []
489
+ });
490
+ if (!entries.ok) {
491
+ if (entries.code === 'io') {
492
+ console.error('❌ AODW-Next 初始化未完成:入口写入失败。');
493
+ for (const error of entries.errors) console.error(` - ${error}`);
494
+ console.error('请修复路径或权限,核对并备份项目改动后用原通道重跑 init;若尚未加锁,须显式使用 init --force。');
416
495
  } else {
417
- const sourceCursor = path.join(SOURCE_ADAPTERS, 'cursor/.cursor/rules');
418
- if (fs.existsSync(sourceCursor)) {
419
- await copyRecursive(sourceCursor, targetCursor, CursorProcessor);
420
- }
421
- }
422
-
423
- // Cursor deployment scripts
424
- const targetCursorDeploy = path.join(process.cwd(), '.cursor/deploy');
425
- await fs.ensureDir(targetCursorDeploy);
426
- const sourceCursorDeploy = path.join(SOURCE_ADAPTERS, 'cursor/.cursor/deploy');
427
- if (fs.existsSync(sourceCursorDeploy)) {
428
- await copyRecursive(sourceCursorDeploy, targetCursorDeploy, BaseProcessor);
429
- }
430
-
431
- // Cursor commands
432
- const targetCursorCommands = path.join(process.cwd(), '.cursor/commands');
433
- await fs.ensureDir(targetCursorCommands);
434
- const sourceCursorCommands = path.join(SOURCE_ADAPTERS, 'cursor/.cursor/commands');
435
- if (fs.existsSync(sourceCursorCommands)) {
436
- await copyRecursive(sourceCursorCommands, targetCursorCommands, BaseProcessor);
496
+ printWriteBoundaryError(entries.errors);
437
497
  }
498
+ process.exitCode = 1;
499
+ return;
438
500
  }
439
-
440
- // Antigravity
441
- if (platforms.includes('antigravity')) {
442
- console.log(chalk.yellow(' • 安装 Antigravity 适配器...'));
443
- const targetAgentRules = path.join(process.cwd(), '.agent/rules');
444
- await fs.ensureDir(targetAgentRules);
445
- if (fs.existsSync(SOURCE_TEMPLATE)) {
446
- await installFile(SOURCE_TEMPLATE, path.join(targetAgentRules, 'aodw-next.md'), AntigravityProcessor);
447
- } else {
448
- const sourceAodw = path.join(SOURCE_ADAPTERS, 'antigravity/.agent/rules/aodw-next.md');
449
- if (fs.existsSync(sourceAodw)) {
450
- await installFile(sourceAodw, path.join(targetAgentRules, 'aodw-next.md'), AntigravityProcessor);
501
+ for (const warning of entries.warnings) console.warn(chalk.yellow(`⚠️ ${warning}`));
502
+ for (const rel of entries.created) console.log(chalk.green(` • 已生成入口薄壳 ${rel}`));
503
+ for (const rel of entries.updated) console.log(chalk.yellow(` • 已更新入口薄壳 ${rel}`));
504
+ for (const rel of entries.kept) {
505
+ if (rel === 'AGENTS.md') {
506
+ console.log(chalk.gray(' • 沿用项目自有的 AGENTS.md(唯一规范入口,未改动)'));
507
+ if (useOrca) {
508
+ console.log(chalk.gray(` • 如需启用 Orca,请手动在 AGENTS.md 中加入 ${CORE_DIRNAME}/${ORCA_RULE} 与 ${CORE_DIRNAME}/${ORCA_GUIDE} 的引用。`));
509
+ } else if (previousDevEnv === 'orca') {
510
+ console.log(chalk.yellow(` ⚠ 切回标准流程:请手动移除 AGENTS.md 中指向已停用的 ${CORE_DIRNAME}/${ORCA_RULE} 的引用。`));
451
511
  }
452
- }
453
- }
454
-
455
- // Claude
456
- if (platforms.includes('claude')) {
457
- console.log(chalk.yellow(' • 安装 Claude 适配器...'));
458
- if (fs.existsSync(SOURCE_TEMPLATE)) {
459
- await installFile(
460
- SOURCE_TEMPLATE,
461
- path.join(process.cwd(), `.claude/CLAUDE.md`),
462
- ClaudeProcessor
463
- );
464
512
  } else {
465
- await installFile(
466
- path.join(SOURCE_ADAPTERS, 'claude/CLAUDE.md'),
467
- path.join(process.cwd(), `.claude/CLAUDE.md`),
468
- ClaudeProcessor
469
- );
470
- }
471
- }
472
-
473
- // OpenClaw
474
- if (platforms.includes('openclaw')) {
475
- console.log(chalk.yellow(' • 安装 OpenClaw 适配器...'));
476
- const sourceOpenclaw = path.join(SOURCE_ADAPTERS, 'openclaw');
477
- if (fs.existsSync(sourceOpenclaw)) {
478
- // 安装 SKILL.md
479
- await installFile(
480
- path.join(sourceOpenclaw, 'SKILL.md'),
481
- path.join(process.cwd(), 'SKILL.md'),
482
- OpenClawProcessor
483
- );
484
- // 安装 AGENTS.md
485
- await installFile(
486
- path.join(sourceOpenclaw, 'AGENTS.md'),
487
- path.join(process.cwd(), 'AGENTS.md'),
488
- OpenClawProcessor
489
- );
490
- }
491
- }
492
-
493
- if (useOrca) {
494
- const platformEntries = {
495
- cursor: ['.cursor/rules/aodw-next.mdc'],
496
- antigravity: ['.agent/rules/aodw-next.md'],
497
- claude: ['.claude/CLAUDE.md'],
498
- openclaw: ['AGENTS.md', 'SKILL.md']
499
- };
500
- for (const platform of platforms) {
501
- const prefix = platform === 'cursor' ? '@' : '';
502
- const reference = `\n本项目用 Orca 多会话协作。先读 ${prefix}${CORE_DIRNAME}/${ORCA_RULE} 和 ${prefix}${CORE_DIRNAME}/${ORCA_GUIDE}\n`;
503
- for (const entry of platformEntries[platform]) {
504
- if (fs.existsSync(entry)) await fs.appendFile(entry, reference, 'utf8');
505
- }
513
+ console.log(chalk.yellow(` ⚠ 已存在项目自有的 ${rel},保持不变;想换成 AODW 薄壳时,只迁移项目自有规则到 AGENTS.md,不要复制旧版全文 loader,再备份并移走原文件后重跑 init`));
506
514
  }
507
515
  }
508
516
 
509
517
  // 4. Enable v0 guard hook automatically in user project
510
518
  await enableGuardHook({ silent: true });
519
+ await printProjectInitPrompt({ writeFile: true });
520
+
521
+ buildAndWriteLock(targetCore, installPlan.releaseFiles, {
522
+ version: packageJson.version,
523
+ devEnv
524
+ });
511
525
 
512
526
  console.log(chalk.green('\n✅ AODW-Next 初始化成功!'));
513
527
  console.log(chalk.white(`项目: ${projectName}`));
514
- console.log(chalk.white(`平台: ${platforms.join(', ')}`));
515
-
516
- await printProjectInitPrompt({ writeFile: true });
517
- }
518
-
519
- async function runUpdate(options) {
520
- // 升级保护:先备份现有规范目录,再执行更新(copyCoreWithPreservation 仅保留
521
- // 06-project/ 与 tools-status.yaml,改过核心规则的项目需靠备份找回定制)
522
- const targetCore = path.join(process.cwd(), CORE_DIRNAME);
523
- if (fs.existsSync(targetCore)) {
524
- const stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 13); // YYYYMMDDHHmm
525
- const backupPath = path.join(process.cwd(), `${CORE_DIRNAME}.backup-${stamp}`);
526
- await fs.copy(targetCore, backupPath);
527
- console.log(chalk.yellow(`📦 升级保护:已备份现有规范到 ${path.basename(backupPath)}`));
528
- console.log(chalk.yellow(' 注意:核心规则文件会被新版覆盖(仅 06-project/ 与 tools-status.yaml 保留);'));
529
- console.log(chalk.yellow(' 若本项目定制过核心规则,请在升级后 diff 备份目录找回定制。'));
530
- }
531
- console.log(chalk.blue('🔄 正在更新 AODW-Next...'));
532
- await runInit({ ...options, updating: true });
528
+ console.log(chalk.white(`入口: AGENTS.md → CLAUDE.md、.cursor/rules/aodw-next.mdc、.agent/rules/aodw-next.md、.github/copilot-instructions.md${openclaw ? '、SKILL.md (OpenClaw)' : ''}`));
533
529
  }
534
530
 
535
531
  async function runUninstall() {
532
+ const cwd = process.cwd();
533
+ const check = validateUninstallCore(cwd, CORE_DIRNAME);
534
+ if (!check.ok) {
535
+ console.error('❌ 拒绝卸载:检测到非法通道目录或符号链接目标。');
536
+ for (const err of check.errors) console.error(` - ${err}`);
537
+ process.exitCode = 1;
538
+ return;
539
+ }
540
+
536
541
  const { confirm } = await inquirer.prompt([
537
542
  {
538
543
  type: 'confirm',
539
544
  name: 'confirm',
540
- message: `确定要卸载 AODW-Next 吗? 这将删除 ${CORE_DIRNAME} 目录(包含 ui-kit)。`,
545
+ message: `确定要卸载 AODW-Next 吗? 这将删除 ${CORE_DIRNAME} 目录(包含 ui-kit)以及由 aodw-skill 生成且未被修改的入口薄壳;项目自有的 AGENTS.md、SKILL.md 与自定义入口会保留。`,
541
546
  default: false
542
547
  }
543
548
  ]);
544
549
 
545
550
  if (confirm) {
546
- const cwd = process.cwd();
547
- await fs.remove(path.join(cwd, CORE_DIRNAME));
548
-
549
- const removeIfExists = async (filePath) => {
550
- if (fs.existsSync(filePath)) {
551
- await fs.remove(filePath);
552
- }
553
- };
554
-
555
- // Cursor
556
- await removeIfExists(path.join(cwd, '.cursor/rules', 'aodw-next.mdc'));
557
-
558
- // Antigravity (Gemini)
559
- await removeIfExists(path.join(cwd, '.agent/rules', 'aodw-next.md'));
560
-
561
- // Claude
562
- await removeIfExists(path.join(cwd, '.claude', 'CLAUDE.md'));
563
-
564
- // OpenClaw
565
- await removeIfExists(path.join(cwd, 'SKILL.md'));
566
- await removeIfExists(path.join(cwd, 'AGENTS.md'));
567
-
551
+ const result = uninstallProject(cwd, CORE_DIRNAME);
552
+ if (!result.ok) {
553
+ console.error('❌ 拒绝卸载:检测到非法通道目录或符号链接目标。');
554
+ for (const err of result.errors) console.error(` - ${err}`);
555
+ process.exitCode = 1;
556
+ return;
557
+ }
558
+ for (const warning of result.warnings) console.warn(chalk.yellow(`⚠️ ${warning}`));
559
+ for (const rel of result.removed) console.log(chalk.gray(` • 已移除入口薄壳 ${rel}`));
560
+ if (result.kept.length > 0) {
561
+ console.log(chalk.yellow(` ⚠ 以下入口不是本版生成且未修改的薄壳,已保留,请自行决定是否删除:${result.kept.join(', ')}`));
562
+ }
568
563
  console.log(chalk.green('✅ AODW-Next 已卸载。'));
569
564
  }
570
565
  }
@@ -623,7 +618,7 @@ async function printProjectInitPrompt(options = {}) {
623
618
 
624
619
  if (heading) {
625
620
  console.log(chalk.cyan('\n--- 下一步:项目深度初始化(复制到 AI 对话) ---'));
626
- console.log(chalk.gray('CLI 已完成安装与检测草稿;请让 AI 阅读真实代码后完善 06-project 文档。\n'));
621
+ console.log(chalk.gray('请让 AI 阅读真实代码后完善 06-project 文档。\n'));
627
622
  }
628
623
 
629
624
  console.log(chalk.yellow('📋 请复制以下提示词到 Cursor / Claude / Antigravity:\n'));
@@ -738,15 +733,16 @@ async function showMainMenu() {
738
733
  pageSize: 10,
739
734
  choices: [
740
735
  new inquirer.Separator('--- 核心功能 ---'),
741
- { name: '1. 初始化 / 更新 AODW-Next (在本项目)', value: 'init' },
736
+ { name: '1. 初始化 AODW-Next (在本项目:首次安装,或重跑 init 刷新入口)', value: 'init' },
737
+ { name: '2. 安全更新上游文件 (update:只改上游文件与 aodw.lock,不碰项目文件、入口与钩子)', value: 'update' },
742
738
 
743
739
  new inquirer.Separator('--- 工具箱 ---'),
744
- { name: '2. 项目深度初始化 - 生成提示词', value: 'init-overview-prompt' },
745
- { name: '3. 工具初始化 (ESLint/Ruff/Stack) - 生成提示词', value: 'init-tools-prompt' },
740
+ { name: '3. 项目深度初始化 - 生成提示词', value: 'init-overview-prompt' },
741
+ { name: '4. 工具初始化 (ESLint/Ruff/Stack) - 生成提示词', value: 'init-tools-prompt' },
746
742
 
747
743
  new inquirer.Separator('--- 帮助与维护 ---'),
748
- { name: '4. 查看帮助 & 部署指南', value: 'help' },
749
- { name: '5. 卸载 AODW-Next', value: 'uninstall' },
744
+ { name: '5. 查看帮助 & 部署指南', value: 'help' },
745
+ { name: '6. 卸载 AODW-Next', value: 'uninstall' },
750
746
  new inquirer.Separator(),
751
747
  { name: '0. 退出 (Exit)', value: 'exit' }
752
748
  ]
@@ -763,6 +759,10 @@ async function showMainMenu() {
763
759
  await runInit();
764
760
  await returnToMenu();
765
761
  break;
762
+ case 'update':
763
+ await startUpdate();
764
+ await returnToMenu();
765
+ break;
766
766
  case 'init-overview-prompt':
767
767
  await generateOverviewPrompt();
768
768
  await returnToMenu();
@@ -787,19 +787,31 @@ async function showMainMenu() {
787
787
  }
788
788
  }
789
789
 
790
+ function startUpdate({ force = false } = {}) {
791
+ return runUpdate({
792
+ coreDirName: CORE_DIRNAME,
793
+ force,
794
+ sourceCore: SOURCE_CORE,
795
+ releaseVersion: packageJson.version,
796
+ recordedDevEnv: getProjectConfig().dev_env
797
+ });
798
+ }
799
+
790
800
  // --- Commands ---
791
801
 
792
802
  program
793
803
  .command('init')
794
804
  .description('Initialize AODW-Next')
795
805
  .addOption(new Option('--dev-env <environment>', '开发环境,跳过提问').choices(['orca', 'none']))
806
+ .option('-f, --force', '直接覆盖既有上游文件和未登记占位(不做备份)')
807
+ .option('--confirm-new-channel', '确认无法识别来源的既有入口为项目预置,且没有旧安装')
796
808
  .action(runInit);
797
809
 
798
810
  program
799
811
  .command('update')
800
812
  .description('Update AODW-Next')
801
- .addOption(new Option('--dev-env <environment>', '覆盖已记录的开发环境').choices(['orca', 'none']))
802
- .action(runUpdate);
813
+ .option('-f, --force', '按新版发行模板覆盖已漂移、无锁或占位的本地文件(先备份)')
814
+ .action((options) => startUpdate({ force: options.force }));
803
815
 
804
816
  program
805
817
  .command('uninstall')
@@ -844,6 +856,12 @@ program
844
856
  .description('Install pre-commit hook to enforce AODW v0 trace guard')
845
857
  .action(enableGuardHook);
846
858
 
859
+ program
860
+ .command('verify')
861
+ .description('Verify AODW-Next upstream file integrity and tool entry references')
862
+ .option('--require-gate', 'Require executable ./gate.sh in repository root')
863
+ .action(runVerify);
864
+
847
865
 
848
866
  // Main Entry Point
849
867
  if (!process.argv.slice(2).length) {