@jjh32456/longlive 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (331) hide show
  1. package/CHANGELOG.md +235 -0
  2. package/LICENSE +21 -0
  3. package/QUICKSTART.md +362 -0
  4. package/README.en.md +64 -0
  5. package/README.md +256 -2
  6. package/SPEC.md +211 -0
  7. package/build-info.json +1665 -0
  8. package/cordis.patch.yml +208 -0
  9. package/docs/A1-MIGRATION.md +75 -0
  10. package/docs/ANSWER-GUARD.md +92 -0
  11. package/docs/ARCHITECTURE.md +128 -0
  12. package/docs/AUTO-RECALL-WIRING.md +115 -0
  13. package/docs/AUTO-RECALL.md +237 -0
  14. package/docs/CONCEPTS.md +143 -0
  15. package/docs/CONFIG.md +839 -0
  16. package/docs/ERRORS.md +271 -0
  17. package/docs/FAQ.md +186 -0
  18. package/docs/FEATURES.md +579 -0
  19. package/docs/INDEX-FRESHNESS.md +21 -0
  20. package/docs/METRICS.md +244 -0
  21. package/docs/MIGRATION-1.6.0.md +220 -0
  22. package/docs/OPERATIONS.md +439 -0
  23. package/docs/PANEL-INTEGRATION.md +190 -0
  24. package/docs/PRIVACY.md +88 -0
  25. package/docs/QUICKSTART.md +155 -0
  26. package/docs/RAW-INDEX-POLICY.md +7 -0
  27. package/docs/README.en.md +48 -0
  28. package/docs/RESIDENT-WATCHER.md +90 -0
  29. package/docs/SESSION-WATCH.md +214 -0
  30. package/docs/TOOLS.md +184 -0
  31. package/docs/TROUBLESHOOTING.md +329 -0
  32. package/icon.svg +11 -0
  33. package/lib/client.js +436 -0
  34. package/locale/en.json +6 -0
  35. package/locale/zh.json +6 -0
  36. package/package.json +163 -4
  37. package/runbook.md +343 -0
  38. package/scripts/archive-digest-build.mjs +668 -0
  39. package/scripts/auto-truncate-run.ps1 +752 -0
  40. package/scripts/backfill-auto-cards.mjs +98 -0
  41. package/scripts/edges-build.mjs +1003 -0
  42. package/scripts/index-maintain.mjs +39 -0
  43. package/scripts/index-reconcile.mjs +49 -0
  44. package/scripts/index-status.mjs +28 -0
  45. package/scripts/install-resident-watcher.ps1 +15 -0
  46. package/scripts/install-session-watch.ps1 +332 -0
  47. package/scripts/install-surgery-task.ps1 +174 -0
  48. package/scripts/lib/auto-truncate-run.ps1 +512 -0
  49. package/scripts/lib/session-watch-fixture.mjs +207 -0
  50. package/scripts/longlive-doctor.mjs +578 -0
  51. package/scripts/metrics-read.mjs +79 -0
  52. package/scripts/metrics-sample.mjs +215 -0
  53. package/scripts/migrate-180.mjs +163 -0
  54. package/scripts/migrate-200.mjs +8 -0
  55. package/scripts/migrate-a1-legacy.mjs +62 -0
  56. package/scripts/migrate-lifecycle.mjs +157 -0
  57. package/scripts/pack.mjs +392 -0
  58. package/scripts/recall-index-build.mjs +128 -0
  59. package/scripts/recall-links-build.mjs +420 -0
  60. package/scripts/rescore-cards.mjs +36 -0
  61. package/scripts/resident-watcher-status.ps1 +15 -0
  62. package/scripts/resident-watcher.ps1 +643 -0
  63. package/scripts/session-watch-drill.mjs +553 -0
  64. package/scripts/session-watch-status.ps1 +146 -0
  65. package/scripts/session-watch.mjs +1367 -0
  66. package/scripts/surgery-inspect.mjs +122 -0
  67. package/scripts/surgery-run.cmd +34 -0
  68. package/scripts/truncate-cli.mjs +279 -0
  69. package/scripts/unattended-surgery.ps1 +1019 -0
  70. package/scripts/uninstall-resident-watcher.ps1 +15 -0
  71. package/scripts/uninstall-session-watch.ps1 +192 -0
  72. package/scripts/verify-card-anchors.mjs +138 -0
  73. package/scripts/watch-loop.ps1 +916 -0
  74. package/src/actions/audit.js +125 -0
  75. package/src/actions/evidence.js +122 -0
  76. package/src/actions/fs.js +162 -0
  77. package/src/activity/index.js +873 -0
  78. package/src/activity/model.js +351 -0
  79. package/src/activity/store.js +786 -0
  80. package/src/activity/summary.js +180 -0
  81. package/src/activity/thinking.js +191 -0
  82. package/src/adapters/constants.js +11 -0
  83. package/src/adapters/engram/data/aliases.json +51 -0
  84. package/src/adapters/engram/data/policy.json +8 -0
  85. package/src/adapters/engram/data/routing-rules.json +546 -0
  86. package/src/adapters/engram/index.js +278 -0
  87. package/src/adapters/registry.js +315 -0
  88. package/src/answer/audit.js +238 -0
  89. package/src/answer/claim-guard.mjs +234 -0
  90. package/src/answer/evidence.js +30 -0
  91. package/src/answer/guard.js +1370 -0
  92. package/src/answer/index.js +1086 -0
  93. package/src/answer/query.js +111 -0
  94. package/src/answer/second-hop.mjs +101 -0
  95. package/src/auto-truncate-status.js +164 -0
  96. package/src/auto-truncate.js +1181 -0
  97. package/src/autoprocedure/candidate.js +342 -0
  98. package/src/autoprocedure/config.js +122 -0
  99. package/src/autoprocedure/evidence.js +345 -0
  100. package/src/autoprocedure/index.js +83 -0
  101. package/src/autoprocedure/ledger.js +329 -0
  102. package/src/autoprocedure/lint.js +232 -0
  103. package/src/autoprocedure/llm.js +409 -0
  104. package/src/autoprocedure/locks.js +102 -0
  105. package/src/autoprocedure/paths.js +39 -0
  106. package/src/autoprocedure/privacy.js +87 -0
  107. package/src/autoprocedure/rules.js +288 -0
  108. package/src/autoprocedure/runtime.js +718 -0
  109. package/src/autoprocedure/session-reader.js +328 -0
  110. package/src/backup.js +310 -0
  111. package/src/bus/bus.mjs +1446 -0
  112. package/src/codec.js +269 -0
  113. package/src/compaction/cut-engine.js +44 -0
  114. package/src/compaction/engine-core.js +1237 -0
  115. package/src/compaction/entry.js +228 -0
  116. package/src/compaction.js +230 -0
  117. package/src/conclusion.js +366 -0
  118. package/src/config.js +835 -0
  119. package/src/d6/runtime.js +517 -0
  120. package/src/d6/surface.js +181 -0
  121. package/src/deps.js +189 -0
  122. package/src/engine-status.js +141 -0
  123. package/src/features.js +1035 -0
  124. package/src/handoff/index.js +1077 -0
  125. package/src/handoff/model.js +1058 -0
  126. package/src/handoff/store.js +1233 -0
  127. package/src/heartbeat.js +385 -0
  128. package/src/home.js +16 -0
  129. package/src/host-version.js +280 -0
  130. package/src/hot-truncate-diag.js +98 -0
  131. package/src/identity/card-marker.js +281 -0
  132. package/src/identity/handover.js +845 -0
  133. package/src/identity/index.js +337 -0
  134. package/src/identity/inject-position.js +133 -0
  135. package/src/identity/writeback.js +344 -0
  136. package/src/identity.js +118 -0
  137. package/src/index.js +647 -0
  138. package/src/lifecycle/gap-clocks.js +364 -0
  139. package/src/lifecycle/index.js +269 -0
  140. package/src/lifecycle/proactive.js +1426 -0
  141. package/src/live-target.js +212 -0
  142. package/src/live.js +1603 -0
  143. package/src/log-rotation.js +153 -0
  144. package/src/memory/a1-migration.js +190 -0
  145. package/src/memory/activity-capture.js +229 -0
  146. package/src/memory/anchor-fallback.js +116 -0
  147. package/src/memory/anchors.js +194 -0
  148. package/src/memory/archive-cold-state.mjs +794 -0
  149. package/src/memory/archive-staging.mjs +305 -0
  150. package/src/memory/archive.mjs +415 -0
  151. package/src/memory/audit-records.js +222 -0
  152. package/src/memory/auto-cards.js +441 -0
  153. package/src/memory/capture-host.js +297 -0
  154. package/src/memory/capture.js +496 -0
  155. package/src/memory/card-anchors.js +203 -0
  156. package/src/memory/card-priority.js +110 -0
  157. package/src/memory/cards.js +425 -0
  158. package/src/memory/catchup.mjs +534 -0
  159. package/src/memory/conclusion-distill.js +381 -0
  160. package/src/memory/conclusion-drafts.js +243 -0
  161. package/src/memory/conflicts.js +1060 -0
  162. package/src/memory/consolidate.js +834 -0
  163. package/src/memory/decay.js +311 -0
  164. package/src/memory/distill.js +485 -0
  165. package/src/memory/event-index.js +1826 -0
  166. package/src/memory/evidence-chain.js +295 -0
  167. package/src/memory/evidence.js +213 -0
  168. package/src/memory/filter-runner.js +555 -0
  169. package/src/memory/filter.js +1035 -0
  170. package/src/memory/forget-v2.js +680 -0
  171. package/src/memory/forget.js +531 -0
  172. package/src/memory/frames-activation.js +249 -0
  173. package/src/memory/frontmatter.js +454 -0
  174. package/src/memory/fts-query.js +342 -0
  175. package/src/memory/governance.js +604 -0
  176. package/src/memory/index-freshness.js +234 -0
  177. package/src/memory/index.js +435 -0
  178. package/src/memory/l2-gate.js +169 -0
  179. package/src/memory/land.mjs +743 -0
  180. package/src/memory/lifecycle.js +235 -0
  181. package/src/memory/lock.js +121 -0
  182. package/src/memory/maintenance.js +1149 -0
  183. package/src/memory/manifest.js +245 -0
  184. package/src/memory/memory-health.mjs +607 -0
  185. package/src/memory/migrate-200.js +1681 -0
  186. package/src/memory/migrate-lifecycle.js +1808 -0
  187. package/src/memory/migrate.js +139 -0
  188. package/src/memory/paths.js +229 -0
  189. package/src/memory/procedure-candidate.mjs +377 -0
  190. package/src/memory/procedure.js +982 -0
  191. package/src/memory/prospective-memory.mjs +362 -0
  192. package/src/memory/provenance.js +119 -0
  193. package/src/memory/recall-feedback.mjs +406 -0
  194. package/src/memory/recall-v2.js +218 -0
  195. package/src/memory/recall.js +357 -0
  196. package/src/memory/reconcile.js +265 -0
  197. package/src/memory/records.js +433 -0
  198. package/src/memory/reinforce.js +281 -0
  199. package/src/memory/retention.js +162 -0
  200. package/src/memory/review.js +124 -0
  201. package/src/memory/state.js +279 -0
  202. package/src/memory/tiers.js +168 -0
  203. package/src/memory/topic-phrases.js +73 -0
  204. package/src/memory/trust.js +97 -0
  205. package/src/memory/turn-budget.mjs +290 -0
  206. package/src/memory/version-chain.js +264 -0
  207. package/src/memory/wake-bridge.mjs +2999 -0
  208. package/src/memory/wal.js +137 -0
  209. package/src/memory/working-frame.js +779 -0
  210. package/src/metrics/classify.mjs +191 -0
  211. package/src/metrics/estimate.mjs +108 -0
  212. package/src/metrics/index.mjs +204 -0
  213. package/src/metrics/measure.mjs +462 -0
  214. package/src/metrics/prestep-latency.mjs +307 -0
  215. package/src/metrics/store.mjs +264 -0
  216. package/src/original.js +294 -0
  217. package/src/policy/threshold-policy.js +224 -0
  218. package/src/policy-profile.js +463 -0
  219. package/src/recall/anaphora.mjs +87 -0
  220. package/src/recall/archive-config.mjs +130 -0
  221. package/src/recall/archive-fallback.mjs +390 -0
  222. package/src/recall/archive-search.mjs +428 -0
  223. package/src/recall/archive-state.mjs +588 -0
  224. package/src/recall/brain.mjs +501 -0
  225. package/src/recall/cards.mjs +202 -0
  226. package/src/recall/current-line.mjs +110 -0
  227. package/src/recall/edges.js +398 -0
  228. package/src/recall/embedding.mjs +698 -0
  229. package/src/recall/entities.mjs +112 -0
  230. package/src/recall/explain.mjs +443 -0
  231. package/src/recall/force-policy.mjs +138 -0
  232. package/src/recall/gate-log.mjs +280 -0
  233. package/src/recall/gate-metrics.mjs +191 -0
  234. package/src/recall/index.js +1337 -0
  235. package/src/recall/inject-order.mjs +279 -0
  236. package/src/recall/link-recall.mjs +183 -0
  237. package/src/recall/links.mjs +696 -0
  238. package/src/recall/privacy.mjs +208 -0
  239. package/src/recall/recall-core.mjs +810 -0
  240. package/src/recall/shared-visibility.js +302 -0
  241. package/src/recall/time-normalizer.mjs +196 -0
  242. package/src/recall/turn-budget-inject.mjs +154 -0
  243. package/src/retention/cold-gate.mjs +146 -0
  244. package/src/retention/config.js +163 -0
  245. package/src/retention/index.js +801 -0
  246. package/src/role/activation.js +191 -0
  247. package/src/role/attention.js +318 -0
  248. package/src/role/base.js +36 -0
  249. package/src/role/channels.js +423 -0
  250. package/src/role/index.js +425 -0
  251. package/src/role/interfaces.js +115 -0
  252. package/src/role/personality.js +370 -0
  253. package/src/role/readers.js +151 -0
  254. package/src/role/relationships.js +477 -0
  255. package/src/role/store.js +202 -0
  256. package/src/role/writeprotect.js +373 -0
  257. package/src/router/aliases.json +182 -0
  258. package/src/router/background/agent-runner.mjs +239 -0
  259. package/src/router/background/anchor.mjs +323 -0
  260. package/src/router/background/audit.mjs +337 -0
  261. package/src/router/background/budget-ledger.mjs +648 -0
  262. package/src/router/background/host-sim.mjs +451 -0
  263. package/src/router/background/index.mjs +81 -0
  264. package/src/router/background/memory.mjs +63 -0
  265. package/src/router/background/mock-llm.mjs +203 -0
  266. package/src/router/background/queue.mjs +224 -0
  267. package/src/router/background/retry.mjs +255 -0
  268. package/src/router/background/router.mjs +1459 -0
  269. package/src/router/background/stream.mjs +276 -0
  270. package/src/router/background/tool-policy.mjs +255 -0
  271. package/src/router/design-headings.json +221 -0
  272. package/src/router/face/config.mjs +155 -0
  273. package/src/router/face/context.mjs +284 -0
  274. package/src/router/face/face.mjs +466 -0
  275. package/src/router/face/identity.mjs +130 -0
  276. package/src/router/face/index.mjs +65 -0
  277. package/src/router/face/journal.mjs +119 -0
  278. package/src/router/face/llm.mjs +252 -0
  279. package/src/router/face/outbox.mjs +153 -0
  280. package/src/router/face/paths.mjs +54 -0
  281. package/src/router/judge.mjs +987 -0
  282. package/src/router/policies/generic.json +131 -0
  283. package/src/router/route.js +1766 -0
  284. package/src/router/router.mjs +535 -0
  285. package/src/router/routing-rules.json +816 -0
  286. package/src/router/run-sim.mjs +530 -0
  287. package/src/router/runtime.js +569 -0
  288. package/src/router/service/apply.mjs +1218 -0
  289. package/src/router/service/board.mjs +712 -0
  290. package/src/router/service/caller.mjs +131 -0
  291. package/src/router/service/config.mjs +361 -0
  292. package/src/router/service/context.mjs +314 -0
  293. package/src/router/service/hint.mjs +668 -0
  294. package/src/router/service/lease.mjs +494 -0
  295. package/src/router/service/live.mjs +251 -0
  296. package/src/router/service/lock.mjs +550 -0
  297. package/src/router/service/merge.mjs +255 -0
  298. package/src/router/service/model-resolve.mjs +350 -0
  299. package/src/router/service/paths.mjs +168 -0
  300. package/src/router/service/proposals.mjs +1461 -0
  301. package/src/router/service/queue.mjs +477 -0
  302. package/src/router/service/reconcile.mjs +271 -0
  303. package/src/router/service/service.mjs +2998 -0
  304. package/src/router/service/sources.mjs +352 -0
  305. package/src/router/service/status.mjs +520 -0
  306. package/src/router/service/store.mjs +476 -0
  307. package/src/router/service/ticklock.mjs +239 -0
  308. package/src/router/service/tokens.mjs +95 -0
  309. package/src/router/service/tools.mjs +248 -0
  310. package/src/router/service/wake.mjs +544 -0
  311. package/src/router/service/wal.mjs +685 -0
  312. package/src/router/shadow.mjs +821 -0
  313. package/src/surgery-recovery.js +1909 -0
  314. package/src/tool-output.js +485 -0
  315. package/src/tools.js +3262 -0
  316. package/src/truncate-visible.js +2416 -0
  317. package/src/truncate.js +999 -0
  318. package/src/ui/actions.js +1312 -0
  319. package/src/ui/flags.js +259 -0
  320. package/src/ui/panel-api.js +371 -0
  321. package/src/ui/panel-auth.js +251 -0
  322. package/src/ui/panel-integrity.js +243 -0
  323. package/src/ui/routes-readonly.js +759 -0
  324. package/src/ui/routes.js +284 -0
  325. package/src/util/append-store.js +368 -0
  326. package/src/util/local-day.js +30 -0
  327. package/src/util/redact.js +227 -0
  328. package/src/util/stale-locks.js +148 -0
  329. package/src/version.js +99 -0
  330. package/test/fixtures/pre-step-container.mjs +100 -0
  331. package/test/p1_probe.mjs +97 -0
@@ -0,0 +1,982 @@
1
+ // Procedural memory: how a task is done, not what happened.
2
+ //
3
+ // One card per procedure at `<root>/procedures/<slug>.md`. Unlike topics/ and
4
+ // journal/ cards, a procedure has a fixed shape, because a procedure is only
5
+ // usable when the model can find the trigger, follow the steps, and learn from
6
+ // the failure modes:
7
+ //
8
+ // ---
9
+ // name: 部署流程
10
+ // trigger: [部署, 上线]
11
+ // salience: 3
12
+ // strength: 3
13
+ // last_used: 2026-11-02
14
+ // revisions: 0
15
+ // ---
16
+ // ## 何时用 … ## 怎么做 (numbered) … ## 失败模式 … ## 例子
17
+ //
18
+ // `revisions` counts CONTENT versions (a merge bumps it), while `strength`
19
+ // counts how often the procedure actually worked (a report moves it). They are
20
+ // deliberately separate: editing a card must not look like using it, and using
21
+ // it must not create a new version.
22
+ //
23
+ // This module also owns the reader the index uses, so the writer and the index
24
+ // can never disagree about what a valid procedure is. A card whose frontmatter
25
+ // is unterminated or that misses a required field is returned as `invalid`
26
+ // rather than thrown: one broken card must not take the whole index down, and
27
+ // it must not be silently overwritten either.
28
+
29
+ import fs from 'node:fs';
30
+ import path from 'node:path';
31
+
32
+ import { memoryRootFromConfig, resolveInside, relativePath, memoryError } from './paths.js';
33
+ import {
34
+ parseFrontmatter, updateFrontmatter, appendLine, dayString,
35
+ normalizedBody, countRevLines,
36
+ } from './frontmatter.js';
37
+ import {
38
+ appendAudit, backupFile, restoreBackup, writeFileAtomic, listMarkdownFiles, sha256File, sha256Text,
39
+ } from './state.js';
40
+ import { sessionIdOfExec } from '../identity.js';
41
+ import { withWriteEvidence as landWithWriteEvidence, UNIMPLEMENTED_CODE as LAND_UNIMPLEMENTED_CODE } from './land.mjs';
42
+ import { MANUAL_SESSION, stampExtras } from './provenance.js';
43
+ import { manifestPath, refreshManifest } from './manifest.js';
44
+ import { appendConflictWith, detectConflicts } from './cards.js';
45
+
46
+ export const PROCEDURES_DIR = 'procedures';
47
+ export const PROCEDURE_ACTIONS = Object.freeze(['save', 'list', 'get', 'report']);
48
+ export const MAX_STRENGTH = 9;
49
+ export const MAX_SALIENCE = 5;
50
+
51
+ /** Required frontmatter keys, in the order the writer emits them. */
52
+ export const PROCEDURE_FIELDS = Object.freeze([
53
+ 'name', 'trigger', 'salience', 'strength', 'last_used', 'revisions',
54
+ ]);
55
+
56
+ /** Body section headings, in the order the writer emits them. */
57
+ export const PROCEDURE_SECTIONS = Object.freeze({
58
+ when: '何时用',
59
+ steps: '怎么做',
60
+ failureModes: '失败模式',
61
+ example: '例子',
62
+ });
63
+
64
+ const EMPTY_SECTION = '(暂无)';
65
+ const OUTCOMES = Object.freeze(['success', 'failure']);
66
+ const DEFAULT_LIST_LIMIT = 50;
67
+ const MAX_LIST_LIMIT = 500;
68
+ const MAX_NAME_CHARS = 120;
69
+ const MAX_TRIGGER_ITEMS = 24;
70
+ const MAX_STEPS = 50;
71
+ const MAX_STEP_CHARS = 500;
72
+ const MAX_REASON_CHARS = 120;
73
+
74
+ function collapse(text) {
75
+ return String(text ?? '').replace(/\s+/g, ' ').trim();
76
+ }
77
+
78
+ function singleLine(label, value) {
79
+ const text = String(value ?? '').trim();
80
+ if (/[\r\n]/.test(text)) {
81
+ throw memoryError('E_BAD_ARGUMENT', `${label} 不能含换行 — 多行内容放进正文,frontmatter 只支持单行值`);
82
+ }
83
+ return text;
84
+ }
85
+
86
+ function stringArg(value) {
87
+ return typeof value === 'string' ? value.trim() : '';
88
+ }
89
+
90
+ function firstHeading(body) {
91
+ for (const raw of String(body ?? '').split(/\r?\n/)) {
92
+ const match = /^\s{0,3}#{1,6}\s+(.+?)\s*$/.exec(raw);
93
+ if (match) return collapse(match[1]);
94
+ }
95
+ return null;
96
+ }
97
+
98
+ /**
99
+ * A slug is a file stem under procedures/. It may not contain a path
100
+ * separator, a `..` run, or a leading dot: `name: "x/y"` would otherwise write
101
+ * outside the directory the user thinks they are writing into.
102
+ */
103
+ function slugFrom(raw, label = 'slug') {
104
+ const text = singleLine(label, raw);
105
+ if (!text) {
106
+ throw memoryError('E_BAD_ARGUMENT', `${label} 不能为空 — 给一个简短的名字(会变成 procedures/<slug>.md)`);
107
+ }
108
+ if (text.length > MAX_NAME_CHARS) {
109
+ throw memoryError('E_BAD_ARGUMENT', `${label} 太长(${text.length} > ${MAX_NAME_CHARS} 字符)`);
110
+ }
111
+ if (/[\\/:*?"<>|\0]/.test(text)) {
112
+ throw memoryError('E_BAD_ARGUMENT', `${label} 不能含路径分隔符或以下字符:\\ / : * ? " < > | — 收到 ${JSON.stringify(text)}`);
113
+ }
114
+ if (text === '.' || text === '..' || text.includes('..')) {
115
+ throw memoryError('E_BAD_ARGUMENT', `${label} 不能含 .. — 收到 ${JSON.stringify(text)}`);
116
+ }
117
+ if (text.startsWith('.')) {
118
+ throw memoryError('E_BAD_ARGUMENT', `${label} 不能以 . 开头 — 收到 ${JSON.stringify(text)}`);
119
+ }
120
+ return text;
121
+ }
122
+
123
+ function intArg(value, label, min, max) {
124
+ if (value === undefined || value === null) return null;
125
+ const number = Number(value);
126
+ if (!Number.isInteger(number) || number < min || number > max) {
127
+ throw memoryError('E_BAD_ARGUMENT', `${label} 必须是 ${min}..${max} 的整数 — 收到 ${JSON.stringify(value)}`);
128
+ }
129
+ return number;
130
+ }
131
+
132
+ /** `trigger: [部署, 上线]` from the frontmatter is a string in `extras`. */
133
+ function parseTriggerValue(value) {
134
+ const text = String(value ?? '').trim();
135
+ if (text === '') return [];
136
+ if (text.startsWith('[') && text.endsWith(']')) {
137
+ const inner = text.slice(1, -1).trim();
138
+ if (inner === '') return [];
139
+ return inner.split(',').map((part) => unquote(part)).filter((part) => part !== '');
140
+ }
141
+ return [unquote(text)];
142
+ }
143
+
144
+ function unquote(value) {
145
+ const text = String(value ?? '').trim();
146
+ if (text.length >= 2) {
147
+ const first = text[0];
148
+ const last = text[text.length - 1];
149
+ if ((first === '"' && last === '"') || (first === "'" && last === "'")) return text.slice(1, -1);
150
+ }
151
+ return text;
152
+ }
153
+
154
+ /**
155
+ * Accept both shapes on purpose: the tool schema says array (that is what a
156
+ * host-validated save sends), while a keyword filter is often typed as one
157
+ * space-separated string.
158
+ */
159
+ function keywordList(value) {
160
+ const parts = Array.isArray(value)
161
+ ? value.flatMap((item) => String(item ?? '').split(/[\s,,、]+/))
162
+ : String(value ?? '').split(/[\s,,、]+/);
163
+ return parts.map((part) => part.trim()).filter((part) => part !== '');
164
+ }
165
+
166
+ function normalizeTrigger(value, label) {
167
+ const items = Array.isArray(value) ? value : (typeof value === 'string' ? [value] : null);
168
+ if (!items) {
169
+ throw memoryError('E_BAD_ARGUMENT', `${label} 必须是字符串数组 — 收到 ${JSON.stringify(value)}`);
170
+ }
171
+ const seen = new Set();
172
+ const out = [];
173
+ for (const item of items) {
174
+ const text = singleLine(label, item);
175
+ if (text === '') continue;
176
+ if (text.length > 60) throw memoryError('E_BAD_ARGUMENT', `${label} 的单个关键词太长(> 60 字符):${JSON.stringify(text)}`);
177
+ if (/[,\[\],]/.test(text)) {
178
+ throw memoryError('E_BAD_ARGUMENT', `${label} 的单个关键词不能含逗号或方括号(会破坏 frontmatter 数组):${JSON.stringify(text)}`);
179
+ }
180
+ if (seen.has(text.toLowerCase())) continue;
181
+ seen.add(text.toLowerCase());
182
+ out.push(text);
183
+ }
184
+ if (out.length === 0) {
185
+ throw memoryError('E_BAD_ARGUMENT', `${label} 至少需要一个关键词 — 空列表的程序卡永远不会被 list 找到`);
186
+ }
187
+ if (out.length > MAX_TRIGGER_ITEMS) {
188
+ throw memoryError('E_BAD_ARGUMENT', `${label} 最多 ${MAX_TRIGGER_ITEMS} 个关键词(收到 ${out.length})`);
189
+ }
190
+ return out;
191
+ }
192
+
193
+ function formatTrigger(trigger) {
194
+ return `[${trigger.join(', ')}]`;
195
+ }
196
+
197
+ /** Steps may arrive as an array, or as one newline-separated string. */
198
+ function normalizeSteps(value) {
199
+ if (value === undefined || value === null) return null;
200
+ const raw = Array.isArray(value) ? value : String(value).split(/\r?\n/);
201
+ const steps = raw
202
+ .map((step) => collapse(step).replace(/^\d+[.)]\s*/, ''))
203
+ .filter((step) => step !== '');
204
+ if (steps.length > MAX_STEPS) {
205
+ throw memoryError('E_BAD_ARGUMENT', `steps 最多 ${MAX_STEPS} 条(收到 ${steps.length})`);
206
+ }
207
+ for (const step of steps) {
208
+ if (step.length > MAX_STEP_CHARS) {
209
+ throw memoryError('E_BAD_ARGUMENT', `单条步骤超过 ${MAX_STEP_CHARS} 字符 — 拆成几条,或把细节放进「失败模式」`);
210
+ }
211
+ if (/[\r\n]/.test(step)) throw memoryError('E_BAD_ARGUMENT', 'steps 的每一条都必须是单行');
212
+ }
213
+ return steps;
214
+ }
215
+
216
+ function normalizeText(label, value) {
217
+ if (value === undefined || value === null) return null;
218
+ const text = String(value).replace(/\r\n/g, '\n').trim();
219
+ return text === '' ? null : text;
220
+ }
221
+
222
+ /** Split a card body into the four known sections plus anything else. */
223
+ function parseSections(body) {
224
+ const lines = String(body ?? '').split(/\r?\n/);
225
+ const sections = new Map();
226
+ let current = null;
227
+ for (const raw of lines) {
228
+ if (/^\s*<!--\s*rev\s*:/i.test(raw)) continue; // usage history, not prose
229
+ const match = /^\s{0,3}##\s+(.+?)\s*$/.exec(raw);
230
+ if (match) {
231
+ current = collapse(match[1]);
232
+ if (!sections.has(current)) sections.set(current, []);
233
+ continue;
234
+ }
235
+ if (current === null) continue;
236
+ sections.get(current).push(raw);
237
+ }
238
+
239
+ const textOf = (heading) => {
240
+ if (!sections.has(heading)) return null;
241
+ const text = sections.get(heading).join('\n').replace(/^\s+|\s+$/g, '');
242
+ return text === '' || text === EMPTY_SECTION ? null : text;
243
+ };
244
+
245
+ const stepsText = textOf(PROCEDURE_SECTIONS.steps);
246
+ const steps = [];
247
+ if (stepsText) {
248
+ for (const raw of stepsText.split(/\r?\n/)) {
249
+ const numbered = /^\s*\d+[.)]\s+(.*)$/.exec(raw);
250
+ const bullet = /^\s*[-*+]\s+(.*)$/.exec(raw);
251
+ const text = numbered?.[1] ?? bullet?.[1];
252
+ if (text !== undefined && text.trim() !== '') steps.push(text.trim());
253
+ }
254
+ if (steps.length === 0) steps.push(stepsText.trim());
255
+ }
256
+
257
+ const known = new Set(Object.values(PROCEDURE_SECTIONS));
258
+ const extras = [];
259
+ for (const [heading, content] of sections) {
260
+ if (known.has(heading)) continue;
261
+ const text = content.join('\n').trim();
262
+ if (text !== '') extras.push({ heading, text });
263
+ }
264
+
265
+ return {
266
+ when: textOf(PROCEDURE_SECTIONS.when),
267
+ steps,
268
+ failureModes: textOf(PROCEDURE_SECTIONS.failureModes),
269
+ example: textOf(PROCEDURE_SECTIONS.example),
270
+ extraSections: extras,
271
+ };
272
+ }
273
+
274
+ function composeBody(sections) {
275
+ const steps = Array.isArray(sections.steps) && sections.steps.length > 0
276
+ ? sections.steps.map((step, index) => `${index + 1}. ${step}`)
277
+ : [EMPTY_SECTION];
278
+ const lines = [
279
+ `## ${PROCEDURE_SECTIONS.when}`,
280
+ '',
281
+ sections.when?.trim() || EMPTY_SECTION,
282
+ '',
283
+ `## ${PROCEDURE_SECTIONS.steps}`,
284
+ '',
285
+ ...steps,
286
+ '',
287
+ `## ${PROCEDURE_SECTIONS.failureModes}`,
288
+ '',
289
+ sections.failureModes?.trim() || EMPTY_SECTION,
290
+ '',
291
+ `## ${PROCEDURE_SECTIONS.example}`,
292
+ '',
293
+ sections.example?.trim() || EMPTY_SECTION,
294
+ ];
295
+ for (const extra of sections.extraSections ?? []) {
296
+ lines.push('', `## ${extra.heading}`, '', extra.text);
297
+ }
298
+ for (const rev of sections.revLines ?? []) {
299
+ lines.push('', rev);
300
+ }
301
+ return `${lines.join('\n')}\n`;
302
+ }
303
+
304
+ function buildCardText(card) {
305
+ const head = [
306
+ '---',
307
+ `name: ${card.name}`,
308
+ `trigger: ${formatTrigger(card.trigger)}`,
309
+ `salience: ${card.salience}`,
310
+ `strength: ${card.strength}`,
311
+ `last_used: ${card.last_used}`,
312
+ `revisions: ${card.revisions}`,
313
+ ];
314
+ // B3 provenance and conflict markers are extras: they go after the six
315
+ // pinned fields (M24 pins those), and are never inserted into them.
316
+ const extras = card.extras && typeof card.extras === 'object' ? card.extras : {};
317
+ for (const [key, value] of Object.entries(extras)) {
318
+ if (PROCEDURE_FIELDS.includes(key) || value == null || String(value) === '') continue;
319
+ const text = String(value);
320
+ if (/[\r\n]/.test(text)) {
321
+ throw memoryError(
322
+ 'E_BAD_ARGUMENT',
323
+ `扩展字段 ${key} 的值含换行 — 该格式只支持单行值,拒绝写出(请把多行内容放进正文)`,
324
+ );
325
+ }
326
+ head.push(`${key}: ${text}`);
327
+ }
328
+ head.push('---');
329
+ return `${head.join('\n')}\n\n${composeBody(card.sections)}`;
330
+ }
331
+
332
+ /** Keys actually written in the frontmatter block (not the parsed defaults). */
333
+ function frontmatterKeys(parsed) {
334
+ const head = parsed.text.slice(parsed.bom.length, parsed.bodyStart);
335
+ const keys = new Set();
336
+ const pattern = /^([A-Za-z_][\w-]*)\s*:/gm;
337
+ let match = pattern.exec(head);
338
+ while (match) {
339
+ keys.add(match[1]);
340
+ match = pattern.exec(head);
341
+ }
342
+ return keys;
343
+ }
344
+
345
+ function procedurePath(root, slug) {
346
+ return resolveInside(root, path.join(PROCEDURES_DIR, `${slug}.md`));
347
+ }
348
+
349
+ /**
350
+ * Read one procedure file. Never throws for bad content: an unterminated
351
+ * frontmatter block or a missing required field comes back as `invalid: true`
352
+ * with a reason, because the index has to keep counting the card and the tool
353
+ * has to refuse to overwrite it.
354
+ */
355
+ export function readProcedureFile(root, abs, text = null) {
356
+ const rel = relativePath(root, abs);
357
+ const slug = path.basename(abs, '.md');
358
+ const source = text ?? fs.readFileSync(abs, 'utf8');
359
+ const base = {
360
+ abs, rel, slug, text: source,
361
+ name: slug, trigger: [], salience: 3, strength: 3, last_used: null, revisions: 0,
362
+ version: 1, legacy: false, invalid: false, invalidReason: null, extras: {},
363
+ sections: { when: null, steps: [], failureModes: null, example: null, extraSections: [] },
364
+ };
365
+
366
+ let parsed;
367
+ try {
368
+ parsed = parseFrontmatter(source);
369
+ } catch (error) {
370
+ return {
371
+ ...base,
372
+ invalid: true,
373
+ invalidReason: error?.code === 'E_FRONTMATTER_UNTERMINATED'
374
+ ? 'frontmatter 以 --- 开头但没有闭合'
375
+ : `frontmatter 解析失败:${error?.message ?? String(error)}`,
376
+ sha256: sha256Text(source),
377
+ };
378
+ }
379
+
380
+ const sections = parseSections(parsed.body);
381
+ const revLines = String(parsed.body).split(/\r?\n/).filter((line) => /^\s*<!--\s*rev\s*:/i.test(line));
382
+ sections.revLines = revLines;
383
+
384
+ if (parsed.legacy) {
385
+ // A card without frontmatter predates the format. It still gets a row (the
386
+ // index must not lose it) and list/get may show it, but report refuses
387
+ // until `save` rewrites it into the real shape.
388
+ return {
389
+ ...base,
390
+ name: firstHeading(parsed.body) || slug,
391
+ legacy: true,
392
+ sections,
393
+ sha256: sha256Text(source),
394
+ };
395
+ }
396
+
397
+ const keys = frontmatterKeys(parsed);
398
+ const missing = PROCEDURE_FIELDS.filter((key) => !keys.has(key));
399
+ const name = unquote(parsed.extras.name ?? '');
400
+ const trigger = parseTriggerValue(parsed.extras.trigger);
401
+ if (name === '') missing.push('name');
402
+ if (trigger.length === 0) missing.push('trigger');
403
+ const uniqueMissing = [...new Set(missing)];
404
+ if (uniqueMissing.length > 0) {
405
+ return {
406
+ ...base,
407
+ name: name || slug,
408
+ trigger,
409
+ salience: parsed.fields.salience,
410
+ strength: parsed.fields.strength,
411
+ last_used: parsed.fields.last_used,
412
+ revisions: parsed.fields.revisions,
413
+ version: parsed.fields.revisions + 1,
414
+ invalid: true,
415
+ invalidReason: `缺少必填 frontmatter 字段:${uniqueMissing.join(', ')}`,
416
+ extras: parsed.extras,
417
+ sections,
418
+ sha256: sha256Text(source),
419
+ };
420
+ }
421
+
422
+ return {
423
+ ...base,
424
+ name,
425
+ trigger,
426
+ salience: parsed.fields.salience,
427
+ strength: parsed.fields.strength,
428
+ last_used: parsed.fields.last_used,
429
+ revisions: parsed.fields.revisions,
430
+ version: parsed.fields.revisions + 1,
431
+ extras: parsed.extras,
432
+ sections,
433
+ sha256: sha256Text(source),
434
+ };
435
+ }
436
+
437
+ /** Every procedure file, valid and broken, plus the broken ones separately. */
438
+ export function scanProcedures(root) {
439
+ const cards = listMarkdownFiles(root, PROCEDURES_DIR)
440
+ .map((abs) => readProcedureFile(root, abs));
441
+ cards.sort((left, right) => {
442
+ if (right.salience !== left.salience) return right.salience - left.salience;
443
+ if (right.strength !== left.strength) return right.strength - left.strength;
444
+ return left.slug.localeCompare(right.slug);
445
+ });
446
+ return { cards, invalid: cards.filter((card) => card.invalid) };
447
+ }
448
+
449
+ function listItem(card) {
450
+ return {
451
+ name: card.name,
452
+ slug: card.slug,
453
+ rel: card.rel,
454
+ trigger: card.trigger,
455
+ salience: card.salience,
456
+ strength: card.strength,
457
+ last_used: card.last_used,
458
+ revisions: card.revisions,
459
+ version: card.version,
460
+ legacy: card.legacy,
461
+ invalid: card.invalid,
462
+ invalidReason: card.invalidReason,
463
+ };
464
+ }
465
+
466
+ function findCard(root, args) {
467
+ const raw = stringArg(args.slug) || stringArg(args.name);
468
+ if (!raw) return null;
469
+ const slug = slugFrom(raw, 'slug');
470
+ const abs = procedurePath(root, slug);
471
+ if (!fs.existsSync(abs)) return null;
472
+ const stat = fs.lstatSync(abs);
473
+ if (stat.isSymbolicLink() || !stat.isFile()) {
474
+ throw memoryError('E_PROCEDURE_INVALID', `不是普通文件,拒绝读写:${relativePath(root, abs)}`);
475
+ }
476
+ return readProcedureFile(root, abs);
477
+ }
478
+
479
+ /**
480
+ * Write `card` to its file and prove the write by reading it back and parsing
481
+ * it again. Any mismatch restores the pre-write backup; a write that cannot be
482
+ * proven must never be reported as success.
483
+ */
484
+ function writeVerifiedCard(root, card, { now, backupOfPrevious }) {
485
+ const text = buildCardText(card);
486
+ const backup = backupOfPrevious ? backupFile(root, card.abs, { now }) : null;
487
+ let written;
488
+ try {
489
+ written = writeFileAtomic(root, card.abs, text, { backup: false, now });
490
+ const readBack = fs.readFileSync(card.abs, 'utf8');
491
+ const reparsed = readProcedureFile(root, card.abs, readBack);
492
+ const problems = [];
493
+ if (reparsed.name !== card.name) problems.push(`name ${reparsed.name} != ${card.name}`);
494
+ if (JSON.stringify(reparsed.trigger) !== JSON.stringify(card.trigger)) problems.push('trigger 不一致');
495
+ if (reparsed.revisions !== card.revisions) problems.push(`revisions ${reparsed.revisions} != ${card.revisions}`);
496
+ if (reparsed.strength !== card.strength) problems.push(`strength ${reparsed.strength} != ${card.strength}`);
497
+ if (reparsed.invalid) problems.push(`写出的卡不合法:${reparsed.invalidReason}`);
498
+ const wantedExtras = card.extras && typeof card.extras === 'object' ? card.extras : {};
499
+ for (const [key, value] of Object.entries(wantedExtras)) {
500
+ if (PROCEDURE_FIELDS.includes(key) || value == null) continue;
501
+ if (reparsed.extras[key] !== String(value)) problems.push(`extras ${key} 不一致`);
502
+ }
503
+ if (problems.length > 0) {
504
+ throw memoryError('E_PROCEDURE_VERIFY', `写后校验失败:${problems.join(';')}`);
505
+ }
506
+ return { text, written, readBack, backup };
507
+ } catch (error) {
508
+ if (backup) {
509
+ try {
510
+ restoreBackup(root, backup.path, card.abs);
511
+ } catch (restoreError) {
512
+ throw memoryError('E_ROLLBACK_FAILED', `写后校验失败且无法回滚:${card.rel}`, restoreError);
513
+ }
514
+ } else if (fs.existsSync(card.abs)) {
515
+ // A new card that failed verification is not left half-written.
516
+ try {
517
+ fs.unlinkSync(card.abs);
518
+ } catch {
519
+ /* best effort: the verification error is the one to report */
520
+ }
521
+ }
522
+ throw error instanceof Error && error.code ? error : memoryError('E_PROCEDURE_VERIFY', `写入失败:${card.rel}`, error);
523
+ }
524
+ }
525
+
526
+ function saveProcedure(root, args, { now, today, sessionId = null, turn = null }) {
527
+ const nameArg = args.name === undefined ? '' : singleLine('name', args.name);
528
+ const slugArg = args.slug === undefined || args.slug === null ? '' : singleLine('slug', args.slug);
529
+ const slug = slugFrom(slugArg || nameArg, slugArg ? 'slug' : 'name');
530
+ const abs = procedurePath(root, slug);
531
+
532
+ const existing = fs.existsSync(abs) ? readProcedureFile(root, abs) : null;
533
+ if (existing?.invalid) {
534
+ throw memoryError(
535
+ 'E_PROCEDURE_INVALID',
536
+ `${existing.rel} 的 frontmatter 坏了(${existing.invalidReason})— 先手工修好或删掉它,工具拒绝静默覆盖`,
537
+ );
538
+ }
539
+
540
+ const triggerArg = args.trigger === undefined ? null : normalizeTrigger(args.trigger, 'trigger');
541
+ const salienceArg = intArg(args.salience, 'salience', 1, MAX_SALIENCE);
542
+ const strengthArg = intArg(args.strength, 'strength', 0, MAX_STRENGTH);
543
+ const whenArg = normalizeText('when', args.when);
544
+ const stepsArg = normalizeSteps(args.steps);
545
+ const failureArg = normalizeText('failureModes', args.failureModes);
546
+ const exampleArg = normalizeText('example', args.example);
547
+
548
+ const name = nameArg || existing?.name || '';
549
+ if (name === '') {
550
+ throw memoryError('E_BAD_ARGUMENT', 'save 需要 name — 或者用 slug 指向一张已存在的卡');
551
+ }
552
+
553
+ if (existing) {
554
+ const sections = {
555
+ when: whenArg ?? existing.sections.when,
556
+ steps: stepsArg ?? existing.sections.steps,
557
+ failureModes: failureArg ?? existing.sections.failureModes,
558
+ example: exampleArg ?? existing.sections.example,
559
+ extraSections: existing.sections.extraSections,
560
+ revLines: existing.sections.revLines,
561
+ };
562
+ const trigger = triggerArg ?? existing.trigger;
563
+ if (trigger.length === 0) {
564
+ throw memoryError('E_BAD_ARGUMENT', `${existing.rel} 没有 trigger — 合并时给一个关键词,否则这张卡永远搜不到`);
565
+ }
566
+ if (!sections.when) {
567
+ throw memoryError('E_BAD_ARGUMENT', `${existing.rel} 没有「何时用」— 合并时给 when,或先修卡`);
568
+ }
569
+ if (sections.steps.length === 0) {
570
+ throw memoryError('E_BAD_ARGUMENT', `${existing.rel} 没有「怎么做」步骤 — 合并时给 steps,或先修卡`);
571
+ }
572
+ const card = {
573
+ abs,
574
+ rel: existing.rel,
575
+ slug,
576
+ name,
577
+ trigger,
578
+ salience: salienceArg ?? existing.salience,
579
+ strength: strengthArg ?? existing.strength,
580
+ last_used: existing.last_used ?? today,
581
+ revisions: existing.revisions + 1,
582
+ // B3: a merge keeps the original source stamps ("已有则保留"); a card
583
+ // written before B3 gains them from this merge onward.
584
+ extras: stampExtras(existing.extras, { sessionId, turn, at: now }),
585
+ sections,
586
+ };
587
+ const { written, backup } = writeVerifiedCard(root, card, { now, backupOfPrevious: true });
588
+ appendAudit(root, {
589
+ action: 'memory_procedure',
590
+ object: card.rel,
591
+ result: `save merged version=${card.revisions + 1} revisions=${card.revisions}`,
592
+ now,
593
+ });
594
+ return {
595
+ ok: true,
596
+ action: 'save',
597
+ status: 'merged',
598
+ root,
599
+ path: abs,
600
+ rel: card.rel,
601
+ slug,
602
+ name: card.name,
603
+ trigger: card.trigger,
604
+ salience: card.salience,
605
+ strength: card.strength,
606
+ last_used: card.last_used,
607
+ revisions: card.revisions,
608
+ version: card.revisions + 1,
609
+ previousVersion: existing.revisions + 1,
610
+ created: false,
611
+ legacy: false,
612
+ invalid: false,
613
+ sha256: written.sha256,
614
+ backup: backup?.path ?? null,
615
+ backupRel: backup?.rel ?? null,
616
+ body: card.sections,
617
+ message:
618
+ `已合并 ${card.rel}:版本 ${card.revisions}→${card.revisions + 1}` +
619
+ `(revisions=${card.revisions}),上一版备份 ${backup?.rel ?? '(无)'}`,
620
+ };
621
+ }
622
+
623
+ if (triggerArg === null || triggerArg.length === 0) {
624
+ throw memoryError('E_BAD_ARGUMENT', '新程序卡需要 trigger(什么时候该用这条流程)');
625
+ }
626
+ if (!whenArg) {
627
+ throw memoryError('E_BAD_ARGUMENT', '新程序卡需要 when(正文「何时用」:什么情况下该用这条流程)');
628
+ }
629
+ if (!stepsArg || stepsArg.length === 0) {
630
+ throw memoryError('E_BAD_ARGUMENT', '新程序卡需要 steps(正文「怎么做」:至少一条编号步骤)');
631
+ }
632
+
633
+ const rel = relativePath(root, abs);
634
+ const sections = {
635
+ when: whenArg,
636
+ steps: stepsArg,
637
+ failureModes: failureArg,
638
+ example: exampleArg,
639
+ extraSections: [],
640
+ revLines: [],
641
+ };
642
+ // B3: a new procedure is a new conclusion — check it against every existing
643
+ // card before writing, and mirror the marker onto the old cards afterwards.
644
+ const conflicts = detectConflicts(root, {
645
+ rel,
646
+ title: name,
647
+ body: composeBody(sections),
648
+ key: null,
649
+ });
650
+ const extras = stampExtras({}, { sessionId: sessionId ?? MANUAL_SESSION, turn, at: now });
651
+ if (conflicts.length > 0) {
652
+ extras.conflict = `[${conflicts.map((row) => row.rel).join(', ')}]`;
653
+ }
654
+
655
+ const card = {
656
+ abs,
657
+ rel,
658
+ slug,
659
+ name,
660
+ trigger: triggerArg,
661
+ salience: salienceArg ?? 3,
662
+ strength: strengthArg ?? 3,
663
+ last_used: today,
664
+ revisions: 0,
665
+ // No host session (a human calling the tool) is recorded honestly as
666
+ // `manual`, not as a made-up id.
667
+ extras,
668
+ sections,
669
+ };
670
+ const { written } = writeVerifiedCard(root, card, { now, backupOfPrevious: false });
671
+ const marked = [];
672
+ try {
673
+ for (const conflict of conflicts) {
674
+ marked.push(appendConflictWith(root, conflict.rel, card.rel, { now }));
675
+ }
676
+ } catch (error) {
677
+ for (const row of marked.reverse()) {
678
+ if (!row.changed || !row.backup) continue;
679
+ try {
680
+ restoreBackup(root, row.backup, resolveInside(root, row.rel));
681
+ } catch {
682
+ /* the original error is the one to report */
683
+ }
684
+ }
685
+ try {
686
+ fs.unlinkSync(abs);
687
+ } catch {
688
+ /* best effort */
689
+ }
690
+ throw error;
691
+ }
692
+ appendAudit(root, {
693
+ action: 'memory_procedure',
694
+ object: card.rel,
695
+ result: `save created revisions=0`,
696
+ now,
697
+ });
698
+ return {
699
+ ok: true,
700
+ action: 'save',
701
+ status: 'created',
702
+ root,
703
+ path: abs,
704
+ rel: card.rel,
705
+ slug,
706
+ name: card.name,
707
+ trigger: card.trigger,
708
+ salience: card.salience,
709
+ strength: card.strength,
710
+ last_used: card.last_used,
711
+ revisions: 0,
712
+ version: 1,
713
+ previousVersion: null,
714
+ created: true,
715
+ legacy: false,
716
+ invalid: false,
717
+ sha256: written.sha256,
718
+ backup: null,
719
+ backupRel: null,
720
+ body: card.sections,
721
+ conflicts: conflicts.map((row) => ({ rel: row.rel, title: row.title, reasons: row.reasons })),
722
+ conflictWith: marked.map((row) => row.rel),
723
+ message: `已新建程序卡 ${card.rel}(版本 1,revisions=0);下次同名 save 会合并成版本 2`,
724
+ };
725
+ }
726
+
727
+ function getProcedure(root, args) {
728
+ const card = findCard(root, args);
729
+ if (!card) {
730
+ const target = stringArg(args.slug) || stringArg(args.name);
731
+ throw memoryError('E_PROCEDURE_NOT_FOUND', `找不到程序卡:${target} — 用 action:"list" 看现有卡`);
732
+ }
733
+ if (card.invalid) {
734
+ throw memoryError(
735
+ 'E_PROCEDURE_INVALID',
736
+ `${card.rel} 的 frontmatter 不合法(${card.invalidReason})— 修好它,或删掉后重新 save`,
737
+ );
738
+ }
739
+ return {
740
+ ok: true,
741
+ action: 'get',
742
+ root,
743
+ path: card.abs,
744
+ rel: card.rel,
745
+ slug: card.slug,
746
+ name: card.name,
747
+ trigger: card.trigger,
748
+ salience: card.salience,
749
+ strength: card.strength,
750
+ last_used: card.last_used,
751
+ revisions: card.revisions,
752
+ version: card.version,
753
+ legacy: card.legacy,
754
+ invalid: false,
755
+ sections: {
756
+ when: card.sections.when,
757
+ steps: card.sections.steps,
758
+ failureModes: card.sections.failureModes,
759
+ example: card.sections.example,
760
+ },
761
+ text: card.text,
762
+ sha256: sha256File(card.abs),
763
+ message: `程序卡 ${card.rel}:版本 ${card.version},strength ${card.strength},${card.trigger.length} 个触发词`,
764
+ };
765
+ }
766
+
767
+ function listProcedures(root, args) {
768
+ const { cards, invalid } = scanProcedures(root);
769
+ const keywords = keywordList(args.trigger ?? args.query ?? '');
770
+ const lowered = keywords.map((keyword) => keyword.toLowerCase());
771
+ const filtered = lowered.length === 0
772
+ ? cards
773
+ : cards.filter((card) => card.trigger.some((term) => {
774
+ const haystack = term.toLowerCase();
775
+ return lowered.some((keyword) => haystack.includes(keyword));
776
+ }));
777
+
778
+ const limit = intArg(args.limit, 'limit', 1, MAX_LIST_LIMIT) ?? DEFAULT_LIST_LIMIT;
779
+ const page = filtered.slice(0, limit);
780
+ return {
781
+ ok: true,
782
+ action: 'list',
783
+ root,
784
+ count: filtered.length,
785
+ total: cards.length,
786
+ invalidCount: invalid.length,
787
+ truncated: filtered.length > page.length,
788
+ limit,
789
+ keywords,
790
+ items: page.map(listItem),
791
+ invalid: invalid.map((card) => ({ rel: card.rel, reason: card.invalidReason })),
792
+ message:
793
+ `程序卡 ${filtered.length}/${cards.length} 张` +
794
+ `${keywords.length > 0 ? `(trigger 匹配 ${keywords.join(' / ')})` : ''}` +
795
+ `${invalid.length > 0 ? `;${invalid.length} 张 frontmatter 坏了,已标注` : ''}`,
796
+ };
797
+ }
798
+
799
+ function reportProcedure(root, args, { now, today }) {
800
+ const target = stringArg(args.slug) || stringArg(args.name);
801
+ if (!target) {
802
+ throw memoryError('E_BAD_ARGUMENT', 'report 需要 slug 或 name(要报告哪张程序卡)');
803
+ }
804
+ const outcome = stringArg(args.outcome);
805
+ if (!outcome) {
806
+ throw memoryError('E_BAD_ARGUMENT', `report 需要 outcome(${OUTCOMES.join(' | ')})`);
807
+ }
808
+ if (!OUTCOMES.includes(outcome)) {
809
+ throw memoryError('E_BAD_ARGUMENT', `outcome 只能是 ${OUTCOMES.join(' | ')} — 收到 ${JSON.stringify(outcome)}`);
810
+ }
811
+ const card = findCard(root, args);
812
+ if (!card) {
813
+ throw memoryError('E_PROCEDURE_NOT_FOUND', `找不到程序卡:${target} — 用 action:"list" 看现有卡`);
814
+ }
815
+ if (card.invalid) {
816
+ throw memoryError(
817
+ 'E_PROCEDURE_INVALID',
818
+ `${card.rel} 的 frontmatter 不合法(${card.invalidReason})— 先修好它,report 不会拿坏卡记账`,
819
+ );
820
+ }
821
+ if (card.legacy) {
822
+ throw memoryError(
823
+ 'E_PROCEDURE_INVALID',
824
+ `${card.rel} 是没有 frontmatter 的旧卡 — 先用 action:"save" 补成 name/trigger/salience/strength/last_used 的新格式,再 report`,
825
+ );
826
+ }
827
+
828
+ const before = { strength: card.strength, last_used: card.last_used, revisions: card.revisions };
829
+ const capped = outcome === 'success' && card.strength >= MAX_STRENGTH;
830
+ const floored = outcome === 'failure' && card.strength <= 0;
831
+ const nextStrength = outcome === 'success'
832
+ ? Math.min(MAX_STRENGTH, card.strength + 1)
833
+ : Math.max(0, card.strength - 1);
834
+ const reason = typeof args.reason === 'string' && args.reason.trim()
835
+ ? args.reason.trim().replace(/[\r\n]+/g, ' ').slice(0, MAX_REASON_CHARS)
836
+ : '';
837
+ const revLine = `<!-- rev: ${today} ${outcome}${reason ? ` ${reason}` : ''} -->`;
838
+
839
+ // revisions stays put: strength counts real uses, revisions counts content
840
+ // versions. Bumping revisions here would make a used card look edited.
841
+ let updated = updateFrontmatter(card.text, { strength: nextStrength, last_used: today });
842
+ updated = appendLine(updated, revLine);
843
+
844
+ const backup = backupFile(root, card.abs, { now });
845
+ let problems = [];
846
+ try {
847
+ writeFileAtomic(root, card.abs, updated, { backup: false, now });
848
+ const readBack = fs.readFileSync(card.abs, 'utf8');
849
+ const reparsed = readProcedureFile(root, card.abs, readBack);
850
+ if (reparsed.invalid) problems.push(`读回不合法:${reparsed.invalidReason}`);
851
+ if (reparsed.strength !== nextStrength) problems.push(`strength ${reparsed.strength} != ${nextStrength}`);
852
+ if (reparsed.last_used !== today) problems.push(`last_used ${reparsed.last_used} != ${today}`);
853
+ if (reparsed.revisions !== card.revisions) problems.push(`revisions 被改动:${reparsed.revisions} != ${card.revisions}`);
854
+ if (normalizedBody(parseFrontmatter(card.text).body) !== normalizedBody(parseFrontmatter(readBack).body)) {
855
+ problems.push('正文被改动');
856
+ }
857
+ if (countRevLines(reparsed.text) !== countRevLines(card.text) + 1) {
858
+ problems.push('rev 注释没有恰好追加一行');
859
+ }
860
+ } catch (error) {
861
+ try {
862
+ restoreBackup(root, backup.path, card.abs);
863
+ } catch (restoreError) {
864
+ throw memoryError('E_ROLLBACK_FAILED', `report 写后校验失败且无法回滚:${card.rel}`, restoreError);
865
+ }
866
+ throw error instanceof Error && error.code ? error : memoryError('E_PROCEDURE_VERIFY', `report 写入失败:${card.rel}`, error);
867
+ }
868
+ if (problems.length > 0) {
869
+ try {
870
+ restoreBackup(root, backup.path, card.abs);
871
+ } catch (restoreError) {
872
+ throw memoryError('E_ROLLBACK_FAILED', `report 写后校验失败且无法回滚:${card.rel}`, restoreError);
873
+ }
874
+ throw memoryError('E_PROCEDURE_VERIFY', `report 写后校验失败,已回滚:${problems.join(';')}`);
875
+ }
876
+
877
+ appendAudit(root, {
878
+ action: 'memory_procedure',
879
+ object: card.rel,
880
+ result: `report ${outcome} strength=${nextStrength} revisions=${card.revisions}`,
881
+ now,
882
+ });
883
+ return {
884
+ ok: true,
885
+ action: 'report',
886
+ status: 'reported',
887
+ root,
888
+ path: card.abs,
889
+ rel: card.rel,
890
+ slug: card.slug,
891
+ name: card.name,
892
+ outcome,
893
+ before,
894
+ after: { strength: nextStrength, last_used: today },
895
+ revisions: card.revisions,
896
+ version: card.revisions + 1,
897
+ capped,
898
+ floored,
899
+ bodyIdentical: true,
900
+ revLine,
901
+ backup: backup.path,
902
+ backupRel: backup.rel,
903
+ sha256: backup.sha256,
904
+ message:
905
+ `已记录 ${card.rel} ${outcome}:strength ${before.strength}→${nextStrength}` +
906
+ `${capped ? '(到顶 9)' : ''}${floored ? '(到底 0)' : ''},last_used=${today},` +
907
+ `revisions 保持 ${card.revisions}(内容版本不变),备份 ${backup.rel}`,
908
+ };
909
+ }
910
+
911
+ /**
912
+ * memory_procedure: save | list | get | report.
913
+ *
914
+ * All four act on the same on-disk contract. `save` is the only writer of new
915
+ * content; `report` is the only writer of usage history. Neither touches the
916
+ * other's field.
917
+ */
918
+ function memoryProcedureLegacy(args = {}, config = {}) {
919
+ const root = memoryRootFromConfig(config);
920
+ const now = config.now instanceof Date ? config.now : new Date();
921
+ const today = typeof config.today === 'string' && config.today.trim() !== ''
922
+ ? config.today.trim()
923
+ : dayString(now);
924
+
925
+ const action = stringArg(args.action);
926
+ if (!action) {
927
+ throw memoryError('E_BAD_ARGUMENT', `memory_procedure 需要 action(${PROCEDURE_ACTIONS.join(' | ')})`);
928
+ }
929
+ if (!PROCEDURE_ACTIONS.includes(action)) {
930
+ throw memoryError('E_BAD_ARGUMENT', `未知 action:${JSON.stringify(action)} — 只支持 ${PROCEDURE_ACTIONS.join(' | ')}`);
931
+ }
932
+
933
+ // B3: the caller's session is real host identity (`exec.agent.session...`);
934
+ // the turn is only written when the host/caller actually supplied one.
935
+ const exec = config.exec;
936
+ const sessionId = sessionIdOfExec(exec);
937
+ const turn = Number.isInteger(config.turn) && config.turn >= 0
938
+ ? config.turn
939
+ : (Number.isInteger(exec?.turn) && exec.turn >= 0 ? exec.turn : null);
940
+ const context = { now, today, sessionId, turn };
941
+
942
+ let result;
943
+ if (action === 'save') result = saveProcedure(root, args, context);
944
+ else if (action === 'list') return listProcedures(root, args, context);
945
+ else if (action === 'get') return getProcedure(root, args, context);
946
+ else result = reportProcedure(root, args, context);
947
+
948
+ // A save/report changed a card, so the manifest baseline must move with it.
949
+ // This is best effort: the card write already succeeded and is verified; a
950
+ // manifest failure must be reported, not turned into a fake card failure.
951
+ if (action === 'save' || action === 'report') {
952
+ try {
953
+ const refreshed = refreshManifest(root, { now });
954
+ result.manifest = {
955
+ rel: relativePath(root, manifestPath(root)),
956
+ cards: refreshed.manifest.cards.length,
957
+ sha256: refreshed.sha256,
958
+ };
959
+ } catch (error) {
960
+ result.manifestWarning = error?.message ?? String(error);
961
+ }
962
+ }
963
+ return result;
964
+ }
965
+
966
+ /**
967
+ * M12/M13/M15 出口委托:land.mjs(落盘门,批次 B)。
968
+ * land 未实现时如实回退旧路径(不双写、不静默吞错);land 实现后同一入口自动切到新路径。
969
+ */
970
+ function landDoubleRoute(name, legacy) {
971
+ try {
972
+ return landWithWriteEvidence(name, legacy);
973
+ } catch (error) {
974
+ if (error?.code === LAND_UNIMPLEMENTED_CODE) return legacy();
975
+ throw error;
976
+ }
977
+ }
978
+
979
+ /** 工具入口:memory_procedure。委托 land 落盘门(未实现时回退旧路径)。 */
980
+ export function memoryProcedure(args = {}, config = {}) {
981
+ return landDoubleRoute('memory_procedure', () => memoryProcedureLegacy(args, config));
982
+ }