@namewta/skills-hub 0.1.43 → 0.1.45

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@namewta/skills-hub",
3
- "version": "0.1.43",
3
+ "version": "0.1.45",
4
4
  "description": "独立中文 Agent Skills:按领域安装,覆盖开发交付、项目知识与系统维护。",
5
5
  "type": "module",
6
6
  "bin": {
@@ -23,6 +23,8 @@
23
23
 
24
24
  `--inspect` 返回每个 remote 的实际 `name`、完整有序 `urls` 和显式 `pushUrls`,不展开推送回退值。空 URL 配置按 Git 的清空列表语义处理。`effectiveFetchUrls` 单独返回 Git 应用 `url.*.insteadOf` 后的首 fetch 目标,不写入登记形成另一份身份真源。已知等价协议改写可以通过;跨 host、owner 或 fork 的改写报告冲突,由项目 owner 明确配置真实目标后再核查。改写目标含凭据时同样拒绝输出。工具不联网验证服务器重定向或 SSH 服务端实际映射,这些仍需真实连接的独立证据。
25
25
 
26
+ 按登记查询单个项目时,`--repo ID --branch-only` 继续核实身份、实际路径和 HEAD,但不扫描未提交变更,返回 `dirty: null`。批量刷新分支可逐项调用;普通路由和派遣核查保留默认行为。
27
+
26
28
  `suggestedPrimaryRemote` 优先建议有 fetch URL 的 origin,只有一个 remote 时建议该名称,其余情况为 null,由已有用户要求决定。建议值不写回登记。
27
29
 
28
30
  v2 路由分别报告身份与登记同步状态。主 fetch 身份相符可以返回 `resolved`;remote 新增、删除,或者 urls、pushUrls 内容及顺序变化,均写入 `remoteDrift` 并令 `registryMatches: false`。这些差异交 setup 核实后更新,不能声称全部登记仍同步。旧 v1 只拥有单身份事实,返回 `registryMatches: null` 与 `registryCoverage: legacy-primary-only`,不虚构完整远端快照。
@@ -145,18 +145,18 @@ export function selectRepos(registry, query, { group = false } = {}) {
145
145
  return exact ? [exact] : registry.repos.filter(repo => (repo.aliases || []).includes(query));
146
146
  }
147
147
 
148
- function git(cwd, args, { optional = false, raw = false } = {}) {
149
- const env = { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0' };
148
+ function git(cwd, args, { optional = false, missing = [], raw = false } = {}) {
149
+ const env = { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0', GIT_NO_LAZY_FETCH: '1' };
150
150
  for (const key of ['GIT_DIR', 'GIT_COMMON_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_PREFIX', 'GIT_OBJECT_DIRECTORY', 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_CONFIG', 'GIT_CONFIG_COUNT', 'GIT_CONFIG_PARAMETERS']) delete env[key];
151
151
  const result = spawnSync('git', ['-c', 'core.fsmonitor=false', '-C', cwd, ...args], { env, encoding: 'utf8', timeout: 15_000, maxBuffer: 4 * 1024 * 1024, windowsHide: true });
152
152
  if (result.error || result.status !== 0) {
153
- if (optional && !result.error) return null;
153
+ if (!result.error && (missing.includes(result.status) || (optional && Number.isInteger(result.status)))) return null;
154
154
  fail('GIT_CHECK_FAILED', `Git 只读核查失败:${args[0]}(${result.error?.code || result.status});未执行 fetch、切分支或写入。`);
155
155
  }
156
156
  return raw ? result.stdout : result.stdout.trim();
157
157
  }
158
158
 
159
- export function inspectCheckout(inputPath) {
159
+ export function inspectCheckout(inputPath, { branchOnly = false } = {}) {
160
160
  const requestedPath = path.resolve(inputPath);
161
161
  let realPath;
162
162
  // Resolve every compared path through the native filesystem implementation;
@@ -188,9 +188,12 @@ export function inspectCheckout(inputPath) {
188
188
  return { name: remote.name, url };
189
189
  });
190
190
  const suggestedPrimaryRemote = remotes.find(remote => remote.name === 'origin' && remote.urls.length)?.name || (remotes.length === 1 && remotes[0].urls.length ? remotes[0].name : null);
191
- const head = git(actualCheckout, ['rev-parse', '--verify', 'HEAD'], { optional: true });
192
- const branch = git(actualCheckout, ['symbolic-ref', '--quiet', '--short', 'HEAD'], { optional: true });
193
- const dirty = Boolean(git(actualCheckout, ['status', '--porcelain=v1', '--untracked-files=normal']));
191
+ const head = git(actualCheckout, ['rev-parse', '--verify', '--quiet', 'HEAD'], { missing: [1] });
192
+ const branchRef = git(actualCheckout, ['symbolic-ref', '--quiet', 'HEAD'], { missing: [1], raw: true })?.replace(/\r?\n$/u, '');
193
+ if (branchRef ? !branchRef.startsWith('refs/heads/') : !head) fail('INVALID_HEAD', 'HEAD 未指向可确认的提交或本地分支。');
194
+ // A full symbolic ref is exact even when a tag shares the branch name.
195
+ const branch = branchRef?.slice('refs/heads/'.length) || null;
196
+ const dirty = branchOnly ? null : Boolean(git(actualCheckout, ['status', '--porcelain=v1', '--untracked-files=normal']));
194
197
  return {
195
198
  requestedPath, realPath, actualCheckout, gitDir, commonDir,
196
199
  isLinkedWorktree: gitDir !== commonDir,
@@ -222,11 +225,12 @@ export function resolveReference(checkout, reference) {
222
225
  return { relativePath: reference, target, realTarget, exists: present, contentsRead: false };
223
226
  }
224
227
 
225
- export function routeRepo(homeRoot, repo, { localPaths = {}, checkout, reference } = {}) {
228
+ export function routeRepo(homeRoot, repo, { localPaths = {}, checkout, reference, branchOnly = false } = {}) {
226
229
  homeRoot = homePath(homeRoot);
227
- const registeredPath = path.resolve(homeRoot, localPaths[repo.id] || repo.localPath);
230
+ const hasLocalPath = Object.hasOwn(localPaths, repo.id);
231
+ const registeredPath = path.resolve(homeRoot, hasLocalPath ? localPaths[repo.id] : repo.localPath);
228
232
  const chosenPath = checkout ? path.resolve(homeRoot, checkout) : registeredPath;
229
- const actual = inspectCheckout(chosenPath);
233
+ const actual = inspectCheckout(chosenPath, { branchOnly });
230
234
  const multiRemote = Object.hasOwn(repo, 'remotes');
231
235
  if (multiRemote) validateRemotes(repo);
232
236
  else if (typeof repo.remote !== 'string') fail('INVALID_REGISTRY', '旧登记缺少 remote;由 home-setup 核实。');
@@ -244,7 +248,7 @@ export function routeRepo(homeRoot, repo, { localPaths = {}, checkout, reference
244
248
  } else {
245
249
  if (actual.remotes.length) fail('IDENTITY_CONFLICT', `仓库 ${repo.id} 登记为本地独有,但实际配置了 remote;先由 home-setup 核实登记。`);
246
250
  if (checkout && path.resolve(chosenPath) !== path.resolve(registeredPath)) {
247
- const registered = inspectCheckout(registeredPath);
251
+ const registered = inspectCheckout(registeredPath, { branchOnly });
248
252
  if (registered.commonDir !== actual.commonDir) fail('IDENTITY_CONFLICT', '无 remote 的替代 checkout 必须由同一 Git common directory 证明,不能把另一个本地仓库视为 worktree。');
249
253
  }
250
254
  identityEvidence = { type: 'local-only', commonDir: actual.commonDir };
@@ -252,7 +256,7 @@ export function routeRepo(homeRoot, repo, { localPaths = {}, checkout, reference
252
256
  const remoteDrift = multiRemote ? compareRemotes(repo.remotes, actual.remotes) : [];
253
257
  const result = {
254
258
  status: 'resolved', repoId: repo.id, purpose: repo.purpose || '', intent: repo.intent,
255
- homeRoot, registeredPath, pathSource: checkout ? 'explicit-checkout' : localPaths[repo.id] ? 'local-path-override' : 'registry',
259
+ homeRoot, registeredPath, pathSource: checkout ? 'explicit-checkout' : hasLocalPath ? 'local-path-override' : 'registry',
256
260
  identityEvidence, ...actual, remoteDrift, registryMatches: multiRemote ? !remoteDrift.length : null, registryCoverage: multiRemote ? 'all-configured-remotes' : 'legacy-primary-only',
257
261
  contextRead: false,
258
262
  next: '由进入实际 checkout 的项目 Agent 读取 AGENTS.md、有关 .agents 资料和所需 SKILL;本结果只核对位置与入口。',
@@ -288,6 +292,7 @@ function parseArgs(argv) {
288
292
  for (let index = 0; index < argv.length; index += 1) {
289
293
  const key = argv[index];
290
294
  if (key === '--help') { options.help = true; continue; }
295
+ if (key === '--branch-only' && !options.branchOnly) { options.branchOnly = true; continue; }
291
296
  if (!['--home', '--repo', '--group', '--checkout', '--ref', '--inspect', '--expected-remote', '--check-fetch'].includes(key) || !argv[index + 1] || argv[index + 1].startsWith('--')) fail('USAGE', `未知或缺值参数:${key}`);
292
297
  if (options[key.slice(2)] !== undefined) fail('USAGE', `重复参数:${key}`);
293
298
  options[key.slice(2)] = argv[++index];
@@ -299,7 +304,7 @@ export function main(argv = process.argv.slice(2)) {
299
304
  try {
300
305
  const options = parseArgs(argv);
301
306
  if (options.help) {
302
- console.log('用法:node route.mjs --home HOME --repo ID或别名 [--checkout 路径] [--ref 相对路径]\n分组:--home HOME --group 组名;接入前:--inspect 路径 [--expected-remote URL]\n克隆前:--home HOME --check-fetch URL(只检查本机 URL 展开)\n只读本机核查;远端须在用户指定且可达的实际主机运行,不启动 Agent。');
307
+ console.log('用法:node route.mjs --home HOME --repo ID或别名 [--checkout 路径] [--ref 相对路径] [--branch-only]\n分组:--home HOME --group 组名;接入前:--inspect 路径 [--expected-remote URL]\n克隆前:--home HOME --check-fetch URL(只检查本机 URL 展开)\n只读本机核查;远端须在用户指定且可达的实际主机运行,不启动 Agent。');
303
308
  return 0;
304
309
  }
305
310
  if (options['check-fetch']) {
@@ -308,7 +313,7 @@ export function main(argv = process.argv.slice(2)) {
308
313
  return 0;
309
314
  }
310
315
  if (options.inspect) {
311
- if (options.home || options.repo || options.group || options.checkout || options.ref) fail('USAGE', '--inspect 不与登记路由参数混用。');
316
+ if (options.home || options.repo || options.group || options.checkout || options.ref || options.branchOnly) fail('USAGE', '--inspect 不与登记路由参数混用。');
312
317
  const result = inspectCheckout(options.inspect);
313
318
  if (options['expected-remote'] !== undefined) {
314
319
  const expected = normalizeRemote(options['expected-remote']);
@@ -318,6 +323,7 @@ export function main(argv = process.argv.slice(2)) {
318
323
  return 0;
319
324
  }
320
325
  if (!options.home || Boolean(options.repo) === Boolean(options.group) || options['expected-remote']) fail('USAGE', '登记路由需要 --home 以及 --repo/--group 中的一项。');
326
+ if (options.branchOnly && (!options.repo || options.checkout || options.ref)) fail('USAGE', '--branch-only 仅用于按登记路径查询单个项目,不读取 dirty 状态。');
321
327
  if (options.group && options.checkout) fail('USAGE', '一个 --checkout 不能覆盖整组仓库;分别解析准确 ID。');
322
328
  const homeRoot = homePath(options.home);
323
329
  const registry = readRegistry(homeRoot);
@@ -326,7 +332,7 @@ export function main(argv = process.argv.slice(2)) {
326
332
  if (!selected.length) { console.log(JSON.stringify({ status: 'not_found', query: options.repo || options.group })); return 3; }
327
333
  if (!options.group && selected.length > 1) { console.log(JSON.stringify({ status: 'ambiguous', candidates: selected.map(repo => ({ id: repo.id, purpose: repo.purpose, localPath: repo.localPath })) }, null, 2)); return 3; }
328
334
  const results = selected.map(repo => {
329
- try { return routeRepo(homeRoot, repo, { localPaths, checkout: options.checkout, reference: options.ref }); }
335
+ try { return routeRepo(homeRoot, repo, { localPaths, checkout: options.checkout, reference: options.ref, branchOnly: options.branchOnly }); }
330
336
  catch (error) { return { status: 'conflict', repoId: repo.id, code: error.code || 'CHECK_FAILED', message: error.message }; }
331
337
  });
332
338
  console.log(JSON.stringify(options.group ? { status: results.every(result => result.status === 'resolved') ? 'resolved' : 'partial', results } : results[0], null, 2));
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: home-setup
3
- description: 初始化 Home 及其主要入口、给已有 Home 补 Git 或白名单、换机后按登记恢复项目。用于「把这里作为 Home 管理项目」、新增或变更登记、查看或导出清单,以及保存 Home 偏好、默认派遣方式和 team。查询项目实际在哪里用 home-route;入口文档组织或长期合作原则用 home-knowledge;单独诊断异常用 home-doctor。
3
+ description: 初始化 Home 及其主要入口、给已有 Home 补 Git 或白名单、换机后按登记恢复项目。用于「把这里作为 Home 管理项目」、新增或变更登记、刷新已登记项目的当前分支、查看或导出清单,以及保存 Home 偏好、默认派遣方式和 team。查询项目实际在哪里用 home-route;入口文档组织或长期合作原则用 home-knowledge;单独诊断异常用 home-doctor。
4
4
  ---
5
5
 
6
6
  # 接入 Home 与用户配置
@@ -16,7 +16,7 @@ description: 初始化 Home 及其主要入口、给已有 Home 补 Git 或白
16
16
  | 完整初始化 Home,含已有 `.git` 的目录 | [Git 基线与换机恢复](references/git.md)、[根导航与交付](references/registry.md#根导航与交付)、[派遣与团队初始化](references/dispatch.md),有项目时读[登记方法](references/registry.md) | 本地 Git、跟踪校验、根短入口、默认派遣方式与 team、适用的登记 |
17
17
  | 给已有 Home 补 Git、检查跟踪范围、克隆 Home 后恢复项目 | [Git 基线与换机恢复](references/git.md) | 可提交的 Home 基线或逐项目恢复结果 |
18
18
  | 只补初始化派遣 | [派遣与团队初始化](references/dispatch.md) | 默认派遣方式与 Home team |
19
- | 登记、移址、解除登记或查看、导出项目清单 | [登记与入口](references/registry.md) | repos.json、按需地图 |
19
+ | 登记、移址、解除登记、刷新当前分支或查看、导出项目清单 | [登记与入口](references/registry.md) | repos.json、逐项目分支刷新结果、按需地图 |
20
20
  | 保存用户背景、偏好、派遣方式或团队 | [用户配置](references/configuration.md),涉及派遣时读[派遣与团队初始化](references/dispatch.md) | context 文档或现有 owner |
21
21
  | 验证本次所需工具或执行位置 | [环境事实](references/environment.md) | 有来源、时间、边界的能力观察 |
22
22
  | 单独要求补根导航 | [根导航与交付](references/registry.md#根导航与交付) | 根 AGENTS.md 中的 Home 入口 |
@@ -26,7 +26,7 @@ description: 初始化 Home 及其主要入口、给已有 Home 补 Git 或白
26
26
  ## 执行方法
27
27
 
28
28
  1. 确认用户指定的 Home 根,读取 `./.agents/home/AGENTS.md` 和本次有关资料,按已安装技能的方法执行。同一上下文已读同版本可复用。新会话、压缩后缺失内容、文件变化或换根时重读。读不到先只读核对根、文件和安装状态;缺失交实际安装机制补齐,入口内容需修复时交 `home-knowledge` 按授权编辑。只有缺项阻止当前行动时询问。
29
- 2. 登记项目时按准确名称调用 `home-route`,核实既有 clone、实际 checkout 与全部 remote。新登记采用 v2,保存名称、完整 URL 列表和明确的主 remote,路径写成 Home 根相对的 `./` 或 `../` 形式。旧 v1 继续读取,改写前按现场核查结果迁移。项目内部知识仍由进入项目的 Agent 读取;不移动仓库、不重新 clone、不切分支。
29
+ 2. 登记项目时按准确名称调用 `home-route`,核实既有 clone、实际 checkout 与全部 remote。新登记采用 v2,保存名称、完整 URL 列表和明确的主 remote,路径写成 Home 根相对的 `./` 或 `../` 形式;记录经现场核实的 `activeBranch`,供换机恢复。旧 v1 继续读取,改写前按现场核查结果迁移。项目内部知识仍由进入项目的 Agent 读取;不移动仓库、不重新 clone、不切分支。
30
30
  3. 按本次范围维护 Git、登记或 context。完整初始化包含根短入口的合并或复用,保留用户已有规则。领域 AGENTS 缺失时由安装器创建,已有入口的内容编辑归 `home-knowledge`。重新初始化 team 时按当前模板和用户选择重建指定团队,只询问仍待确定的默认派遣方式或 team。仅补 Git、登记、偏好或换机恢复沿用既有入口与配置。
31
31
  4. 将用户的配置意图、现场能力观察和本次实际运行证据分开。CLI、模型、推理设置和派遣技能不设固定候选枚举;未知值不传入工具。
32
32
  5. 用包内工具校验、保存,再回读所改字段、路径和作用范围。地图按需从登记生成,显式导出时才保存 `repos.md`。
@@ -222,6 +222,11 @@
222
222
  "null"
223
223
  ],
224
224
  "description": "明确选择有 urls[0] 的 remote 名称;工具校验引用存在。本地独有仓库为 null。"
225
+ },
226
+ "activeBranch": {
227
+ "type": ["string", "null"],
228
+ "pattern": "^(?![-/.]|HEAD(?![\\s\\S]))(?![\\s\\S]*(?:\\.\\.|@\\{|//|/\\.))(?![\\s\\S]*\\.lock(?:/|(?![\\s\\S])))(?![\\s\\S]*[/.](?![\\s\\S]))[^\\u0000-\\u0020\\u007f~^:?*\\[\\\\]+(?![\\s\\S])",
229
+ "description": "上次现场核实的有提交的本地检出分支,不是远端默认分支。null 表示 detached HEAD 或未有首个提交;省略表示未记录。"
225
230
  }
226
231
  },
227
232
  "allOf": [
@@ -29,6 +29,8 @@ node <本技能目录>/scripts/git.mjs apply-scope --home "<Home 根>" --expect-
29
29
 
30
30
  ## 新机克隆后使用
31
31
 
32
+ 旧机迁移前用[分支刷新](registry.md#批量刷新当前分支)更新 `repos.json`。确认要恢复的分支和提交已经可从登记主远端获取,再按用户授权提交、同步 Home 基线。刷新不替代推送分支或备份本地工作。
33
+
32
34
  在新克隆的 Home 根,使用 Git 和 Node.js 22.14+ 运行随仓工具:
33
35
 
34
36
  ```sh
@@ -41,8 +43,8 @@ node .agents/skills/home-setup/scripts/restore.mjs --home . --repo project-a --a
41
43
 
42
44
  恢复后按新机实际选择的宿主重新核验根入口和技能发现。只有确需且已有授权时,依据既有 environment 的非秘密方法重建本机薄入口;旧机文件不存在或验证等级不同均如实报告。`restore.mjs` 只恢复登记项目,不创建宿主指导文件,也不把旧机的宿主可用性外推到新机。
43
45
 
44
- 已有且核验匹配的 checkout 原地复用,报告附加远端漂移并保留当前状态。缺失项目使用登记的主 fetch URL 和远端默认分支。v2 新 checkout 按登记恢复远端名称、有序 URL 和显式 push URL;v1 使用单远端克隆,保留共享登记。克隆前检查 Git 展开的实际 fetch 身份,下载后由 `home-route` 核验再放到目标位置。项目保留独立 Git,内嵌项目须已被 Home 忽略且索引中无该路径。
46
+ 已有且核验匹配的 checkout 原地复用,报告附加远端漂移及实际分支;有记录分支时以 `branchMatches` 报告差异,不切换。缺失项目从登记主 fetch URL 克隆:有 `activeBranch` 时检出主远端同名分支,只有同名标签或缺失分支则报告 `REMOTE_BRANCH_MISSING`,不发布目标、不回退;显式 `null` 报告 `NO_RECORDED_BRANCH`。仅省略字段时沿用远端默认分支。预览不联络远端,分支是否可用由 `--apply` 核验。v2 新 checkout 按登记恢复远端名称、有序 URL 和显式 push URL;v1 使用单远端克隆,保留共享登记。克隆前检查 Git 展开的实际 fetch 身份,下载后由 `home-route` 核验再放到目标位置。项目保留独立 Git,内嵌项目须已被 Home 忽略且索引中无该路径。
45
47
 
46
- 若路径已有其他文件、与另一个登记路径重叠、始于另一个项目内部或经目录链接跳转,报告目标冲突。远端不可访问、授权缺失和本机独有项目逐项报告。其余可恢复项目继续。验证通过且已下载的项目在重跑时复用;新机的 Git/SSH 凭据从本机有效配置取得。记录的历史提交可供需要时另行定位。原会话或旧机未提交工作由原 owner 确认。
48
+ 若路径已有其他文件、与另一个登记路径重叠、始于另一个项目内部或经目录链接跳转,报告目标冲突。远端不可访问、授权缺失和本机独有项目逐项报告。其余可恢复项目继续。验证通过且已下载的项目在重跑时复用;新机的 Git/SSH 凭据从本机有效配置取得。记录的历史提交可供需要时另行定位。未推送提交、未提交文件、stash 和旧机 worktree 本身不会随分支名迁移,由原 owner 单独核实和备份。
47
49
 
48
50
  两个工具输出 JSON。`0` 表示本次检查或操作成功,`1` 表示边界冲突或部分项目无法恢复,`2` 表示用法、环境或读写失败。安装和本地检查不联络远端。只有恢复的 `--apply` 克隆缺失的项目。
@@ -5,6 +5,7 @@
5
5
  - 识别现有资料
6
6
  - 登记合同
7
7
  - 原地接入和可恢复编辑
8
+ - 批量刷新当前分支
8
9
  - 按需查看与显式导出地图
9
10
  - 本机路径与移址
10
11
  - 根导航与交付
@@ -28,6 +29,7 @@ Home 是用户选定的工作入口仓库,可以是现有 Git 仓库。默认
28
29
  | groups | 可选业务分组,分组不证明依赖 |
29
30
  | remotes | 全部已核实 remote,逐项保存 `name`、按配置顺序的 `urls` 和显式 `pushUrls`;名称唯一,不折叠镜像或上游 |
30
31
  | primaryRemote | 明确的主 remote 名称,以其 `urls[0]` 核验 fetch 身份;本地独有仓库用 `remotes: []` 和 `primaryRemote: null` |
32
+ | activeBranch | v2 可选。已核实 checkout 上有提交的本地分支名;detached HEAD 或未有首个提交时写 `null`;未核实则不猜测。仅用于换机恢复,不是远端默认分支或实时状态。 |
31
33
  | localPath | Home 根相对的默认 clone 位置,例如 `./project-a`、`../repos/project-a`;本机绝对路径进入 local.json |
32
34
  | intent | work 或 reference,仅表示用途,不是 OS 权限或修改授权 |
33
35
  | backgroundRef | 可选 Home 内相对路径;背景页由 home-knowledge 维护,不要求建页 |
@@ -48,6 +50,7 @@ Home 是用户选定的工作入口仓库,可以是现有 Git 仓库。默认
48
50
  {"name": "mirror", "urls": ["ssh://git@mirror.example.invalid/team/project-a.git"], "pushUrls": []}
49
51
  ],
50
52
  "primaryRemote": "origin",
53
+ "activeBranch": "dev",
51
54
  "localPath": "../项目 A",
52
55
  "intent": "work"
53
56
  }
@@ -73,7 +76,7 @@ Home 是用户选定的工作入口仓库,可以是现有 Git 仓库。默认
73
76
  node <本技能目录>/scripts/registry.mjs inspect --home "<Home 根>"
74
77
  ```
75
78
 
76
- 4. 从读到的完整登记和现场 `remotes` 生成 v2 候选,只改授权字段。共享路径明确写成 `./` 或 `../`,含中文和空格的目录保留原名。保存时会规范化裸相对写法,绝对路径和盘符相对路径拒绝写入共享登记。候选文件由调用方放在其已有工作位置,不要求创建 `temp/home/`。校验结构:
79
+ 4. 从读到的完整登记和现场 `remotes` 生成 v2 候选,只改授权字段。新登记用同一份 route 结果取 `activeBranch`:有 `head` 且有 `branch` 时保存原分支名;已确认 detached 或 unborn 时写 `null`。不要用远端默认分支代填。共享路径明确写成 `./` 或 `../`,含中文和空格的目录保留原名。保存时会规范化裸相对写法,绝对路径和盘符相对路径拒绝写入共享登记。候选文件由调用方放在其已有工作位置,不要求创建 `temp/home/`。校验结构:
77
80
 
78
81
  ```sh
79
82
  node <本技能目录>/scripts/registry.mjs validate --input "<候选登记.json>"
@@ -93,6 +96,19 @@ Home 是用户选定的工作入口仓库,可以是现有 Git 仓库。默认
93
96
 
94
97
  `STALE_WRITE` 表示基线变化:重新读取、合并用户新内容并验证,不自动重试旧候选。显式导出时的 `UNMANAGED_MAP` 表示手写地图占用目标:按已授权范围先保留其权威位置并接入,不覆盖自定义文档。`RECOVERY_REQUIRED` 要先核对受影响文件与来源,不能报告保存完成。
95
98
 
99
+ ## 批量刷新当前分支
100
+
101
+ 切换分支后、准备换机或提交 Home 基线前,用当前 Home 随仓的 `home-setup` 和 `home-route` 读取 v2 登记。默认扫描全部,重复 `--repo <准确 ID>` 可缩小范围:
102
+
103
+ ```sh
104
+ node .agents/skills/home-setup/scripts/refresh-branches.mjs --home .
105
+ node .agents/skills/home-setup/scripts/refresh-branches.mjs --home . --write --expect "<预览返回的 registryRevision>"
106
+ ```
107
+
108
+ 预览不写文件。刷新优先用 `local.json` 覆盖,核实所指 checkout(可为 worktree)本身是登记项目的 Git 根,不查找或猜测其他 worktree。逐项返回旧值、观察到的分支及 `checkoutState`;身份不符、路径不存在或 Git 读取失败时保留原值,其他项目继续。`primaryBranchCached: false` 只表示本机没有该主远端同名跟踪引用,不代表远端分支不存在;为 `true` 也只代表本机缓存,不能证明提交已推送或远端仍保留分支。
109
+
110
+ `--write` 重新观察并复核登记和本机路径基线,仅保存成功核实且发生变化的分支,不写地图、不 fetch、不切换分支、不暂存或提交。无变化零写入;写后回读 `repos.json`。退出码 `0` 为全部正常、`1` 为逐项部分失败(成功项仍可保存,查看 `files`)、`2` 为用法、版本、基线或全局读取/保存失败。v1 先按登记方法迁移,脚本不自动升级旧登记。
111
+
96
112
  ## 按需查看与显式导出地图
97
113
 
98
114
  需要查看项目清单时直接从当前登记生成 Markdown,输出到终端,不写文件:
@@ -0,0 +1,73 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { spawnSync } from 'node:child_process';
4
+ import { inspectRegistry, validateLocal } from './registry.mjs';
5
+ import { entry, fail, gitRoot } from './git-tools.mjs';
6
+
7
+ export function realParent(target) {
8
+ let parent = path.dirname(target);
9
+ while (!entry(parent)) {
10
+ const next = path.dirname(parent);
11
+ if (next === parent) fail('PATH_CONFLICT', '无法到达目标父目录。');
12
+ parent = next;
13
+ }
14
+ for (let current = parent; ; current = path.dirname(current)) {
15
+ if (!entry(current)?.isDirectory()) fail('PATH_CONFLICT', '目标父路径包含目录链接或非目录入口。');
16
+ if (current === path.dirname(current)) break;
17
+ }
18
+ return parent;
19
+ }
20
+
21
+ export function readCheckoutState(home) {
22
+ for (const relative of ['.agents', '.agents/home']) {
23
+ const directory = path.join(home, relative);
24
+ const stat = entry(directory);
25
+ if (stat && (!stat.isDirectory() || entry(path.join(directory, '.git')))) fail('HOME_BOUNDARY', '登记位置不是 Home 的真实资料目录。');
26
+ }
27
+ const { registry, registryRevision } = inspectRegistry(home, { includeMap: false });
28
+ if (registryRevision === 'absent') fail('MISSING_REGISTRY', '操作需要已有项目登记 repos.json。');
29
+ const localFile = path.join(home, '.agents/home/local.json');
30
+ const stat = entry(localFile);
31
+ if (stat && !stat.isFile()) fail('UNSAFE_LOCAL', 'local.json 必须是同仓普通文件。');
32
+ const localText = stat ? fs.readFileSync(localFile, 'utf8') : null;
33
+ let localPaths = {};
34
+ if (localText !== null) {
35
+ let value;
36
+ try { value = JSON.parse(localText); }
37
+ catch { fail('INVALID_LOCAL', 'local.json 无法解析。'); }
38
+ localPaths = validateLocal(value, registry).paths;
39
+ }
40
+ return { registry, registryRevision, localPaths, localText };
41
+ }
42
+
43
+ export function assertCheckoutState(home, state) {
44
+ const current = readCheckoutState(home);
45
+ if (current.registryRevision !== state.registryRevision || current.localText !== state.localText) fail('STALE_REGISTRY', '登记或本机路径在操作期间已变化,请重新预览。');
46
+ }
47
+
48
+ export function checkoutTarget(home, repo, state) {
49
+ return path.resolve(home, Object.hasOwn(state.localPaths, repo.id) ? state.localPaths[repo.id] : repo.localPath);
50
+ }
51
+
52
+ export function routeRunner(home) {
53
+ const script = path.join(home, '.agents/skills/home-route/scripts/route.mjs');
54
+ if (!entry(script)?.isFile()) fail('MISSING_HOME_ROUTE', 'Home 缺少同仓 home-route 技能本体。');
55
+ if (gitRoot(realParent(script)) !== gitRoot(home)) fail('UNSAFE_HOME_ROUTE', 'home-route 入口位于另一个 Git 仓库。');
56
+ return args => {
57
+ const result = spawnSync(process.execPath, [script, '--home', home, ...args], {
58
+ cwd: home, encoding: 'utf8', timeout: 30_000, maxBuffer: 4 * 1024 * 1024, windowsHide: true,
59
+ });
60
+ let output;
61
+ try { output = JSON.parse(result.status === 2 ? result.stderr : result.stdout); } catch { /* Report an unusable tool response below. */ }
62
+ if (result.status !== 0 || !output) fail(output?.code || 'ROUTE_FAILED', output?.message || 'home-route 未能核验目标身份。');
63
+ return output;
64
+ };
65
+ }
66
+
67
+ export function verifyCheckout(runRoute, repo, checkout, args = []) {
68
+ const result = runRoute(['--repo', repo.id, ...args]);
69
+ if (result.status !== 'resolved' || !result.requestedPathIsGitRoot || result.actualCheckout !== fs.realpathSync.native(checkout)) {
70
+ fail('PATH_CONFLICT', '目标未指向登记项目的独立 Git 根。');
71
+ }
72
+ return result;
73
+ }
@@ -0,0 +1,79 @@
1
+ #!/usr/bin/env node
2
+ import { assertCheckoutState, checkoutTarget, readCheckoutState, routeRunner, verifyCheckout } from './checkout-tools.mjs';
3
+ import { fail, git, homeRoot, inside, isDirectInvocation } from './git-tools.mjs';
4
+ import { saveRegistry, validActiveBranch, verifyExpected } from './registry.mjs';
5
+ import path from 'node:path';
6
+
7
+ export function refreshBranches(home, { ids = [], write = false, expectedRevision } = {}) {
8
+ if (!write && expectedRevision !== undefined) fail('USAGE', '--expect 仅用于 --write。');
9
+ home = homeRoot(home);
10
+ const state = readCheckoutState(home);
11
+ const { registry, registryRevision } = state;
12
+ if (registry.formatVersion !== 2) fail('MIGRATION_REQUIRED', '分支刷新只支持 v2;先核实远端并迁移旧登记。');
13
+ if (write) verifyExpected(registryRevision, expectedRevision, '登记');
14
+ if (ids.some(id => !registry.repos.some(repo => repo.id === id))) fail('UNKNOWN_REPO', '请求包含未登记的 repo ID。');
15
+
16
+ const projects = [];
17
+ const managed = ['.git', '.agents', 'temp'].map(name => path.join(home, name));
18
+ const conflictsWithHome = target => inside(target, home) || managed.some(root => inside(root, target));
19
+ const runRoute = registry.repos.length ? routeRunner(home) : null;
20
+ const repos = registry.repos.map(repo => {
21
+ if (ids.length && !ids.includes(repo.id)) return repo;
22
+ const target = checkoutTarget(home, repo, state);
23
+ const project = { id: repo.id, target, ...(Object.hasOwn(repo, 'activeBranch') ? { previousBranch: repo.activeBranch } : {}) };
24
+ projects.push(project);
25
+ try {
26
+ if (conflictsWithHome(target)) fail('PATH_CONFLICT', '登记路径与 Home 根或其管理目录重叠。');
27
+ const checkout = verifyCheckout(runRoute, repo, target, ['--branch-only']);
28
+ const { branch, head, actualCheckout, pathSource, isLinkedWorktree, registryMatches } = checkout;
29
+ if (conflictsWithHome(actualCheckout)) fail('PATH_CONFLICT', '真实 checkout 与 Home 根或其管理目录重叠。');
30
+ const activeBranch = head && branch ? branch : null;
31
+ if (activeBranch !== null && !validActiveBranch(activeBranch)) fail('INVALID_ACTIVE_BRANCH', '现场分支名不适合写入登记。');
32
+ const primaryBranchCached = activeBranch !== null && repo.primaryRemote !== null
33
+ ? git(actualCheckout, ['show-ref', '--verify', '--quiet', '--', `refs/remotes/${repo.primaryRemote}/${activeBranch}`], { accept: [0, 1] }).status === 0
34
+ : null;
35
+ Object.assign(project, { status: repo.activeBranch === activeBranch ? 'unchanged' : 'changed', activeBranch,
36
+ checkoutState: !head ? 'unborn' : branch ? 'branch' : 'detached', actualCheckout, pathSource, isLinkedWorktree, registryMatches, primaryBranchCached });
37
+ return project.status === 'changed' ? { ...repo, activeBranch } : repo;
38
+ } catch (error) {
39
+ Object.assign(project, { status: 'blocked', code: error.code || 'IO_FAILED', message: error.message });
40
+ return repo;
41
+ }
42
+ });
43
+ assertCheckoutState(home, state);
44
+ const changed = projects.some(project => project.status === 'changed');
45
+ const saved = write && changed ? saveRegistry(home, { ...registry, repos }, { expectedRevision: registryRevision }) : null;
46
+ return { status: projects.some(project => project.status === 'blocked') ? 'partial' : !write ? 'preview' : saved?.status || 'unchanged',
47
+ registryRevision: saved?.registryRevision || registryRevision, files: saved?.files || [], projects };
48
+ }
49
+
50
+ export function main(argv = process.argv.slice(2)) {
51
+ try {
52
+ if (!argv.length || (argv.length === 1 && argv[0] === '--help')) {
53
+ console.log('refresh-branches.mjs --home HOME [--repo ID ...] [--write --expect REV]\n默认只预览;--write 只保存成功核验且有变化的分支记录,不联络远端或切换分支。');
54
+ return 0;
55
+ }
56
+ let home, write = false, expectedRevision;
57
+ const ids = [];
58
+ for (let index = 0; index < argv.length; index++) {
59
+ const flag = argv[index];
60
+ const value = argv[index + 1];
61
+ if (flag === '--write' && !write) { write = true; continue; }
62
+ if (!value || value.startsWith('--')) fail('USAGE', '参数缺值,请使用 --help。');
63
+ if (flag === '--home' && !home) home = value;
64
+ else if (flag === '--repo' && !ids.includes(value)) ids.push(value);
65
+ else if (flag === '--expect' && expectedRevision === undefined) expectedRevision = value;
66
+ else fail('USAGE', '未知或重复参数,请使用 --help。');
67
+ index++;
68
+ }
69
+ if (!home) fail('USAGE', '需要显式 --home。');
70
+ const result = refreshBranches(home, { ids, write, expectedRevision });
71
+ console.log(JSON.stringify(result, null, 2));
72
+ return result.status === 'partial' ? 1 : 0;
73
+ } catch (error) {
74
+ console.error(JSON.stringify({ status: 'failed', code: error.code || 'IO_FAILED', message: error.message }));
75
+ return 2;
76
+ }
77
+ }
78
+
79
+ if (isDirectInvocation(import.meta.url)) process.exitCode = main();
@@ -11,6 +11,12 @@ export class RegistryError extends Error {
11
11
  const fail = (code, message) => { throw new RegistryError(code, message); };
12
12
  const plain = value => value !== null && typeof value === 'object' && !Array.isArray(value);
13
13
  const text = value => typeof value === 'string' && value.length > 0 && !/[\x00-\x1f\x7f]/u.test(value);
14
+ // Validate literal local branch names without interpreting Git checkout shorthand.
15
+ export function validActiveBranch(value) {
16
+ return typeof value === 'string' && value.length > 0 && value !== 'HEAD' && !value.startsWith('-') &&
17
+ !/[\x00-\x20\x7f~^:?*\[\\]/u.test(value) && !value.includes('..') && !value.includes('@{') &&
18
+ !value.endsWith('.') && value.split('/').every(part => part && !part.startsWith('.') && !part.endsWith('.lock'));
19
+ }
14
20
  const ownKeys = (value, allowed, label) => { if (Object.keys(value).some(key => !allowed.includes(key))) fail('UNKNOWN_FIELD', `${label} 含未定义字段;不能把身份、配置或派遣状态混入路径覆盖。`); };
15
21
  export const revision = content => content === null ? 'absent' : `sha256:${createHash('sha256').update(content).digest('hex')}`;
16
22
 
@@ -29,7 +35,7 @@ export function validateRegistry(value) {
29
35
  const ids = new Set();
30
36
  for (const repo of value.repos) {
31
37
  if (!plain(repo)) fail('INVALID_REPO', '每项登记必须是对象。');
32
- ownKeys(repo, ['id', 'purpose', 'aliases', 'groups', ...(value.formatVersion === 1 ? ['remote'] : ['remotes', 'primaryRemote']), 'localPath', 'intent', 'backgroundRef'], '仓库登记');
38
+ ownKeys(repo, ['id', 'purpose', 'aliases', 'groups', ...(value.formatVersion === 1 ? ['remote'] : ['remotes', 'primaryRemote', 'activeBranch']), 'localPath', 'intent', 'backgroundRef'], '仓库登记');
33
39
  if (!/^[a-z0-9][a-z0-9-]*$/u.test(repo.id || '') || ids.has(repo.id)) fail('DUPLICATE_ID', '仓库 id 必须是唯一的小写字母/数字/连字符标识。');
34
40
  ids.add(repo.id);
35
41
  if (!text(repo.purpose) || !text(repo.localPath)) fail('INVALID_REPO', `${repo.id} 缺少单行 purpose 或 localPath。`);
@@ -40,6 +46,7 @@ export function validateRegistry(value) {
40
46
  if (!['work', 'reference'].includes(repo.intent)) fail('INVALID_INTENT', `${repo.id} 的 intent 必须为 work 或 reference;它不是权限授权。`);
41
47
  if (value.formatVersion === 1) checkRemote(repo.remote, repo.id);
42
48
  else {
49
+ if (Object.hasOwn(repo, 'activeBranch') && repo.activeBranch !== null && !validActiveBranch(repo.activeBranch)) fail('INVALID_ACTIVE_BRANCH', `${repo.id} 的 activeBranch 必须是本地分支名或 null。`);
43
50
  if (normalizeLocalPath(repo.localPath) !== repo.localPath) fail('INVALID_PATH', `${repo.id} localPath 须为显式 ./ 或 ../ 相对路径,使用正斜线。`);
44
51
  if (!Array.isArray(repo.remotes)) fail('INVALID_REMOTE', `${repo.id} remotes 必须是保留名称及 URL 顺序的数组。`);
45
52
  const names = new Set();
@@ -126,7 +133,7 @@ export function inspectRegistry(home, { includeMap = true } = {}) {
126
133
  return { ...paths, registry, registryRevision: revision(registryText), mapRevision: mapError || !includeMap ? null : revision(mapText), mapStatus: !includeMap ? 'not-inspected' : mapError ? 'unavailable' : mapText === null ? 'absent' : !mapText.startsWith(MARKER) ? 'unmanaged' : mapText === renderMap(registry, { homeRoot: paths.homeRoot, registryRevision: revision(registryText) }) ? 'current' : 'stale', ...(mapError ? { mapError } : {}), registryText, mapText };
127
134
  }
128
135
 
129
- function verifyExpected(actual, expected, label) {
136
+ export function verifyExpected(actual, expected, label) {
130
137
  if (!expected || !/^(absent|sha256:[a-f0-9]{64})$/u.test(expected)) fail('MISSING_REVISION', `${label} 需要 inspect 返回的显式 revision(首次为 absent)。`);
131
138
  if (actual !== expected) fail('STALE_WRITE', `${label} 已变化;重新读取、合并用户变更并生成新候选,不覆盖新版本。`);
132
139
  }
@@ -1,26 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
- import { spawnSync } from 'node:child_process';
5
- import { inspectRegistry, validateLocal } from './registry.mjs';
4
+ import { assertCheckoutState, checkoutTarget, readCheckoutState, realParent, routeRunner, verifyCheckout } from './checkout-tools.mjs';
6
5
  import { entry, fail, git, gitRoot, homeRoot, inside, isDirectInvocation } from './git-tools.mjs';
7
6
 
8
7
  const transports = ['file', 'https', 'http', 'ssh', 'git'];
9
8
 
10
- function realParent(target) {
11
- let parent = path.dirname(target);
12
- while (!entry(parent)) {
13
- const next = path.dirname(parent);
14
- if (next === parent) fail('PATH_CONFLICT', '无法到达目标父目录。');
15
- parent = next;
16
- }
17
- for (let current = parent; ; current = path.dirname(current)) {
18
- if (!entry(current)?.isDirectory()) fail('PATH_CONFLICT', '目标父路径包含目录链接或非目录入口。');
19
- if (current === path.dirname(current)) break;
20
- }
21
- return parent;
22
- }
23
-
24
9
  function assertDestination(home, target) {
25
10
  if (inside(target, home) || ['.git', '.agents', 'temp'].some(name => inside(path.join(home, name), target))) {
26
11
  fail('PATH_CONFLICT', '目标与 Home 根或其管理目录重叠。');
@@ -37,48 +22,13 @@ function assertDestination(home, target) {
37
22
  }
38
23
  }
39
24
 
40
- function readState(home) {
41
- for (const relative of ['.agents', '.agents/home']) {
42
- const directory = path.join(home, relative);
43
- const stat = entry(directory);
44
- if (stat && (!stat.isDirectory() || entry(path.join(directory, '.git')))) fail('HOME_BOUNDARY', '登记位置不是 Home 的真实资料目录。');
45
- }
46
- const { registry, registryRevision } = inspectRegistry(home, { includeMap: false });
47
- if (registryRevision === 'absent') fail('MISSING_REGISTRY', '克隆项目需要已有项目登记 repos.json。');
48
- const localFile = path.join(home, '.agents/home/local.json');
49
- const stat = entry(localFile);
50
- if (stat && !stat.isFile()) fail('UNSAFE_LOCAL', 'local.json 必须是同仓普通文件。');
51
- const localText = stat ? fs.readFileSync(localFile, 'utf8') : null;
52
- let localPaths = {};
53
- if (localText !== null) {
54
- let value;
55
- try { value = JSON.parse(localText); }
56
- catch { fail('INVALID_LOCAL', 'local.json 无法解析。'); }
57
- localPaths = validateLocal(value, registry).paths;
58
- }
59
- return { registry, registryRevision, localPaths, localText };
60
- }
61
-
62
- function runRoute(home, args) {
63
- const script = path.join(home, '.agents/skills/home-route/scripts/route.mjs');
64
- if (gitRoot(realParent(script)) !== home) fail('UNSAFE_HOME_ROUTE', 'home-route 入口位于另一个 Git 仓库。');
65
- if (!entry(script)?.isFile()) fail('MISSING_HOME_ROUTE', 'Home 基线缺少同仓 home-route 技能本体。');
66
- const result = spawnSync(process.execPath, [script, '--home', home, ...args], {
67
- cwd: home, encoding: 'utf8', timeout: 30_000, maxBuffer: 4 * 1024 * 1024, windowsHide: true,
68
- });
69
- let output;
70
- try { output = JSON.parse(result.status === 0 ? result.stdout : result.stderr); } catch { /* Report an unusable tool response below. */ }
71
- if (result.status !== 0 || !output) fail(output?.code || 'ROUTE_FAILED', 'home-route 未能核验目标身份。');
72
- return output;
73
- }
74
-
75
25
  function remoteConfig(repo) {
76
26
  if (Object.hasOwn(repo, 'remote')) return repo.remote ? { name: 'origin', url: repo.remote } : null;
77
27
  if (repo.primaryRemote === null) return null;
78
28
  return { name: repo.primaryRemote, url: repo.remotes.find(remote => remote.name === repo.primaryRemote).urls[0] };
79
29
  }
80
30
 
81
- function checkRemote(home, source, repo) {
31
+ function checkRemote(home, source, repo, runRoute) {
82
32
  const url = source.url;
83
33
  const scheme = /^([a-z][a-z0-9+.-]*):\/\//iu.exec(url)?.[1].toLowerCase();
84
34
  const local = path.isAbsolute(url) || path.win32.isAbsolute(url);
@@ -88,7 +38,7 @@ function checkRemote(home, source, repo) {
88
38
  for (const name of repo.remotes?.map(remote => remote.name) || [source.name]) {
89
39
  if (name.startsWith('-') || git(home, ['check-ref-format', `refs/remotes/${name}/HEAD`], { accept: [0, 1] }).status !== 0) fail('INVALID_REMOTE_NAME', '登记的 remote 名称无法用于 Git。');
90
40
  }
91
- if (runRoute(home, ['--check-fetch', url]).status !== 'verified') fail('ROUTE_FAILED', '未确认主远端 URL 的实际身份。');
41
+ if (runRoute(['--check-fetch', url]).status !== 'verified') fail('ROUTE_FAILED', '未确认主远端 URL 的实际身份。');
92
42
  }
93
43
 
94
44
  function configureRemotes(directory, repo, primary) {
@@ -103,12 +53,10 @@ function configureRemotes(directory, repo, primary) {
103
53
  }
104
54
  }
105
55
 
106
- function inspectCheckout(home, repo, checkout, explicit = false) {
107
- const result = runRoute(home, ['--repo', repo.id, ...(explicit ? ['--checkout', checkout] : [])]);
108
- if (result.status !== 'resolved' || !result.requestedPathIsGitRoot || result.actualCheckout !== fs.realpathSync.native(checkout)) {
109
- fail('PATH_CONFLICT', '目标未指向登记项目的独立 Git 根。');
110
- }
111
- return { head: result.head, branch: result.branch, dirty: result.dirty, remoteDrift: result.remoteDrift?.map(({ name, change, fields }) => ({ name, change, fields })) || [] };
56
+ function inspectCheckout(runRoute, repo, checkout, explicit = false) {
57
+ const result = verifyCheckout(runRoute, repo, checkout, explicit ? ['--checkout', checkout] : []);
58
+ return { head: result.head, branch: result.branch, dirty: result.dirty, remoteDrift: result.remoteDrift?.map(({ name, change, fields }) => ({ name, change, fields })) || [],
59
+ ...(typeof repo.activeBranch === 'string' ? { branchMatches: Boolean(result.head) && result.branch === repo.activeBranch } : {}) };
112
60
  }
113
61
 
114
62
  function publish(staged, target) {
@@ -125,7 +73,7 @@ function publish(staged, target) {
125
73
  }
126
74
  }
127
75
 
128
- function cloneProject(home, repo, target, source, state) {
76
+ function cloneProject(home, repo, target, source, state, runRoute) {
129
77
  const parent = path.dirname(target);
130
78
  fs.mkdirSync(parent, { recursive: true });
131
79
  assertDestination(home, target);
@@ -133,22 +81,32 @@ function cloneProject(home, repo, target, source, state) {
133
81
  const staged = path.join(temporary, 'checkout');
134
82
  try {
135
83
  const protocolOptions = ['-c', 'protocol.allow=never', '-c', 'protocol.ext.allow=never', ...transports.flatMap(protocol => ['-c', `protocol.${protocol}.allow=always`])];
84
+ const safeConfig = [...protocolOptions, '-c', `core.hooksPath=${path.join(temporary, 'no-hooks')}`];
85
+ const branch = repo.activeBranch;
136
86
  try {
137
- git(home, [...protocolOptions, '-c', `core.hooksPath=${path.join(temporary, 'no-hooks')}`, 'clone', '--template=', '--no-recurse-submodules', '--no-local', '--origin', source.name, '--', source.url, staged], { timeout: 300_000 });
87
+ git(home, [...safeConfig, 'clone', '--template=', '--no-recurse-submodules', '--no-local', '--origin', source.name, ...(branch === undefined ? [] : ['--no-checkout']), '--', source.url, staged], { timeout: 300_000 });
138
88
  } catch (error) {
139
89
  fail('CLONE_FAILED', `${error.message} 请核对主远端可达性和新机凭据。`);
140
90
  }
91
+ if (branch !== undefined) {
92
+ // Select an exact fetched branch, never a tag or a remote's HEAD alias.
93
+ const remoteRef = `refs/remotes/${source.name}/${branch}`;
94
+ if (git(staged, ['show-ref', '--verify', '--quiet', '--', remoteRef], { accept: [0, 1] }).status !== 0) {
95
+ fail('REMOTE_BRANCH_MISSING', `主远端未提供记录的分支 ${branch};不回退到默认分支或同名标签。`);
96
+ }
97
+ git(staged, [...safeConfig, 'checkout', '--no-recurse-submodules', '--track', '-B', branch, remoteRef]);
98
+ }
141
99
  configureRemotes(staged, repo, source.name);
142
- const checkout = inspectCheckout(home, repo, staged, true);
100
+ const checkout = inspectCheckout(runRoute, repo, staged, true);
101
+ if (branch !== undefined && !checkout.branchMatches) fail('BRANCH_MISMATCH', '新 checkout 未检出记录的分支。');
143
102
  if (!checkout.head) fail('MISSING_REMOTE_HEAD', '主远端没有可检出的默认分支提交。');
144
103
  if (checkout.remoteDrift.length) fail('REMOTE_CONFIG_CONFLICT', '新 checkout 的完整 remote 配置与登记不同。');
145
- const current = readState(home);
146
- if (current.registryRevision !== state.registryRevision || current.localText !== state.localText) fail('STALE_REGISTRY', '恢复期间登记或本机路径已变化,请重新预览。');
104
+ assertCheckoutState(home, state);
147
105
  assertDestination(home, target);
148
106
  if (entry(target)) fail('PATH_CONFLICT', '下载期间目标路径已被占用。');
149
107
  if (!inside(parent, staged) || !inside(parent, target)) fail('PATH_CONFLICT', '恢复路径超出目标父目录。');
150
108
  publish(staged, target);
151
- return inspectCheckout(home, repo, target);
109
+ return inspectCheckout(runRoute, repo, target);
152
110
  } finally {
153
111
  const stat = entry(temporary);
154
112
  if (stat?.isDirectory() && inside(parent, fs.realpathSync.native(temporary))) fs.rmSync(temporary, { recursive: true, force: true });
@@ -158,13 +116,15 @@ function cloneProject(home, repo, target, source, state) {
158
116
  export function restore(home, { apply = false, ids = [] } = {}) {
159
117
  home = homeRoot(home);
160
118
  if (gitRoot(home) !== home) fail('MISSING_HOME_GIT', '请从已建立的 Home Git 工作树执行恢复。');
161
- const state = readState(home);
162
- const targets = state.registry.repos.map(repo => ({ repo, target: path.resolve(home, Object.hasOwn(state.localPaths, repo.id) ? state.localPaths[repo.id] : repo.localPath) }));
119
+ const state = readCheckoutState(home);
120
+ const targets = state.registry.repos.map(repo => ({ repo, target: checkoutTarget(home, repo, state) }));
121
+ let runner;
122
+ const runRoute = args => (runner ??= routeRunner(home))(args);
163
123
  if (ids.some(id => !targets.some(({ repo }) => repo.id === id))) fail('UNKNOWN_REPO', '请求包含未登记的 repo ID。');
164
124
  const projects = [];
165
125
  for (const { repo, target } of targets) {
166
126
  if (ids.length && !ids.includes(repo.id)) continue;
167
- const project = { id: repo.id, target };
127
+ const project = { id: repo.id, target, ...(Object.hasOwn(repo, 'activeBranch') ? { requestedBranch: repo.activeBranch } : {}) };
168
128
  try {
169
129
  if (targets.some(other => other.repo.id !== repo.id && (inside(target, other.target) || inside(other.target, target)))) fail('PATH_CONFLICT', '目标与另一个登记项目路径重叠。');
170
130
  assertDestination(home, target);
@@ -172,12 +132,13 @@ export function restore(home, { apply = false, ids = [] } = {}) {
172
132
  if (stat) {
173
133
  const marker = stat.isDirectory() && entry(path.join(target, '.git'));
174
134
  if (!marker || !(marker.isDirectory() || marker.isFile())) fail('PATH_CONFLICT', '目标已存在且不是可复用的独立 checkout。');
175
- Object.assign(project, { status: 'reused', ...inspectCheckout(home, repo, target) });
135
+ Object.assign(project, { status: 'reused', ...inspectCheckout(runRoute, repo, target) });
176
136
  } else {
177
137
  const source = remoteConfig(repo);
178
138
  if (!source) fail('LOCAL_ONLY', '项目仅存于旧机器,需要独立迁移其 Git 数据。');
179
- checkRemote(home, source, repo);
180
- Object.assign(project, apply ? { status: 'cloned', ...cloneProject(home, repo, target, source, state) } : { status: 'planned' });
139
+ if (repo.activeBranch === null) fail('NO_RECORDED_BRANCH', '记录显示旧机没有可恢复的已提交分支;先由项目 owner 核实再恢复。');
140
+ checkRemote(home, source, repo, runRoute);
141
+ Object.assign(project, apply ? { status: 'cloned', ...cloneProject(home, repo, target, source, state, runRoute) } : { status: 'planned' });
181
142
  }
182
143
  } catch (error) {
183
144
  Object.assign(project, { status: 'blocked', code: error.code || 'IO_FAILED', message: error.message });
@@ -190,7 +151,7 @@ export function restore(home, { apply = false, ids = [] } = {}) {
190
151
  export function main(argv = process.argv.slice(2)) {
191
152
  try {
192
153
  if (!argv.length || (argv.length === 1 && argv[0] === '--help')) {
193
- console.log('restore.mjs --home HOME [--repo ID ...] [--apply]\n默认只预览;--apply 克隆缺失的登记项目并核验,已匹配的 checkout 原地复用。');
154
+ console.log('restore.mjs --home HOME [--repo ID ...] [--apply]\n默认只预览;--apply 按登记分支克隆缺失项目,已匹配的 checkout 原地复用、不切分支。');
194
155
  return 0;
195
156
  }
196
157
  let home, apply = false;
@@ -223,7 +223,7 @@ herdr pane read <returned-pane-id> --source recent-unwrapped --lines 120
223
223
 
224
224
  在同一连接上下文执行 `herdr pane close <pane_id>`,随后用 `herdr pane list` 确认目标已关闭。
225
225
 
226
- ## Claude Code & Codex & Pi 的默认启动方式命令
226
+ ## Claude Code、Codex、Pi 和 agy 的默认启动方式
227
227
 
228
228
  在已有可用 shell 窗格中启动;`<name>` 为唯一名称,`<returned-pane-id>` 为实际返回的窗格 ID,`<models_name>`/`<effort>` 为模型/推理强度,未指定则删除对应参数:
229
229
 
@@ -231,6 +231,7 @@ herdr pane read <returned-pane-id> --source recent-unwrapped --lines 120
231
231
  herdr agent start <name> --kind claude --pane <returned-pane-id> -- --dangerously-skip-permissions --model <models_name> --effort <effort>
232
232
  herdr agent start <name> --kind codex --pane <returned-pane-id> -- --no-daemon --dangerously-bypass-approvals-and-sandbox -m <models_name> --config model_reasoning_effort="<effort>"
233
233
  herdr agent start <name> --kind pi --pane <returned-pane-id> -- --model <models_name> --thinking <effort>
234
+ herdr agent start <name> --kind agy --pane <returned-pane-id> -- --dangerously-skip-permissions
234
235
  ```
235
236
 
236
237
  ## 文件通信协议
@@ -28,9 +28,10 @@ description: "当用户明确要求使用 herdr-core、hc 或 system-herdr-core
28
28
  hc run --bg --json --name claude-error-review --cwd "$PWD" -- claude --dangerously-skip-permissions
29
29
  hc run --bg --json --name codex-error-review --cwd "$PWD" -- codex --no-daemon --dangerously-bypass-approvals-and-sandbox
30
30
  hc run --bg --json --name pi-error-review --cwd "$PWD" -- pi
31
+ hc run --bg --json --name agy-error-review --cwd "$PWD" -- agy --dangerously-skip-permissions
31
32
  ```
32
33
 
33
- Claude Code 必须带 `--dangerously-skip-permissions`。Codex 必须同时带 `--no-daemon` 和 `--dangerously-bypass-approvals-and-sandbox`,分别让实例留在自己的终端上下文,以及跳过审批并关闭沙箱。Pi 使用原生交互入口 `pi`,保留默认工具,不加 Claude Code 或 Codex 的参数,也不用 `-p` 启动一次性进程。
34
+ Claude Code 和 `agy` 启动时都带 `--dangerously-skip-permissions`。Codex 必须同时带 `--no-daemon` 和 `--dangerously-bypass-approvals-and-sandbox`,分别让实例留在自己的终端上下文,以及跳过审批并关闭沙箱。Pi 使用原生交互入口 `pi`,保留默认工具,不加 Claude Code 或 Codex 的参数,也不用 `-p` 启动一次性进程。
34
35
 
35
36
  直接启动、远程启动和角色模板都使用这套启动约定。选用的 CLI 不支持必带参数时,报告具体参数和版本,不删参数后重试。全权限启动只改变 CLI 自身的审批或沙箱设置,不提权,也不扩大用户已授权的任务范围。
36
37
 
@@ -46,7 +47,7 @@ Codex 的 `-c` 等同于 `--config`。无法解析为 TOML 的覆盖值按字符
46
47
 
47
48
  ### 检查模板和终端身份
48
49
 
49
- 角色模板使用 `<cli>-<topic>.md`,如 `codex-error-review.md`,调用时使用不带 `.md` 的模板名。模板不使用 `codex`、`claude`、`pi` 等实际程序名;已有同名模板按实际主题改名,并同步模板调用处。模板的 `command:` 和直接启动命令中的可执行程序仍使用真实名称与完整参数。`--name` 只命名终端,不参与模板匹配;仅修改 `--name` 不能消除同名模板冲突。
50
+ 角色模板使用 `<cli>-<topic>.md`,如 `codex-error-review.md`,调用时使用不带 `.md` 的模板名。模板不使用 `codex`、`claude`、`pi`、`agy` 等实际程序名;已有同名模板按实际主题改名,并同步模板调用处。模板的 `command:` 和直接启动命令中的可执行程序仍使用真实名称与完整参数。`--name` 只命名终端,不参与模板匹配;仅修改 `--name` 不能消除同名模板冲突。
50
51
 
51
52
  `hc templates` 列出当前 Core 的角色模板。远程启动由目标 Core 解析模板,也要在目标上核对。Core 会先查与命令同名的模板;`--` 只分隔参数,不阻止模板解析。需要直接启动而遇到同名模板时,使用目标机器上核实的可执行文件绝对路径,例如 `/usr/local/bin/codex` 或 Windows 上 `codex.cmd` 的实际路径。
52
53