@namewta/skills-hub 0.1.49 → 0.1.51

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 (253) hide show
  1. package/README.md +4 -1
  2. package/THIRD_PARTY_NOTICES.md +19 -7
  3. package/cli.mjs +2 -2
  4. package/install.mjs +11 -4
  5. package/package.json +1 -1
  6. package/scripts/persistence/home.md +1 -1
  7. package/skills/dev/dev-build/SKILL.md +2 -0
  8. package/skills/dev/dev-build/references/implement-request.md +7 -2
  9. package/skills/dev/dev-formal-verify/SKILL.md +2 -1
  10. package/skills/dev/dev-formal-verify/references/create-check.md +3 -1
  11. package/skills/dev/dev-formal-verify/references/example.md +1 -1
  12. package/skills/dev/dev-formal-verify/references/tool-choice.md +1 -1
  13. package/skills/dev/dev-help/references/capabilities.md +6 -6
  14. package/skills/dev/dev-help/references/guide-verification.md +7 -1
  15. package/skills/dev/dev-help/references/help-method.md +7 -1
  16. package/skills/dev/dev-issue/SKILL.md +1 -0
  17. package/skills/dev/dev-issue/references/github-operations.md +8 -0
  18. package/skills/dev/dev-plan/references/plan-template.md +1 -0
  19. package/skills/dev/dev-plan/references/vertical-slicing.md +2 -0
  20. package/skills/dev/dev-pr/references/pull-request-evidence.md +2 -0
  21. package/skills/dev/dev-review/references/host-parity.md +12 -0
  22. package/skills/dev/dev-review/references/review-baseline.md +2 -0
  23. package/skills/dev/dev-setup/references/formal-options.md +1 -1
  24. package/skills/dev/dev-statechart/SKILL.md +17 -19
  25. package/skills/dev/dev-statechart/agents/openai.yaml +3 -3
  26. package/skills/dev/dev-statechart/assets/theme.css +135 -0
  27. package/skills/dev/dev-statechart/references/lean-proof.md +47 -0
  28. package/skills/dev/dev-statechart/references/render.md +15 -83
  29. package/skills/dev/dev-statechart/references/runtime.md +21 -1
  30. package/skills/dev/dev-statechart/scripts/lean/backends/lemma-chart.mjs +285 -0
  31. package/skills/dev/dev-statechart/scripts/lean/backends/mermaid.mjs +174 -0
  32. package/skills/dev/dev-statechart/scripts/lean/backends/proof-chart.mjs +540 -0
  33. package/skills/dev/dev-statechart/scripts/lean/backends/report.mjs +242 -0
  34. package/skills/dev/dev-statechart/scripts/lean/frontends/facts.mjs +234 -0
  35. package/skills/dev/dev-statechart/scripts/lean/frontends/view.mjs +217 -0
  36. package/skills/dev/dev-statechart/scripts/lean/ir.mjs +226 -0
  37. package/skills/dev/dev-statechart/scripts/lean/passes/attribute.mjs +148 -0
  38. package/skills/dev/dev-statechart/scripts/lean/passes/blocks.mjs +32 -0
  39. package/skills/dev/dev-statechart/scripts/lean/passes/budget.mjs +167 -0
  40. package/skills/dev/dev-statechart/scripts/lean/passes/check.mjs +70 -0
  41. package/skills/dev/dev-statechart/scripts/lean/passes/contract.mjs +160 -0
  42. package/skills/dev/dev-statechart/scripts/lean/passes/fold.mjs +206 -0
  43. package/skills/dev/dev-statechart/scripts/lean/passes/inline.mjs +84 -0
  44. package/skills/dev/dev-statechart/scripts/lean/passes/mark.mjs +432 -0
  45. package/skills/dev/dev-statechart/scripts/lean/passes/reduce.mjs +73 -0
  46. package/skills/dev/dev-statechart/scripts/lean/passes/trust.mjs +111 -0
  47. package/skills/dev/dev-statechart/scripts/lean/passes/view-lemmas.mjs +155 -0
  48. package/skills/dev/dev-statechart/scripts/lean/pipeline.mjs +164 -0
  49. package/skills/dev/dev-statechart/scripts/lean/run.mjs +168 -0
  50. package/skills/dev/dev-statechart/scripts/statechart.mjs +42 -23
  51. package/skills/dev/dev-statechart/scripts/worker.mjs +33 -7
  52. package/skills/dev/dev-ui-design/SKILL.md +2 -2
  53. package/skills/dev/dev-ui-design/references/interaction-review.md +9 -0
  54. package/skills/dev/dev-verify/SKILL.md +1 -1
  55. package/skills/dev/dev-verify/references/evidence-storage.md +12 -0
  56. package/skills/dev/dev-workflow/SKILL.md +6 -6
  57. package/skills/dev/dev-workflow/references/method-handoffs.md +7 -1
  58. package/skills/dev/dev-writing/SKILL.md +2 -0
  59. package/skills/dev/dev-writing/references/library-docs.md +37 -0
  60. package/skills/home/home-doctor/references/diagnosis.md +2 -2
  61. package/skills/home/home-doctor/scripts/doctor.mjs +68 -38
  62. package/skills/home/home-project-changelog/SKILL.md +6 -6
  63. package/skills/home/home-project-changelog/assets/project-changelog.example.json +188 -0
  64. package/skills/home/home-project-changelog/assets/project-changelog.schema.json +156 -0
  65. package/skills/home/home-project-changelog/assets/worker-brief.md +1 -1
  66. package/skills/home/home-project-changelog/references/git-ranges.md +2 -2
  67. package/skills/home/home-project-changelog/references/schema.md +60 -0
  68. package/skills/home/home-project-changelog/references/tools.md +27 -22
  69. package/skills/home/home-project-changelog/references/workflow.md +12 -9
  70. package/skills/home/home-project-changelog/references/writing.md +5 -3
  71. package/skills/home/home-project-changelog/scripts/changelog.mjs +34 -37
  72. package/skills/home/home-project-changelog/scripts/contract.mjs +39 -3
  73. package/skills/home/home-project-changelog/scripts/legacy-markdown.mjs +116 -0
  74. package/skills/home/home-project-changelog/scripts/migrate.mjs +122 -0
  75. package/skills/home/home-project-changelog/scripts/revision.mjs +2 -196
  76. package/skills/home/home-project-changelog/scripts/storage.mjs +120 -125
  77. package/skills/home/home-project-changelog/scripts/summary.mjs +0 -60
  78. package/skills/home/home-route/SKILL.md +2 -2
  79. package/skills/home/home-route/references/routing.md +3 -1
  80. package/skills/home/home-route/scripts/route.mjs +79 -11
  81. package/skills/home/home-setup/SKILL.md +2 -1
  82. package/skills/home/home-setup/assets/repos.schema.json +10 -0
  83. package/skills/home/home-setup/references/registry.md +18 -1
  84. package/skills/home/home-setup/scripts/registry.mjs +67 -7
  85. package/skills/home/home-website/SKILL.md +13 -9
  86. package/skills/home/home-website/assets/website/scripts/inputs.mjs +136 -128
  87. package/skills/home/home-website/assets/website/scripts/render.mjs +3 -3
  88. package/skills/home/home-website/assets/website/scripts/site.mjs +21 -10
  89. package/skills/home/home-website/assets/website/site/public/home-assets/app.js +69 -23
  90. package/skills/home/home-website/assets/website/site/public/home-assets/site.css +74 -42
  91. package/skills/home/home-website/assets/website/site/templates/layout.mjs +2 -6
  92. package/skills/home/home-website/assets/website/site/templates/ledger.mjs +33 -24
  93. package/skills/home/home-website/assets/website/site/templates/model.mjs +28 -5
  94. package/skills/home/home-website/assets/website/site/templates/pages.mjs +48 -19
  95. package/skills/home/home-website/assets/website/site/templates/project-logs.mjs +2 -107
  96. package/skills/home/home-website/assets/website/site.config.json +1 -1
  97. package/skills/home/home-website/references/website.md +64 -46
  98. package/skills/home/home-website/scripts/activate.mjs +105 -0
  99. package/skills/home/home-website/scripts/init.mjs +79 -11
  100. package/skills/home/home-workflow/SKILL.md +6 -4
  101. package/skills/system/system-clash-proxy-config/SKILL.md +21 -0
  102. package/skills/system/system-clash-proxy-config/agents/openai.yaml +4 -0
  103. package/skills/system/system-clash-proxy-config/assets/clash-override.js +328 -0
  104. package/skills/system/{system-proxy → system-clash-proxy-config}/references/browser-privacy.md +2 -2
  105. package/skills/system/{system-config → system-clash-proxy-config}/references/changes.md +2 -2
  106. package/skills/system/{system-proxy → system-clash-proxy-config}/references/clash-verge.md +1 -1
  107. package/skills/system/{system-proxy → system-clash-proxy-config}/references/diagnosis.md +1 -1
  108. package/skills/system/system-clash-proxy-config/references/dns-workflow.md +42 -0
  109. package/skills/system/system-clash-proxy-config/references/egress-macos.md +31 -0
  110. package/skills/system/system-clash-proxy-config/references/egress-windows.md +37 -0
  111. package/skills/system/system-clash-proxy-config/references/egress.md +12 -0
  112. package/skills/system/{system-proxy → system-clash-proxy-config}/references/flclash.md +1 -1
  113. package/skills/system/{system-proxy → system-clash-proxy-config}/references/index.md +1 -1
  114. package/skills/system/{system-clash-tun-egress → system-clash-proxy-config}/references/linux-cutover.md +29 -0
  115. package/skills/system/system-clash-proxy-config/references/locale-workflow.md +9 -0
  116. package/skills/system/{system-proxy → system-clash-proxy-config}/references/mihomo.md +1 -25
  117. package/skills/system/system-clash-proxy-config/references/session.md +34 -0
  118. package/skills/system/system-clash-proxy-config/references/subscription.md +29 -0
  119. package/skills/system/{system-proxy → system-clash-proxy-config}/references/troubleshooting.md +7 -7
  120. package/skills/system/{system-clash-tun-egress → system-clash-proxy-config}/references/verification.md +2 -0
  121. package/skills/system/system-clash-proxy-config/scripts/prepare-session.mjs +155 -0
  122. package/skills/system/system-clash-proxy-config/scripts/run-session.mjs +138 -0
  123. package/skills/system/system-inspect/SKILL.md +1 -1
  124. package/skills/system/system-inspect/references/health-audit.md +1 -1
  125. package/upstream-skills/zh-archify/SKILL.md +11 -11
  126. package/upstream-skills/zh-archify/assets/template.html +6 -3
  127. package/upstream-skills/zh-archify/bin/archify.mjs +67 -4
  128. package/upstream-skills/zh-archify/modules/code-analysis/ARCHITECTURE.md +7 -1
  129. package/upstream-skills/zh-archify/modules/code-analysis/bin/analyze-run.mjs +2 -1
  130. package/upstream-skills/zh-archify/modules/code-analysis/bin/check.mjs +29 -15
  131. package/upstream-skills/zh-archify/modules/code-analysis/bin/drift.mjs +3 -3
  132. package/upstream-skills/zh-archify/modules/code-analysis/bin/prepare.mjs +5 -6
  133. package/upstream-skills/zh-archify/modules/code-analysis/bin/serve.mjs +66 -36
  134. package/upstream-skills/zh-archify/modules/code-analysis/bin/verify-change.mjs +43 -13
  135. package/upstream-skills/zh-archify/modules/code-analysis/docs/TECH-GUIDE.md +1 -1
  136. package/upstream-skills/zh-archify/modules/code-analysis/docs/USAGE.md +37 -4
  137. package/upstream-skills/zh-archify/modules/code-analysis/extract/ts/functions.mjs +7 -5
  138. package/upstream-skills/zh-archify/modules/code-analysis/extract/ts/index.mjs +4 -1
  139. package/upstream-skills/zh-archify/modules/code-analysis/extract/ts/snapshot-host.mjs +9 -0
  140. package/upstream-skills/zh-archify/modules/code-analysis/lib/architecture-drift.mjs +28 -7
  141. package/upstream-skills/zh-archify/modules/code-analysis/lib/drift-capture.mjs +4 -3
  142. package/upstream-skills/zh-archify/modules/code-analysis/lib/git-sources.mjs +5 -3
  143. package/upstream-skills/zh-archify/modules/code-analysis/lib/output.mjs +272 -0
  144. package/upstream-skills/zh-archify/modules/code-analysis/lib/pull-request.mjs +34 -4
  145. package/upstream-skills/zh-archify/modules/code-analysis/lib/task.mjs +4 -2
  146. package/upstream-skills/zh-archify/modules/code-analysis/lib/verification-context.mjs +13 -1
  147. package/upstream-skills/zh-archify/modules/code-analysis/lib/verification-history.mjs +112 -0
  148. package/upstream-skills/zh-archify/modules/code-analysis/lib/verification.mjs +6 -2
  149. package/upstream-skills/zh-archify/modules/code-analysis/overlay/atlas.mjs +71 -5
  150. package/upstream-skills/zh-archify/modules/code-analysis/overlay/client/atlas.css +16 -2
  151. package/upstream-skills/zh-archify/modules/code-analysis/overlay/client/atlas.js +121 -5
  152. package/upstream-skills/zh-archify/modules/code-analysis/overlay/client/atlas3d.js +38 -1
  153. package/upstream-skills/zh-archify/modules/code-analysis/overlay/client/overlay.css +14 -1
  154. package/upstream-skills/zh-archify/modules/code-analysis/overlay/client/overlay.js +187 -27
  155. package/upstream-skills/zh-archify/modules/code-analysis/overlay/client/verification.js +1 -1
  156. package/upstream-skills/zh-archify/modules/code-analysis/overlay/i18n.mjs +9 -0
  157. package/upstream-skills/zh-archify/modules/code-analysis/overlay/inject.mjs +1 -1
  158. package/upstream-skills/zh-archify/modules/code-analysis/overlay/page.mjs +11 -6
  159. package/upstream-skills/zh-archify/modules/code-analysis/overlay/pull-request.mjs +1 -1
  160. package/upstream-skills/zh-archify/modules/code-analysis/schemas/ai-task.schema.json +1 -0
  161. package/upstream-skills/zh-archify/modules/code-analysis/test/atlas.test.mjs +88 -0
  162. package/upstream-skills/zh-archify/modules/code-analysis/test/duplicates.test.mjs +1 -1
  163. package/upstream-skills/zh-archify/modules/code-analysis/test/external-workflow.test.mjs +1 -1
  164. package/upstream-skills/zh-archify/modules/code-analysis/test/fixtures/tasks/boundary.task.json +1 -0
  165. package/upstream-skills/zh-archify/modules/code-analysis/test/fixtures/tasks/boundary.task.missing.json +1 -0
  166. package/upstream-skills/zh-archify/modules/code-analysis/test/fixtures/tasks/complexity.task.json +1 -0
  167. package/upstream-skills/zh-archify/modules/code-analysis/test/fixtures/tasks/complexity.task.valid.json +1 -0
  168. package/upstream-skills/zh-archify/modules/code-analysis/test/fixtures/tasks/import-cycle.task.changed.json +1 -0
  169. package/upstream-skills/zh-archify/modules/code-analysis/test/fixtures/tasks/import-cycle.task.json +1 -0
  170. package/upstream-skills/zh-archify/modules/code-analysis/test/fixtures/tasks/module-cycle.task.json +1 -0
  171. package/upstream-skills/zh-archify/modules/code-analysis/test/function-source-range.test.mjs +10 -0
  172. package/upstream-skills/zh-archify/modules/code-analysis/test/output-recovery.test.mjs +626 -0
  173. package/upstream-skills/zh-archify/modules/code-analysis/test/pull-request.test.mjs +98 -2
  174. package/upstream-skills/zh-archify/modules/code-analysis/test/review.test.mjs +37 -0
  175. package/upstream-skills/zh-archify/modules/code-analysis/test/source-panel.test.mjs +2 -1
  176. package/upstream-skills/zh-archify/modules/code-analysis/test/task.test.mjs +3 -2
  177. package/upstream-skills/zh-archify/modules/code-analysis/test/verification-history.test.mjs +216 -0
  178. package/upstream-skills/zh-archify/modules/code-analysis/test/verification.test.mjs +122 -0
  179. package/upstream-skills/zh-archify/package-lock.json +2 -2
  180. package/upstream-skills/zh-archify/package.json +1 -1
  181. package/upstream-skills/zh-archify/references/authoring-contract.md +2 -0
  182. package/upstream-skills/zh-archify/references/explainer-authoring.md +1 -1
  183. package/upstream-skills/zh-archify/renderers/architecture/render-architecture.mjs +1 -0
  184. package/upstream-skills/zh-archify/renderers/class/render-class.mjs +1 -0
  185. package/upstream-skills/zh-archify/renderers/dataflow/render-dataflow.mjs +2 -1
  186. package/upstream-skills/zh-archify/renderers/erd/render-erd.mjs +1 -0
  187. package/upstream-skills/zh-archify/renderers/lifecycle/render-lifecycle.mjs +4 -2
  188. package/upstream-skills/zh-archify/renderers/sequence/render-sequence.mjs +4 -2
  189. package/upstream-skills/zh-archify/renderers/shared/cli.mjs +7 -1
  190. package/upstream-skills/zh-archify/renderers/timeline/render-timeline.mjs +1 -0
  191. package/upstream-skills/zh-archify/renderers/tree/render-tree.mjs +1 -0
  192. package/upstream-skills/zh-archify/renderers/waterfall/render-waterfall.mjs +1 -0
  193. package/upstream-skills/zh-archify/renderers/workflow/render-workflow.mjs +3 -2
  194. package/upstream-skills/zh-archify/renderers/workflow/workflow-compiler.mjs +68 -7
  195. package/upstream-skills/zh-archify/skill-release.json +1 -1
  196. package/upstream-skills/zh-modern-web-guidance/SKILL.md +4 -11
  197. package/upstream-skills/zh-modern-web-guidance/guides/built-in-ai/language-detection.md +20 -0
  198. package/upstream-skills/zh-modern-web-guidance/guides/built-in-ai/language-model.md +22 -0
  199. package/upstream-skills/zh-modern-web-guidance/guides/built-in-ai/prompt-api.md +22 -0
  200. package/upstream-skills/zh-modern-web-guidance/guides/built-in-ai/summarizer.md +20 -0
  201. package/upstream-skills/zh-modern-web-guidance/guides/built-in-ai/translator.md +22 -0
  202. package/upstream-skills/zh-modern-web-guidance/guides/performance/custom-ml-model-inference.md +342 -0
  203. package/upstream-skills/zh-modern-web-guidance/guides/performance/data-parallel-computation.md +337 -0
  204. package/upstream-skills/zh-modern-web-guidance/guides/performance/improve-next-page-load-performance.md +4 -1
  205. package/upstream-skills/zh-modern-web-guidance/guides/performance/large-scene-rendering.md +350 -0
  206. package/upstream-skills/zh-modern-web-guidance/guides/ui-atoms/position-aware-tooltips.md +9 -0
  207. package/upstream-skills/zh-modern-web-guidance/guides/ui-atoms/viewport-aware-dropdowns.md +9 -0
  208. package/upstream-skills/zh-modern-web-guidance/guides/ui-behaviors/animate-to-from-top-layer.md +9 -0
  209. package/upstream-skills/zh-modern-web-guidance/guides/ui-behaviors/declarative-dialog-popover-control.md +9 -0
  210. package/upstream-skills/zh-modern-web-guidance/guides/ui-behaviors/interest-triggered-tooltips.md +9 -0
  211. package/upstream-skills/zh-modern-web-guidance/guides/ui-behaviors/scroll-target-on-load.md +29 -0
  212. package/upstream-skills/zh-modern-web-guidance/guides/ui-behaviors/sortable-table.md +1 -0
  213. package/upstream-skills/zh-modern-web-guidance/guides/ui-components/app-menus.md +9 -0
  214. package/upstream-skills/zh-modern-web-guidance/guides/ui-components/context-menu.md +9 -0
  215. package/upstream-skills/zh-modern-web-guidance/guides/ui-components/copy-button.md +9 -0
  216. package/upstream-skills/zh-modern-web-guidance/guides/ui-components/dialog.md +10 -1
  217. package/upstream-skills/zh-modern-web-guidance/guides/ui-components/hovercard.md +9 -0
  218. package/upstream-skills/zh-modern-web-guidance/guides/ui-components/menu.md +9 -0
  219. package/upstream-skills/zh-modern-web-guidance/guides/ui-components/navbar.md +9 -0
  220. package/upstream-skills/zh-modern-web-guidance/guides/ui-components/persistent-app-tours.md +9 -0
  221. package/upstream-skills/zh-modern-web-guidance/guides/ui-components/persistent-toast-notifications.md +9 -0
  222. package/upstream-skills/zh-modern-web-guidance/guides/ui-components/toolbar.md +9 -0
  223. package/upstream-skills/zh-modern-web-guidance/guides/user-experience/content-first-noise-reduction.md +9 -0
  224. package/upstream-skills/zh-modern-web-guidance/guides/user-experience/natural-interactions.md +9 -0
  225. package/upstream-skills/zh-modern-web-guidance/guides/webmcp/agentic-javascript-tools.md +27 -0
  226. package/skills/home/home-project-changelog/assets/project-changelog.md +0 -35
  227. package/skills/system/system-clash-tun-egress/SKILL.md +0 -22
  228. package/skills/system/system-clash-tun-egress/agents/openai.yaml +0 -4
  229. package/skills/system/system-config/SKILL.md +0 -37
  230. package/skills/system/system-config/agents/openai.yaml +0 -4
  231. package/skills/system/system-config/references/ai-cli-config.md +0 -75
  232. package/skills/system/system-config/references/ai-cli-optimization.md +0 -37
  233. package/skills/system/system-config/references/index.md +0 -12
  234. package/skills/system/system-config/references/locale-workflow.md +0 -33
  235. package/skills/system/system-config/references/locale.md +0 -50
  236. package/skills/system/system-proxy/SKILL.md +0 -40
  237. package/skills/system/system-proxy/agents/openai.yaml +0 -4
  238. package/skills/system/system-proxy/assets/protected-rules.yaml +0 -7
  239. package/skills/system/system-proxy/references/dns-workflow.md +0 -152
  240. /package/skills/system/{system-config → system-clash-proxy-config}/assets/configuration.md +0 -0
  241. /package/skills/system/{system-proxy → system-clash-proxy-config}/assets/network.md +0 -0
  242. /package/skills/system/{system-proxy → system-clash-proxy-config}/references/acceptance.md +0 -0
  243. /package/skills/system/{system-proxy → system-clash-proxy-config}/references/dns-fields.md +0 -0
  244. /package/skills/system/{system-proxy → system-clash-proxy-config}/references/dns-misconceptions.md +0 -0
  245. /package/skills/system/{system-clash-tun-egress/references/troubleshooting.md → system-clash-proxy-config/references/egress-troubleshooting.md} +0 -0
  246. /package/skills/system/{system-config → system-clash-proxy-config}/references/locale-linux.md +0 -0
  247. /package/skills/system/{system-config → system-clash-proxy-config}/references/locale-macos.md +0 -0
  248. /package/skills/system/{system-config → system-clash-proxy-config}/references/locale-windows.md +0 -0
  249. /package/skills/system/{system-proxy → system-clash-proxy-config}/references/network-performance.md +0 -0
  250. /package/skills/system/{system-clash-tun-egress → system-clash-proxy-config}/references/nodes-and-dns.md +0 -0
  251. /package/skills/system/{system-proxy → system-clash-proxy-config}/references/platform-dns.md +0 -0
  252. /package/skills/system/{system-proxy → system-clash-proxy-config}/references/platforms.md +0 -0
  253. /package/skills/system/{system-proxy → system-clash-proxy-config}/references/tun-dns.md +0 -0
@@ -3,13 +3,7 @@ import os from 'node:os';
3
3
  import path from 'node:path';
4
4
  import { randomUUID } from 'node:crypto';
5
5
  import { isDeepStrictEqual } from 'node:util';
6
- import {
7
- documentStamp, expectId, hasOwn, isId, requireThat, revisionOf, sameStamp, validateState,
8
- } from './contract.mjs';
9
-
10
- const stateName = 'state.json';
11
- const lockName = '.state.lock';
12
- const emptyState = () => ({ formatVersion: 1, projects: {} });
6
+ import { expectId, isId, requireThat, revisionOf, validateProjectFile } from './contract.mjs';
13
7
 
14
8
  function sameFile(first, second) {
15
9
  // Node 22 on Windows may report dev=0 when looking up the same file by path.
@@ -25,11 +19,11 @@ export function openStore(home, filesystem = fs) {
25
19
  requireThat(regularDirectory(info(requested)), 'UNSAFE_HOME', 'Home 根必须是已有普通目录。');
26
20
  const root = filesystem.realpathSync.native(requested);
27
21
 
28
- function directory(create = false) {
22
+ function directory(create = false, segments = ['.agents', 'home', 'website', 'changelogs']) {
29
23
  requireThat(regularDirectory(info(requested)) && filesystem.realpathSync.native(requested) === root,
30
24
  'UNSAFE_HOME', 'Home 根在操作期间发生变化。');
31
25
  let current = root;
32
- for (const segment of ['.agents', 'home', 'changelogs']) {
26
+ for (const segment of segments) {
33
27
  current = path.join(current, segment);
34
28
  let entry = info(current);
35
29
  if (!entry) {
@@ -43,48 +37,39 @@ export function openStore(home, filesystem = fs) {
43
37
  return current;
44
38
  }
45
39
 
46
- function filename(name) {
47
- const base = directory();
48
- return base === null ? null : path.join(base, name);
40
+ function projectName(id) {
41
+ expectId(id);
42
+ return id + '.json';
49
43
  }
50
44
 
51
- function read(name) {
52
- const target = filename(name);
53
- const entry = target === null ? null : info(target);
45
+ function read(name, segments) {
46
+ const base = directory(false, segments);
47
+ if (base === null) return null;
48
+ const target = path.join(base, name);
49
+ const entry = info(target);
54
50
  if (!entry) return null;
55
- requireThat(entry.isFile() && !entry.isSymbolicLink(), 'UNSAFE_PATH', `${name} 必须是同仓普通文件。`);
51
+ requireThat(entry.isFile() && !entry.isSymbolicLink(), 'UNSAFE_PATH', name + ' 必须是同仓普通文件。');
56
52
  const fd = filesystem.openSync(target, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
57
53
  try {
58
54
  const opened = filesystem.fstatSync(fd);
59
- requireThat(opened.isFile() && sameFile(opened, entry),
60
- 'UNSAFE_PATH', `${name} 已被替换。`);
55
+ requireThat(opened.isFile() && sameFile(opened, entry), 'UNSAFE_PATH', name + ' 已被替换。');
61
56
  const bytes = filesystem.readFileSync(fd);
62
- const current = filename(name) === target && info(target);
57
+ const current = directory(false, segments) === base && info(target);
63
58
  requireThat(current?.isFile() && sameFile(current, opened),
64
- 'READ_CONFLICT', `${name} 在读取期间发生变化。`);
59
+ 'READ_CONFLICT', name + ' 在读取期间发生变化。');
65
60
  return bytes;
66
61
  } finally { filesystem.closeSync(fd); }
67
62
  }
68
63
 
69
- function readState() {
70
- const bytes = read(stateName);
71
- if (bytes === null) return { state: emptyState(), bytes };
72
- let state;
73
- try { state = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); }
74
- catch { requireThat(false, 'STATE_FORMAT', 'state.json 无法解析,保留现场并暂停写入。'); }
75
- return { state: validateState(state), bytes };
76
- }
77
-
78
- function documentName(id) {
79
- expectId(id);
80
- return `${id}.md`;
81
- }
82
-
83
64
  function view(id) {
84
- const doc = documentName(id);
85
- const { state, bytes } = readState();
86
- const project = hasOwn(state.projects, id) ? state.projects[id] : null;
87
- return { state, stateBytes: bytes, project, previous: project?.ranges.at(-1) ?? null, document: read(doc) };
65
+ const name = projectName(id);
66
+ const bytes = read(name);
67
+ if (bytes === null) return { project: null, previous: null, bytes };
68
+ let data;
69
+ try { data = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); }
70
+ catch { requireThat(false, 'PROJECT_FORMAT', name + ' 无法解析,保留原件。'); }
71
+ const project = validateProjectFile(data, id);
72
+ return { project, previous: project.ranges.at(-1), bytes };
88
73
  }
89
74
 
90
75
  function putFile(target, bytes) {
@@ -95,17 +80,27 @@ export function openStore(home, filesystem = fs) {
95
80
  } finally { filesystem.closeSync(fd); }
96
81
  }
97
82
 
98
- function withLock(action) {
83
+ function withLock(id, action) {
84
+ expectId(id);
99
85
  const base = directory(true);
86
+ const lockName = '.' + id + '.lock';
100
87
  const lock = path.join(base, lockName);
101
88
  const token = JSON.stringify({ pid: process.pid, host: os.hostname(), startedAt: new Date().toISOString(), token: randomUUID() });
102
- try { putFile(lock, token); }
89
+ const stagedLock = path.join(base, '.' + id + '-lock-' + randomUUID() + '.tmp');
90
+ try {
91
+ putFile(stagedLock, token);
92
+ requireThat(directory() === base, 'UNSAFE_PATH', 'Home 日志目录在加锁期间变化。');
93
+ filesystem.linkSync(stagedLock, lock);
94
+ }
103
95
  catch (error) {
104
96
  if (error.code !== 'EEXIST') throw error;
105
97
  const lockBytes = read(lockName);
106
98
  let holder;
107
- try { holder = JSON.parse(lockBytes?.toString('utf8')); } catch { /* An in-flight or interrupted lock can be empty. */ }
108
- requireThat(false, 'LOCK_BUSY', '另一写入者占用 Home 日志短锁,先核实持锁运行。', { lock: holder ?? null });
99
+ try { holder = JSON.parse(lockBytes?.toString('utf8')); } catch { /* A writer may still be writing the lock. */ }
100
+ requireThat(false, 'LOCK_BUSY', '另一写入者占用此项目的短锁,先核实持锁运行。', { lock: holder ?? null });
101
+ }
102
+ finally {
103
+ if (directory() === base && info(stagedLock)?.isFile()) filesystem.unlinkSync(stagedLock);
109
104
  }
110
105
  try { return action(); }
111
106
  finally {
@@ -113,113 +108,113 @@ export function openStore(home, filesystem = fs) {
113
108
  }
114
109
  }
115
110
 
116
- function replace(name, bytes, expected, code, check) {
111
+ function save(id, project, before) {
112
+ const name = projectName(id);
113
+ validateProjectFile(project, id);
114
+ const bytes = Buffer.from(JSON.stringify(project, null, 2) + '\n');
117
115
  const base = directory();
118
116
  requireThat(base, 'UNSAFE_PATH', 'Home 日志目录在更新期间消失。');
119
- const temporary = path.join(base, `.changelog-${randomUUID()}.tmp`);
117
+ const directoryInfo = info(base);
118
+ const temporary = path.join(base, '.' + id + '-' + randomUUID() + '.tmp');
119
+ const target = path.join(base, name);
120
+ const sameDirectory = () => {
121
+ const current = directory() === base && info(base);
122
+ return current && sameFile(current, directoryInfo);
123
+ };
120
124
  try {
121
125
  putFile(temporary, bytes);
122
- requireThat(sameStamp(documentStamp(read(name)), expected), code, `${name} 已变化,重新读取后再处理。`);
123
- check?.();
124
- requireThat(directory() === base, 'UNSAFE_PATH', 'Home 日志目录在更新期间变化。');
125
- filesystem.renameSync(temporary, path.join(base, name));
126
+ requireThat(isDeepStrictEqual(read(name), before), 'STALE_CANDIDATE', name + ' 已变化,重新读取后再处理。');
127
+ requireThat(sameDirectory(), 'UNSAFE_PATH', 'Home 日志目录在更新期间变化。');
128
+ if (before === null) {
129
+ // Publishing a hard link to the flushed file cannot overwrite an existing destination.
130
+ try { filesystem.linkSync(temporary, target); }
131
+ catch (error) {
132
+ if (error.code !== 'EEXIST') throw error;
133
+ requireThat(false, 'STALE_CANDIDATE', name + ' 已由另一写入者创建。');
134
+ }
135
+ } else filesystem.renameSync(temporary, target);
136
+ requireThat(isDeepStrictEqual(read(name), bytes), 'READ_CONFLICT', name + ' 写入回读不一致。');
126
137
  } finally {
127
- if (directory() === base && info(temporary)?.isFile()) filesystem.unlinkSync(temporary);
138
+ if (sameDirectory() && info(temporary)?.isFile()) filesystem.unlinkSync(temporary);
128
139
  }
129
140
  }
130
141
 
131
- function saveState(state, before, check) {
132
- validateState(state);
133
- const bytes = Buffer.from(`${JSON.stringify(state, null, 2)}\n`);
134
- replace(stateName, bytes, documentStamp(before), 'STATE_CHANGED', check);
135
- requireThat(sameStamp(documentStamp(read(stateName)), documentStamp(bytes)), 'STATE_CHANGED', 'state.json 写入回读不一致。');
136
- return bytes;
137
- }
138
-
139
- function confirm(id, state, stateBytes, project, record) {
140
- const { pending, ...success } = project;
141
- const saved = { ...record, savedAt: new Date().toISOString() };
142
- const ranges = pending.operation === 'revision'
143
- ? success.ranges.map(range => range.rangeId === saved.rangeId ? saved : range)
144
- : [...success.ranges, saved];
145
- const next = { ...success, ranges, lastSuccessfulRangeId: ranges.at(-1).rangeId };
146
- const hasExpectedDocument = () => requireThat(sameStamp(documentStamp(read(documentName(id))), pending.afterDocument),
147
- 'DOCUMENT_CHANGED', 'Markdown 在最终确认前已变化,保留 pending。');
148
- saveState({ ...state, projects: { ...state.projects, [id]: next } }, stateBytes, hasExpectedDocument);
149
- const result = view(id);
150
- const persisted = result.project?.ranges.find(range => range.rangeId === saved.rangeId);
151
- requireThat(isDeepStrictEqual(persisted, saved) && !result.project.pending
152
- && sameStamp(documentStamp(result.document), pending.afterDocument), 'READ_CONFLICT', '成功记录或 Markdown 回读不一致。');
153
- return persisted;
142
+ function createProject(project) {
143
+ const id = project?.repoId;
144
+ validateProjectFile(project, id);
145
+ return withLock(id, () => {
146
+ const current = view(id);
147
+ if (current.project !== null) {
148
+ requireThat(isDeepStrictEqual(current.project, project), 'PROJECT_EXISTS', '此项目已有内容,保留当前 JSON。');
149
+ return { status: 'already-saved', project: current.project };
150
+ }
151
+ save(id, project, null);
152
+ return { status: 'saved', project };
153
+ });
154
154
  }
155
155
 
156
- function commit(id, expected, record, document, { revision = false } = {}) {
157
- return withLock(() => {
156
+ function commit(id, expected, record, { revision = false, displayName } = {}) {
157
+ return withLock(id, () => {
158
158
  const current = view(id);
159
- requireThat(!current.project?.pending, 'PENDING', '该项目存在待恢复写入,先执行 recover。');
160
159
  const prior = current.project?.ranges.find(range => range.rangeId === record.rangeId);
161
- if (revision && prior && prior.revisionRequest === record.revisionRequest
162
- && sameStamp(documentStamp(current.document), documentStamp(document))) {
163
- return { status: 'already-saved', record: prior };
164
- }
165
- if (!revision && current.previous?.rangeId === record.rangeId) {
166
- requireThat(current.document !== null, 'DOCUMENT_MISSING', '成功记录对应的 Markdown 丢失,先恢复正文。');
167
- return { status: 'already-saved', record: current.previous };
168
- }
169
- requireThat(revisionOf(current.project) === expected.projectRevision
170
- && sameStamp(documentStamp(current.document), expected.document), 'STALE_CANDIDATE', '项目状态或 Markdown 已变化,重读后重新生成。');
171
- if (revision && prior && prior.firstCommitAt === record.firstCommitAt
172
- && isDeepStrictEqual(prior.displayDates, record.displayDates) && isDeepStrictEqual(prior.ledger, record.ledger)
173
- && sameStamp(expected.document, documentStamp(document))) {
174
- return { status: 'already-saved', record: prior };
175
- }
176
- const pending = {
177
- transactionId: randomUUID(), rangeId: record.rangeId, expectedProjectRevision: expected.projectRevision,
178
- beforeDocument: expected.document, afterDocument: documentStamp(document), nextRecord: record,
179
- ...(revision ? { operation: 'revision' } : {}),
160
+ if (!revision && prior) return { status: 'already-saved', record: prior };
161
+ if (revision && prior?.revisionRequest && prior.revisionRequest === record.revisionRequest
162
+ && isDeepStrictEqual(prior.ledger, record.ledger)) return { status: 'already-saved', record: prior };
163
+ requireThat(revisionOf(current.project) === expected.projectRevision,
164
+ 'STALE_CANDIDATE', '项目 JSON 已变化,重读后重新生成。');
165
+ if (revision) requireThat(prior, 'RANGE_NOT_FOUND', '项目中没有该成功区间。');
166
+ const saved = { ...record, savedAt: new Date().toISOString() };
167
+ const project = current.project ?? {
168
+ schemaVersion: 1, repoId: id, initialization: record.initialization, ranges: [],
169
+ ...(displayName === undefined ? {} : { displayName }),
180
170
  };
181
- const project = {
182
- ...(current.project ?? { initialization: record.initialization, ranges: [], lastSuccessfulRangeId: null }), pending,
183
- };
184
- const state = { ...current.state, projects: { ...current.state.projects, [id]: project } };
185
- const intentBytes = saveState(state, current.stateBytes);
186
- if (!sameStamp(pending.beforeDocument, pending.afterDocument)) {
187
- replace(documentName(id), document, pending.beforeDocument, 'DOCUMENT_CHANGED');
188
- }
189
- requireThat(sameStamp(documentStamp(read(documentName(id))), pending.afterDocument), 'DOCUMENT_CHANGED', 'Markdown 写入回读不一致,保留 pending。');
190
- return { status: 'saved', record: confirm(id, state, intentBytes, project, record) };
171
+ const ranges = revision ? project.ranges.map(range => range.rangeId === saved.rangeId ? saved : range)
172
+ : [...project.ranges, saved];
173
+ save(id, { ...project, ranges, lastSuccessfulRangeId: ranges.at(-1).rangeId }, current.bytes);
174
+ return { status: 'saved', record: saved };
191
175
  });
192
176
  }
193
177
 
194
178
  function recover(id) {
195
179
  expectId(id);
196
- if (!view(id).project?.pending) return { status: 'no-pending' };
197
- return withLock(() => {
198
- const { state, stateBytes, project, previous, document } = view(id);
199
- if (!project?.pending) return { status: 'no-pending' };
200
- const { pending, ...success } = project;
201
- const stamp = documentStamp(document);
202
- if (sameStamp(stamp, pending.afterDocument)) {
203
- return { status: 'confirmed', record: confirm(id, state, stateBytes, project, pending.nextRecord) };
204
- }
205
- requireThat(sameStamp(stamp, pending.beforeDocument), 'RECOVERY_CONFLICT', 'Markdown 与写入前后摘要均不同,保留正文和 pending。');
206
- const projects = { ...state.projects };
207
- if (previous) projects[id] = success;
208
- else delete projects[id];
209
- saveState({ ...state, projects }, stateBytes, () => requireThat(
210
- sameStamp(documentStamp(read(documentName(id))), pending.beforeDocument), 'RECOVERY_CONFLICT', 'Markdown 在恢复时发生变化,保留 pending。',
211
- ));
212
- return { status: 'cleared', record: previous };
213
- });
180
+ const { project, previous } = view(id);
181
+ const lock = read('.' + id + '.lock');
182
+ return { status: project === null ? 'missing' : 'no-pending',
183
+ ...(previous ? { record: previous } : {}), ...(lock ? { lockPresent: true } : {}) };
214
184
  }
215
185
 
216
186
  function list() {
217
187
  const base = directory();
218
188
  if (base === null) return [];
219
189
  return filesystem.readdirSync(base, { withFileTypes: true })
220
- .filter(entry => entry.isFile() && entry.name.endsWith('.md') && isId(entry.name.slice(0, -3)))
221
- .map(entry => entry.name.slice(0, -3)).sort();
190
+ .filter(entry => entry.isFile() && entry.name.endsWith('.json') && isId(entry.name.slice(0, -5)))
191
+ .map(entry => entry.name.slice(0, -5)).sort();
192
+ }
193
+
194
+ function resolveId(query) {
195
+ const tracked = list();
196
+ if (tracked.includes(query)) return query;
197
+ const bytes = read('repos.json', ['.agents', 'home']);
198
+ const registry = bytes ? JSON.parse(new TextDecoder('utf-8', {fatal:true}).decode(bytes)) : {repos:[]};
199
+ requireThat(Array.isArray(registry.repos), 'INVALID_REGISTRY', 'repos.json 缺少项目登记数组。');
200
+ const registered = new Map(registry.repos.map(repo => [repo.id, repo]));
201
+ if (registered.has(query)) return query;
202
+ const names = new Map(Object.entries(registry.projectNames ?? {}));
203
+ const knownIds = new Set([...tracked, ...registered.keys()]);
204
+ const unchecked = [query, ...[...names].filter(([, name]) => name === query).map(([id]) => id)]
205
+ .filter(id => isId(id) && !knownIds.has(id));
206
+ if (unchecked.length) {
207
+ const config = read('site.config.json', ['.agents', 'home', 'website']);
208
+ const bindings = config && JSON.parse(config).overrides;
209
+ for (const id of unchecked) if (registered.has(bindings?.[id]?.submoduleOf)) knownIds.add(id);
210
+ if (knownIds.has(query)) return query;
211
+ }
212
+ const matches = [...knownIds].filter(id => names.get(id) === query || registered.get(id)?.aliases?.includes(query));
213
+ requireThat(matches.length <= 1, 'AMBIGUOUS_PROJECT', '项目名称重名,请使用准确 ID:' + matches.join('、'));
214
+ if (matches.length) return matches[0];
215
+ requireThat(isId(query), 'PROJECT_MISSING', '未找到该名称对应的项目。');
216
+ return query;
222
217
  }
223
218
 
224
- return { root, view, commit, recover, list, show: id => read(documentName(id)) };
219
+ return { root, view, commit, createProject, recover, list, resolveId, show: id => view(id).bytes };
225
220
  }
@@ -48,63 +48,3 @@ export function candidateEntries(candidate, snapshot, git) {
48
48
  }
49
49
  return candidate.entries;
50
50
  }
51
-
52
- function oneLine(text) {
53
- return text.trim().replace(/[[\]]/gu, '\\$&');
54
- }
55
-
56
- export function section(record, entries) {
57
- const { displayDates: { from, to }, kind, stats } = record;
58
- const parts = [`## ${from ? `${from} 至 ${to}` : to}`];
59
- if (kind === 'delta') {
60
- if (record.previousRangeId === null) parts.push('指定起点之前的变更未回填。');
61
- if (record.changeReason) parts.push('本次按新指定的引用继续记录。');
62
- } else if (kind === 'baseline' || kind === 'rebaseline') {
63
- const lead = kind === 'rebaseline' ? '重新建立基线。' : record.initialization.mode === 'from' ? '所选初始区间为空。' : '';
64
- parts.push(`${lead}从 ${to} 开始记录,之前的变更未回填。`);
65
- }
66
- if (record.freshness === 'remote-cache') parts.push('本次采用本地缓存,远端新鲜度未验证。');
67
- const byCategory = new Map(categories.map(category => [category, []]));
68
- for (const entry of entries) byCategory.get(entry.category).push(entry);
69
- const columns = ['变更总数', ...categories, '本次提交'];
70
- const counts = [entries.length, ...categories.map(category => byCategory.get(category).length), stats.rangeCommitCount];
71
- const features = byCategory.get('功能');
72
- if (features.length && features.every(entry => typeof entry.added === 'boolean')) {
73
- columns.push('新增');
74
- counts.push(features.filter(entry => entry.added).length);
75
- }
76
- const row = cells => `| ${cells.join(' | ')} |`;
77
- parts.push([
78
- row(columns),
79
- row(columns.map(() => '---:')),
80
- row(counts.map(count => count.toLocaleString('en-US'))),
81
- ].join('\n'));
82
- for (const [category, group] of byCategory) {
83
- const items = group.map(entry => {
84
- const impacts = [...new Set(entry.markers)].map(marker => `**[${marker}]**`).join(' ');
85
- const source = entry.date ? `${entry.date} · ${entry.area ? oneLine(entry.area) : '—'} · ` : '';
86
- return `- ${source}${impacts ? `${impacts} ` : ''}${oneLine(entry.text)}`;
87
- });
88
- if (items.length) parts.push(`### ${category}`, items.join('\n'));
89
- }
90
- if (record.coverage === 'complete' && !entries.length) parts.push('本次没有需单列的变更。');
91
- return parts.join('\n\n');
92
- }
93
-
94
- export function renderNext(before, repoId, displayName, record, entries) {
95
- const body = section(record, entries);
96
- if (before === null || !before.length) return Buffer.from(`# ${oneLine(displayName ?? repoId)} 变更日志\n\n${body}\n`);
97
- let existing;
98
- try { existing = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(before); }
99
- catch { requireThat(false, 'DOCUMENT_FORMAT', '已有 Markdown 需要可读的 UTF-8 内容,保留原件。'); }
100
- const start = existing.match(/^\uFEFF?(?:(?:---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$))?(?:[ \t]*\r?\n)*# [^\r\n]+(?:\r?\n|$)|(?:---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)))/u)?.[0]
101
- ?? (existing.startsWith('\uFEFF') ? '\uFEFF' : '');
102
- const at = Buffer.byteLength(start);
103
- const insertion = `${at && start !== '\uFEFF' ? (start.endsWith('\n') ? '\n' : '\n\n') : ''}${body}\n${at < before.length ? '\n' : ''}`;
104
- const newline = existing.match(/\r?\n/u)?.[0] ?? '\n';
105
- return Buffer.concat([
106
- before.subarray(0, at),
107
- Buffer.from(insertion.replaceAll('\n', newline)),
108
- before.subarray(at),
109
- ]);
110
- }
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: home-route
3
- description: 只读定位已登记项目,解析项目名、别名、分组、本机路径覆盖或指定 worktree。用于「项目在哪里」「这个名字指哪个仓库」「用这个 worktree」,核对实际 checkout、Git 远端身份和资料入口。更新登记用 home-setup,诊断已发现的结构异常用 home-doctor。
3
+ description: 按稳定 ID、用户指定的名称或其他别名查找已登记项目、子模块和项目日志,支持分组、本机路径覆盖与指定 worktree。用于「项目在哪里」「这个名字指哪个仓库」「用这个 worktree」,核对实际 checkout、Git 远端身份和资料入口。更新登记用 home-setup,诊断已发现的结构异常用 home-doctor。
4
4
  ---
5
5
 
6
6
  # 定位项目与实际 checkout
@@ -11,7 +11,7 @@ description: 只读定位已登记项目,解析项目名、别名、分组、
11
11
 
12
12
  先读取下述 Home 主入口,再读[路由与身份核查](references/routing.md)。同一上下文已读同一根、同一版本的入口可复用;新会话、压缩后缺失、入口更新或换根时重读。入口读不到先核对根、路径和安装状态,可用时调用 `home-doctor`;无需先成功读取才能做最小只读诊断。
13
13
 
14
- 1. 从实际 Home 根读取 `./.agents/home/AGENTS.md`。按用户所指 ID、别名或分组读取登记及合法本机路径覆盖。准确 ID 优先,别名重名时返回候选,以登记和用户明确指定的目标核对身份。
14
+ 1. 从实际 Home 根读取 `./.agents/home/AGENTS.md`。优先匹配稳定 ID,再匹配 `repos.json` 的 `projectNames` 和登记项 `aliases`。重名时列候选。只有分仓日志的项目返回日志位置。已声明的子模块可经父仓核对 checkout。分组查询限于登记项目。
15
15
  2. 按显式 checkout → local.json → 登记路径选择入口。核对真实路径、Git root、主 remote 和 common directory,支持 `.git` 为文件的 worktree;路径指向不同仓库时停止该目标。v2 按指定主 remote 的首 fetch URL 核验,其他 remote 的变动单独报告;旧 v1 沿用原身份规则。
16
16
  3. 只确认统一入口是否存在;项目资料引用只解析 `repo ID + checkout 内相对路径`,不读取正文或扫描项目知识。
17
17
  4. 将解析结果交回调用者。项目调查和开发由 `home-workflow` 按用户选择调用当地派遣方法。已授权的 Git 区间采集交 `home-project-changelog`。登记修改交 `home-setup`,结构异常交 `home-doctor`。
@@ -2,7 +2,9 @@
2
2
 
3
3
  ## 输入与选择
4
4
 
5
- 读取 Home 的 `.agents/home/repos.json`;当前新登记为 `formatVersion: 2`,继续读取旧 v1;完整写入校验归 `home-setup`。未知版本明确失败。精确 repo ID 优先于同名 alias,别名可同时命中多个项目,返回其 ID、用途和默认路径,让用户或已有上下文消解。分组必须显式请求,不将名称相似视为同组。
5
+ 读取 Home 的 `.agents/home/repos.json`;当前新登记为 `formatVersion: 2`,继续读取旧 v1;完整写入校验归 `home-setup`。未知版本明确失败。`--repo` 先精确匹配登记或日志的稳定 ID,再匹配 `projectNames` 中的首选名称及登记项 `aliases`。同一项目只返回一次,多个匹配返回 `ambiguous` 和候选 ID。显式 `--group` 只匹配登记分组。
6
+
7
+ 只有分仓 JSON 时,普通查询返回 `changelog_only`、稳定 ID 和日志路径,可直接查看历史。已配置 `submoduleOf` 的项目,根据父仓 HEAD 的 gitlink、`.gitmodules` 路径和本地初始化的 remote 核验子模块,返回 `resolved` 和实际 checkout。派遣、查询分支和补采 Git 均需要已核实的 checkout。
6
8
 
7
9
  本机覆盖只接受:
8
10
 
@@ -83,10 +83,16 @@ function readJson(filename, optional = false) {
83
83
  catch (error) { fail('INVALID_JSON', `${filename} 无法读取为 JSON(${error.code || '语法错误'})。`); }
84
84
  }
85
85
 
86
- export function readRegistry(homeRoot) {
86
+ export function readRegistry(homeRoot, { optional = false } = {}) {
87
87
  homeRoot = homePath(homeRoot);
88
- const value = readJson(path.join(homeRoot, '.agents/home/repos.json'));
88
+ const value = readJson(path.join(homeRoot, '.agents/home/repos.json'), optional);
89
+ if (value === undefined) return { formatVersion: 2, repos: [] };
89
90
  if (![1, 2].includes(value?.formatVersion) || !Array.isArray(value.repos)) fail('REGISTRY_VERSION', '只读取 formatVersion: 1 或 2 的 repos 数组;未知版本不猜测迁移。');
91
+ const names = value.projectNames;
92
+ if (names !== undefined && (!names || typeof names !== 'object' || Array.isArray(names) ||
93
+ Object.entries(names).some(([id, name]) => !/^[a-z0-9][a-z0-9-]*$/u.test(id) || !text(name) || name.trim() !== name))) {
94
+ fail('INVALID_REGISTRY', 'repos.json 的 projectNames 需要稳定 ID 与单行首选名称。');
95
+ }
90
96
  const ids = new Set();
91
97
  for (const repo of value.repos) {
92
98
  if (!repo || !/^[a-z0-9][a-z0-9-]*$/u.test(repo.id || '') || ids.has(repo.id) || !text(repo.localPath)) {
@@ -138,11 +144,41 @@ export function readLocalPaths(homeRoot, registry) {
138
144
  return value.paths;
139
145
  }
140
146
 
141
- export function selectRepos(registry, query, { group = false } = {}) {
147
+ function trackedProjects(homeRoot, registry, query) {
148
+ const registered = new Set(registry.repos.map(repo => repo.id));
149
+ const ids = new Set(Object.entries(registry.projectNames ?? {})
150
+ .filter(([id, name]) => name === query && !registered.has(id)).map(([id]) => id));
151
+ if (/^[a-z0-9][a-z0-9-]*$/u.test(query) && !registered.has(query)) ids.add(query);
152
+ if (!ids.size) return [];
153
+ const website = path.join(homeRoot, '.agents/home/website');
154
+ const logs = path.join(website, 'changelogs');
155
+ function hasDirectory(directory) {
156
+ const entry = fs.lstatSync(directory, { throwIfNoEntry: false });
157
+ if (entry && !entry.isDirectory()) fail('UNSAFE_FILE', '项目日志须位于 Home 内的普通目录。');
158
+ return Boolean(entry);
159
+ }
160
+ if (!hasDirectory(website)) return [];
161
+ const hasLogs = hasDirectory(logs);
162
+ const site = readJson(path.join(website, 'site.config.json'), true);
163
+ const projects = [];
164
+ for (const id of ids) {
165
+ const entry = hasLogs && fs.lstatSync(path.join(logs, id + '.json'), {throwIfNoEntry:false});
166
+ if (entry && !entry.isFile()) fail('UNSAFE_FILE', '项目日志须为普通文件。');
167
+ const binding = site?.overrides?.[id];
168
+ if (entry || binding?.submoduleOf) projects.push({id, ...(entry && {changelog:'.agents/home/website/changelogs/' + id + '.json'}),
169
+ ...(binding?.submoduleOf && {parent:binding.submoduleOf, submodulePath:binding.submodulePath ?? id})});
170
+ }
171
+ return projects;
172
+ }
173
+
174
+ export function selectRepos(registry, query, { group = false, tracked = [] } = {}) {
142
175
  if (!text(query)) fail('MISSING_QUERY', '提供准确 repo ID、别名或显式分组。');
143
176
  if (group) return registry.repos.filter(repo => (repo.groups || []).includes(query));
144
- const exact = registry.repos.find(repo => repo.id === query);
145
- return exact ? [exact] : registry.repos.filter(repo => (repo.aliases || []).includes(query));
177
+ const candidates = new Map(tracked.map(repo => [repo.id, repo]));
178
+ for (const repo of registry.repos) candidates.set(repo.id, repo);
179
+ if (candidates.has(query)) return [candidates.get(query)];
180
+ const names = new Map(Object.entries(registry.projectNames ?? {}));
181
+ return [...candidates.values()].filter(repo => names.get(repo.id) === query || repo.aliases?.includes(query));
146
182
  }
147
183
 
148
184
  function git(cwd, args, { optional = false, missing = [], raw = false } = {}) {
@@ -265,6 +301,25 @@ export function routeRepo(homeRoot, repo, { localPaths = {}, checkout, reference
265
301
  return result;
266
302
  }
267
303
 
304
+ export function routeSubmodule(home, registry, id, {parent, submodulePath = id}, options = {}) {
305
+ const owner = registry.repos.find(repo => repo.id === parent);
306
+ if (!owner || id === parent || !text(submodulePath) || !submodulePath.split('/').every(part => /^[a-zA-Z0-9_-][a-zA-Z0-9._-]*$/u.test(part))) {
307
+ fail('INVALID_SUBMODULE', '子模块需要已登记的父仓和有效的相对检出路径。');
308
+ }
309
+ const base = routeRepo(home, owner, {localPaths:options.localPaths, branchOnly:true}).actualCheckout;
310
+ const link = git(base, ['ls-tree','HEAD','--',submodulePath]);
311
+ if (!link.startsWith('160000 commit ') || link.split('\t')[1] !== submodulePath) fail('INVALID_SUBMODULE', '父仓 HEAD 缺少该路径的 Git 子模块。');
312
+ const paths = git(base, ['config','--blob','HEAD:.gitmodules','--get-regexp','^submodule\\..*\\.path$']);
313
+ const entry = paths.split(/\r?\n/u).find(line => line.slice(line.indexOf(' ') + 1) === submodulePath);
314
+ if (!entry) fail('INVALID_SUBMODULE', '父仓 .gitmodules 缺少该子模块。');
315
+ const key = entry.slice(0, entry.indexOf(' ')).replace(/\.path$/u, '.url');
316
+ const remote = git(base, ['config','--local','--get',key]);
317
+ const location = resolveReference(base, submodulePath);
318
+ if (!remote || !location.exists || !exists(path.join(location.realTarget, '.git'))) fail('INVALID_SUBMODULE', '子模块尚未初始化。');
319
+ const route = routeRepo(home, {id, localPath:location.realTarget, remote}, {...options, localPaths:{}});
320
+ return {...route, parent, submodulePath, pathSource:options.checkout ? 'explicit-checkout' : 'submodule'};
321
+ }
322
+
268
323
  function compareRemotes(registered, actual) {
269
324
  const before = new Map(registered.map(remote => [remote.name, remote]));
270
325
  const after = new Map(actual.map(remote => [remote.name, remote]));
@@ -304,7 +359,7 @@ export function main(argv = process.argv.slice(2)) {
304
359
  try {
305
360
  const options = parseArgs(argv);
306
361
  if (options.help) {
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。');
362
+ 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。');
308
363
  return 0;
309
364
  }
310
365
  if (options['check-fetch']) {
@@ -326,17 +381,30 @@ export function main(argv = process.argv.slice(2)) {
326
381
  if (options.branchOnly && (!options.repo || options.checkout || options.ref)) fail('USAGE', '--branch-only 仅用于按登记路径查询单个项目,不读取 dirty 状态。');
327
382
  if (options.group && options.checkout) fail('USAGE', '一个 --checkout 不能覆盖整组仓库;分别解析准确 ID。');
328
383
  const homeRoot = homePath(options.home);
329
- const registry = readRegistry(homeRoot);
330
- const localPaths = readLocalPaths(homeRoot, registry);
331
- const selected = selectRepos(registry, options.repo || options.group, { group: Boolean(options.group) });
384
+ const registry = readRegistry(homeRoot, {optional: Boolean(options.repo)});
385
+ const tracked = options.repo && !registry.repos.some(repo => repo.id === options.repo) ? trackedProjects(homeRoot, registry, options.repo) : [];
386
+ const selected = selectRepos(registry, options.repo || options.group, { group: Boolean(options.group), tracked });
332
387
  if (!selected.length) { console.log(JSON.stringify({ status: 'not_found', query: options.repo || options.group })); return 3; }
333
388
  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; }
389
+ const checkoutOptions = { checkout:options.checkout, reference:options.ref, branchOnly:options.branchOnly };
390
+ const localPaths = selected.some(repo => repo.localPath || repo.parent) ? readLocalPaths(homeRoot, registry) : {};
334
391
  const results = selected.map(repo => {
335
- try { return routeRepo(homeRoot, repo, { localPaths, checkout: options.checkout, reference: options.ref, branchOnly: options.branchOnly }); }
392
+ try {
393
+ const label = Object.hasOwn(registry.projectNames ?? {}, repo.id) ? {displayName:registry.projectNames[repo.id]} : {};
394
+ if (repo.parent) {
395
+ const route = routeSubmodule(homeRoot, registry, repo.id, repo, {...checkoutOptions, localPaths});
396
+ return {...route, ...(repo.changelog && {changelog:repo.changelog}), ...label};
397
+ }
398
+ if (!repo.changelog) return {...routeRepo(homeRoot, repo, {...checkoutOptions, localPaths}), ...label};
399
+ const saved = readJson(path.join(homeRoot, repo.changelog));
400
+ if (saved?.schemaVersion !== 1 || saved.repoId !== repo.id) fail('INVALID_CHANGELOG', '日志身份与项目 ID 不符。');
401
+ if (options.checkout || options.ref || options.branchOnly) fail('CHECKOUT_NOT_REGISTERED', '已找到项目日志,核对 checkout 需要登记或已声明的子模块关系。');
402
+ return {status:'changelog_only', repoId:repo.id, changelog:repo.changelog, ...label};
403
+ }
336
404
  catch (error) { return { status: 'conflict', repoId: repo.id, code: error.code || 'CHECK_FAILED', message: error.message }; }
337
405
  });
338
406
  console.log(JSON.stringify(options.group ? { status: results.every(result => result.status === 'resolved') ? 'resolved' : 'partial', results } : results[0], null, 2));
339
- return results.every(result => result.status === 'resolved') ? 0 : 3;
407
+ return results.every(result => ['resolved','changelog_only'].includes(result.status)) ? 0 : 3;
340
408
  } catch (error) {
341
409
  console.error(JSON.stringify({ status: 'invalid', code: error.code || 'READ_FAILED', message: error.message }));
342
410
  return 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 与用户配置
@@ -14,6 +14,7 @@ description: 初始化 Home 及其主要入口、给已有 Home 补 Git 或白
14
14
  | 任务 | 必读方法 | 产物 |
15
15
  | --- | --- | --- |
16
16
  | 完整初始化 Home,含已有 `.git` 的目录 | [Git 基线与换机恢复](references/git.md)、[根导航与交付](references/registry.md#根导航与交付)、[派遣与团队初始化](references/dispatch.md),有项目时读[登记方法](references/registry.md) | 本地 Git、跟踪校验、根短入口、默认派遣方式与 team、适用的登记 |
17
+ | 给登记项目、子模块或仅有日志的项目命名或改名 | [项目首选名称](references/registry.md#项目首选名称) | `repos.json` 的 `projectNames`,已有网站按现有日志刷新 |
17
18
  | 给已有 Home 补 Git、检查跟踪范围、克隆 Home 后恢复项目 | [Git 基线与换机恢复](references/git.md) | 可提交的 Home 基线或逐项目恢复结果 |
18
19
  | 只补初始化派遣 | [派遣与团队初始化](references/dispatch.md) | 默认派遣方式与 Home team |
19
20
  | 登记、移址、解除登记、刷新当前分支或查看、导出项目清单 | [登记与入口](references/registry.md) | repos.json、逐项目分支刷新结果、按需地图 |
@@ -13,6 +13,16 @@
13
13
  2
14
14
  ]
15
15
  },
16
+ "projectNames": {
17
+ "description": "用户指定的首选名称,键为已登记、已声明为子模块或已有项目日志的稳定 ID。",
18
+ "type": "object",
19
+ "propertyNames": { "pattern": "^[a-z0-9][a-z0-9-]*$" },
20
+ "additionalProperties": {
21
+ "type": "string",
22
+ "minLength": 1,
23
+ "pattern": "^(?=\\S)(?![\\s\\S]*\\s$)[^\\u0000-\\u001f\\u007f]+$"
24
+ }
25
+ },
16
26
  "repos": {
17
27
  "type": "array"
18
28
  }