@ftai/dsh-plugin-acn 0.0.0-stage → 0.1.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 (272) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/LICENSE-APACHE +201 -0
  3. package/LICENSE-MIT +19 -0
  4. package/README.md +55 -2
  5. package/README_EN.md +56 -0
  6. package/cordis.patch.yml +29 -0
  7. package/docs/acn-compat.md +33 -0
  8. package/docs/architecture.md +129 -0
  9. package/docs/assets/activity-view.png +0 -0
  10. package/docs/assets/install-package.png +0 -0
  11. package/docs/assets/knowledge-model.png +0 -0
  12. package/docs/assets/knowledge-view.png +0 -0
  13. package/docs/assets/personal-configuration.png +0 -0
  14. package/docs/assets/session-upstream.png +0 -0
  15. package/docs/assets/upstream-settings.png +0 -0
  16. package/docs/assets/upstream-team.png +0 -0
  17. package/docs/command-reference.md +201 -0
  18. package/docs/config.md +243 -0
  19. package/docs/development.md +197 -0
  20. package/docs/dsh-compat.md +59 -0
  21. package/docs/index.md +16 -0
  22. package/docs/outstanding-issues.md +61 -0
  23. package/docs/user_guide.md +183 -0
  24. package/icon.svg +8 -0
  25. package/lib/activities-LRoCwpzw.js +327 -0
  26. package/lib/alignment-CwH0nBf-.js +80 -0
  27. package/lib/auth-DFI9yowX.js +71 -0
  28. package/lib/checkpoint-Bmt8q2vB.js +188 -0
  29. package/lib/checkpoint-RgcdqifN.js +318 -0
  30. package/lib/claim-DOAGe8ZK.js +168 -0
  31. package/lib/client.js +18420 -0
  32. package/lib/deliver-BuYQaPRW.js +168 -0
  33. package/lib/delivery-status-D5m3178s.js +87 -0
  34. package/lib/dispute-CtrInHzf.js +20 -0
  35. package/lib/disputes-ByEmi43j.js +51 -0
  36. package/lib/dream-agent-DBszTHXY.js +249 -0
  37. package/lib/dream.js +4 -0
  38. package/lib/effects-DJ4Xa7Tx.js +268 -0
  39. package/lib/errors-Bp_2WXBr.js +19 -0
  40. package/lib/errors-pPumDOGD.js +18 -0
  41. package/lib/evidence-store-DLFvSuNa.js +1030 -0
  42. package/lib/formation-D4LO31WW.js +187 -0
  43. package/lib/formation-replay-CEOy5FkI.js +87 -0
  44. package/lib/formation.js +9 -0
  45. package/lib/inbox-2CugZZQm.js +188 -0
  46. package/lib/inbox-DFtE2fOp.js +71 -0
  47. package/lib/inbox.js +3 -0
  48. package/lib/index.js +1377 -0
  49. package/lib/lock-DbmlKOoX.js +332 -0
  50. package/lib/pages-BEWC3kmZ.js +51 -0
  51. package/lib/paths-CDYV5UH9.js +154 -0
  52. package/lib/plugins/commands.js +590 -0
  53. package/lib/plugins/dream.js +66 -0
  54. package/lib/plugins/formation.js +66 -0
  55. package/lib/plugins/inbox.js +53 -0
  56. package/lib/plugins/knowledge.js +1111 -0
  57. package/lib/plugins/prompt.js +102 -0
  58. package/lib/plugins/tools.js +280 -0
  59. package/lib/policy-DnyHh7Bl.js +16 -0
  60. package/lib/prepare-DwHZudbA.js +134 -0
  61. package/lib/presentation-BlLjgDjP.js +47 -0
  62. package/lib/protocol.js +8 -0
  63. package/lib/queue-M917xHPS.js +153 -0
  64. package/lib/regular-file-BFpqMoub.js +136 -0
  65. package/lib/render-CJaVcKKC.js +48 -0
  66. package/lib/reported-sets-DdEKdeVb.js +122 -0
  67. package/lib/revision-DeoL_IUN.js +11 -0
  68. package/lib/scheduler-MaUEbXr3.js +64 -0
  69. package/lib/service-B7AI5jds.js +344 -0
  70. package/lib/service-BcHV5mc7.js +305 -0
  71. package/lib/service-CNjqHCBR.js +505 -0
  72. package/lib/service-C_i3BzdP.js +1106 -0
  73. package/lib/session-binding-BQrOGhZI.js +151 -0
  74. package/lib/session-state-CYqUhC95.js +38 -0
  75. package/lib/sessions-C2xuPFQv.js +218 -0
  76. package/lib/store.js +16 -0
  77. package/lib/structured-lyQCK-Zk.js +452 -0
  78. package/lib/subagent-yJsFxHmH.js +9 -0
  79. package/lib/team-credentials-C9xHrPIi.js +579 -0
  80. package/lib/team.js +3 -0
  81. package/lib/tool-schema-3b4gH1zf.js +28 -0
  82. package/lib/trace-Da0RnL5R.js +14 -0
  83. package/lib/traces-CHBo8y1z.js +11 -0
  84. package/lib/types/activities.d.ts +71 -0
  85. package/lib/types/advanced-configuration.d.ts +11 -0
  86. package/lib/types/client/ActivityDetails.d.ts +18 -0
  87. package/lib/types/client/AdvancedPreferences.d.ts +8 -0
  88. package/lib/types/client/BlankCommandFeedback.d.ts +10 -0
  89. package/lib/types/client/ComposerMenu.d.ts +24 -0
  90. package/lib/types/client/ConfigurationPage.d.ts +11 -0
  91. package/lib/types/client/ConnectionCheckDialog.d.ts +12 -0
  92. package/lib/types/client/KnowledgeDetail.d.ts +6 -0
  93. package/lib/types/client/KnowledgeDirectoryField.d.ts +11 -0
  94. package/lib/types/client/KnowledgePanel.d.ts +12 -0
  95. package/lib/types/client/KnowledgeReference.d.ts +13 -0
  96. package/lib/types/client/SessionToolbar.d.ts +16 -0
  97. package/lib/types/client/SettingsToast.d.ts +3 -0
  98. package/lib/types/client/SourceSessionLink.d.ts +15 -0
  99. package/lib/types/client/TeamCredentialField.d.ts +16 -0
  100. package/lib/types/client/TeamSettingsPage.d.ts +30 -0
  101. package/lib/types/client/configuration-errors.d.ts +2 -0
  102. package/lib/types/client/interaction-styles.d.ts +1 -0
  103. package/lib/types/client/interaction-ui.d.ts +30 -0
  104. package/lib/types/client/knowledge-labels.d.ts +5 -0
  105. package/lib/types/client/locales.d.ts +51 -0
  106. package/lib/types/commands/claim.d.ts +4 -0
  107. package/lib/types/commands/import.d.ts +10 -0
  108. package/lib/types/commands/status.d.ts +5 -0
  109. package/lib/types/config.d.ts +122 -0
  110. package/lib/types/configuration.d.ts +259 -0
  111. package/lib/types/credentials.d.ts +65 -0
  112. package/lib/types/dream/audit.d.ts +4 -0
  113. package/lib/types/dream/autonomous.d.ts +185 -0
  114. package/lib/types/dream/candidates.d.ts +34 -0
  115. package/lib/types/dream/checkpoint.d.ts +35 -0
  116. package/lib/types/dream/evidence-files.d.ts +10 -0
  117. package/lib/types/dream/evidence-store.d.ts +103 -0
  118. package/lib/types/dream/evidence.d.ts +30 -0
  119. package/lib/types/dream/index.d.ts +10 -0
  120. package/lib/types/dream/plan.d.ts +18 -0
  121. package/lib/types/dream/preservation.d.ts +6 -0
  122. package/lib/types/dream/review.d.ts +10 -0
  123. package/lib/types/dream/schema.d.ts +1475 -0
  124. package/lib/types/dream/service.d.ts +56 -0
  125. package/lib/types/dream/sync.d.ts +147 -0
  126. package/lib/types/dsh-adapter/configuration-remote.d.ts +1 -0
  127. package/lib/types/dsh-adapter/configuration-service.d.ts +28 -0
  128. package/lib/types/dsh-adapter/dream-agent.d.ts +4 -0
  129. package/lib/types/dsh-adapter/dream-evidence.d.ts +3 -0
  130. package/lib/types/dsh-adapter/formation-archive.d.ts +3 -0
  131. package/lib/types/dsh-adapter/formation-replay.d.ts +5 -0
  132. package/lib/types/dsh-adapter/formation.d.ts +4 -0
  133. package/lib/types/dsh-adapter/interaction-service.d.ts +13 -0
  134. package/lib/types/dsh-adapter/knowledge-paths.d.ts +3 -0
  135. package/lib/types/dsh-adapter/llm.d.ts +10 -0
  136. package/lib/types/dsh-adapter/project-upstream.d.ts +4 -0
  137. package/lib/types/dsh-adapter/runtime-pool.d.ts +110 -0
  138. package/lib/types/dsh-adapter/session-binding.d.ts +43 -0
  139. package/lib/types/dsh-adapter/source-sessions.d.ts +3 -0
  140. package/lib/types/dsh-adapter/team-credentials.d.ts +5 -0
  141. package/lib/types/dsh-adapter/tool-schema.d.ts +4 -0
  142. package/lib/types/dsh-adapter/tools.d.ts +5 -0
  143. package/lib/types/formation/capture.d.ts +19 -0
  144. package/lib/types/formation/checkpoint.d.ts +136 -0
  145. package/lib/types/formation/index.d.ts +10 -0
  146. package/lib/types/formation/prepare.d.ts +16 -0
  147. package/lib/types/formation/schema.d.ts +45 -0
  148. package/lib/types/formation/service.d.ts +58 -0
  149. package/lib/types/formation/transcript.d.ts +75 -0
  150. package/lib/types/formation/triggers.d.ts +3 -0
  151. package/lib/types/inbox/cascade.d.ts +3 -0
  152. package/lib/types/inbox/effects.d.ts +275 -0
  153. package/lib/types/inbox/index.d.ts +5 -0
  154. package/lib/types/inbox/prepare.d.ts +380 -0
  155. package/lib/types/inbox/service.d.ts +26 -0
  156. package/lib/types/inbox/sync.d.ts +9 -0
  157. package/lib/types/index.d.ts +1 -0
  158. package/lib/types/interaction-messages.d.ts +69 -0
  159. package/lib/types/interaction.d.ts +550 -0
  160. package/lib/types/knowledge/alignment.d.ts +49 -0
  161. package/lib/types/knowledge/catalog.d.ts +5 -0
  162. package/lib/types/knowledge/changes.d.ts +32 -0
  163. package/lib/types/knowledge/disputes.d.ts +3 -0
  164. package/lib/types/knowledge/errors.d.ts +9 -0
  165. package/lib/types/knowledge/ordering.d.ts +7 -0
  166. package/lib/types/knowledge/pages.d.ts +7 -0
  167. package/lib/types/knowledge/safety.d.ts +2 -0
  168. package/lib/types/knowledge/service.d.ts +52 -0
  169. package/lib/types/knowledge/sessions.d.ts +59 -0
  170. package/lib/types/knowledge/sources.d.ts +2 -0
  171. package/lib/types/knowledge/timestamps.d.ts +1 -0
  172. package/lib/types/knowledge/types.d.ts +84 -0
  173. package/lib/types/llm/response.d.ts +1 -0
  174. package/lib/types/llm/structured.d.ts +27 -0
  175. package/lib/types/local-name.d.ts +1 -0
  176. package/lib/types/plugins/client.d.ts +9 -0
  177. package/lib/types/plugins/commands.d.ts +11 -0
  178. package/lib/types/plugins/configuration.d.ts +8 -0
  179. package/lib/types/plugins/dream.d.ts +16 -0
  180. package/lib/types/plugins/formation.d.ts +16 -0
  181. package/lib/types/plugins/inbox.d.ts +16 -0
  182. package/lib/types/plugins/knowledge.d.ts +19 -0
  183. package/lib/types/plugins/prompt.d.ts +17 -0
  184. package/lib/types/plugins/tools.d.ts +10 -0
  185. package/lib/types/prompt/render.d.ts +2 -0
  186. package/lib/types/protocol/arbitration.d.ts +154 -0
  187. package/lib/types/protocol/auth.d.ts +31 -0
  188. package/lib/types/protocol/claim.d.ts +36 -0
  189. package/lib/types/protocol/dispute.d.ts +17 -0
  190. package/lib/types/protocol/ids.d.ts +20 -0
  191. package/lib/types/protocol/inbox.d.ts +141 -0
  192. package/lib/types/protocol/index.d.ts +11 -0
  193. package/lib/types/protocol/policy.d.ts +21 -0
  194. package/lib/types/protocol/revision.d.ts +2 -0
  195. package/lib/types/protocol/router.d.ts +114 -0
  196. package/lib/types/protocol/schema.d.ts +4 -0
  197. package/lib/types/protocol/time.d.ts +5 -0
  198. package/lib/types/protocol/trace.d.ts +11 -0
  199. package/lib/types/store/atomic.d.ts +8 -0
  200. package/lib/types/store/claim-edits.d.ts +33 -0
  201. package/lib/types/store/claims.d.ts +7 -0
  202. package/lib/types/store/context.d.ts +13 -0
  203. package/lib/types/store/delivery-status.d.ts +47 -0
  204. package/lib/types/store/disputes.d.ts +6 -0
  205. package/lib/types/store/entities.d.ts +16 -0
  206. package/lib/types/store/errors.d.ts +8 -0
  207. package/lib/types/store/inbox.d.ts +27 -0
  208. package/lib/types/store/index.d.ts +16 -0
  209. package/lib/types/store/jobs.d.ts +5 -0
  210. package/lib/types/store/lock.d.ts +11 -0
  211. package/lib/types/store/path-names.d.ts +2 -0
  212. package/lib/types/store/paths.d.ts +45 -0
  213. package/lib/types/store/presentation.d.ts +13 -0
  214. package/lib/types/store/regular-file.d.ts +2 -0
  215. package/lib/types/store/rejected-disputes.d.ts +18 -0
  216. package/lib/types/store/rename.d.ts +1 -0
  217. package/lib/types/store/reported-sets.d.ts +24 -0
  218. package/lib/types/store/session-state.d.ts +17 -0
  219. package/lib/types/store/traces.d.ts +6 -0
  220. package/lib/types/store/uploads.d.ts +312 -0
  221. package/lib/types/store/yaml.d.ts +8 -0
  222. package/lib/types/team/errors.d.ts +10 -0
  223. package/lib/types/team/http.d.ts +20 -0
  224. package/lib/types/team/index.d.ts +5 -0
  225. package/lib/types/team/maintainer-client.d.ts +18 -0
  226. package/lib/types/team/router-client.d.ts +14 -0
  227. package/lib/types/team/service.d.ts +28 -0
  228. package/lib/types/team/system-proxy.d.ts +9 -0
  229. package/lib/types/tools/claim.d.ts +63 -0
  230. package/lib/types/tools/consult-router.d.ts +11 -0
  231. package/lib/types/tools/subagent.d.ts +8 -0
  232. package/lib/types/tools/validation.d.ts +2 -0
  233. package/lib/types/upload/consolidation.d.ts +63 -0
  234. package/lib/types/upload/deliver.d.ts +15 -0
  235. package/lib/types/upload/index.d.ts +2 -0
  236. package/lib/types/upload/scheduler.d.ts +19 -0
  237. package/lib/types/upstreams.d.ts +5 -0
  238. package/lib/types/worker/queue.d.ts +17 -0
  239. package/lib/types/worker/types.d.ts +51 -0
  240. package/lib/types/worker/worker.d.ts +39 -0
  241. package/lib/types-C2ST2Zdg.js +17 -0
  242. package/lib/upload.js +3 -0
  243. package/lib/uploads-BCA2p92b.js +210 -0
  244. package/lib/worker-BBTYP2RE.js +185 -0
  245. package/locale/commands/en.json +1 -0
  246. package/locale/commands/zh.json +1 -0
  247. package/locale/dream/en.json +1 -0
  248. package/locale/dream/zh.json +1 -0
  249. package/locale/en.json +7 -0
  250. package/locale/formation/en.json +1 -0
  251. package/locale/formation/zh.json +1 -0
  252. package/locale/inbox/en.json +1 -0
  253. package/locale/inbox/zh.json +1 -0
  254. package/locale/knowledge/en.json +1 -0
  255. package/locale/knowledge/zh.json +1 -0
  256. package/locale/prompt/en.json +1 -0
  257. package/locale/prompt/zh.json +1 -0
  258. package/locale/tools/en.json +1 -0
  259. package/locale/tools/zh.json +1 -0
  260. package/locale/zh.json +7 -0
  261. package/package.json +262 -3
  262. package/prompts/claim_dream.j2 +77 -0
  263. package/prompts/claim_dream_legacy.j2 +63 -0
  264. package/prompts/dream_compaction.j2 +11 -0
  265. package/prompts/dream_evidence.j2 +5 -0
  266. package/prompts/inbox_claim_attribute_update_internalize.j2 +112 -0
  267. package/prompts/inbox_policy_update_internalize.j2 +87 -0
  268. package/prompts/knowledge.j2 +38 -0
  269. package/prompts/session_recap.j2 +113 -0
  270. package/prompts/what_is_claim.j2 +51 -0
  271. package/prompts/what_is_dispute.j2 +21 -0
  272. package/prompts/what_is_policy.j2 +22 -0
@@ -0,0 +1,71 @@
1
+ import { a as TextSchema, c as AgentIdSchema, l as ClaimIdSchema, o as optional, t as ClaimSchema, u as DisputeIdSchema, y as TimestampSchema } from "./claim-DOAGe8ZK.js";
2
+ import { z } from "zod";
3
+ //#region src/protocol/router.ts
4
+ const count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
5
+ const AgentQuerySchema = z.object({
6
+ scope: TextSchema,
7
+ semantic_query: TextSchema.nullable().default(null)
8
+ });
9
+ const CandidateClaimSchema = ClaimSchema.extend({
10
+ open_dispute_ids: z.array(DisputeIdSchema).default([]),
11
+ resolved_dispute_ids: z.array(DisputeIdSchema).default([])
12
+ });
13
+ const DisputeRefSchema = z.object({
14
+ id: DisputeIdSchema,
15
+ name: TextSchema,
16
+ claim_ids: z.array(ClaimIdSchema),
17
+ summary: TextSchema,
18
+ status: z.enum(["open", "resolved"])
19
+ });
20
+ const retrievalDebug = z.object({
21
+ mode: TextSchema,
22
+ failed_paths: z.array(TextSchema).default([]),
23
+ error_summaries: z.array(TextSchema).default([]),
24
+ lexical_hits: count.default(0),
25
+ vector_hits: count.default(0),
26
+ rerank_fallback: z.boolean().default(false),
27
+ candidates: z.array(z.object({
28
+ claim_id: TextSchema,
29
+ hit_sources: TextSchema,
30
+ lexical_score: count.default(0),
31
+ vector_score: count.default(0),
32
+ rank_before_rerank: count.default(0),
33
+ rank_after_rerank: count.default(0),
34
+ vector_status: TextSchema
35
+ })).default([])
36
+ });
37
+ const RouterQueryResultSchema = z.object({
38
+ candidate_claims: z.array(CandidateClaimSchema),
39
+ disputes: z.array(DisputeRefSchema),
40
+ retrieval_debug: optional(retrievalDebug)
41
+ });
42
+ const ScopeOverviewItemSchema = z.strictObject({
43
+ scope: TextSchema,
44
+ active_claims: count,
45
+ stale_claims: count,
46
+ open_disputes: count,
47
+ resolved_disputes: count,
48
+ latest_claim_created_at: TimestampSchema
49
+ });
50
+ const ScopesOverviewSnapshotSchema = z.strictObject({ scopes: z.array(ScopeOverviewItemSchema).default([]) });
51
+ //#endregion
52
+ //#region src/protocol/auth.ts
53
+ const AuthEnvelopeSchema = z.strictObject({
54
+ agent_id: AgentIdSchema,
55
+ acn_key: TextSchema
56
+ });
57
+ const authRequestSchema = (data) => z.strictObject({
58
+ auth: AuthEnvelopeSchema,
59
+ data
60
+ });
61
+ const HealthRequestSchema = z.strictObject({
62
+ auth: AuthEnvelopeSchema.nullish(),
63
+ data: z.strictObject({}).default({})
64
+ });
65
+ const HealthResponseSchema = z.object({
66
+ status: z.string(),
67
+ team_auth_enabled: z.boolean(),
68
+ auth_passed: z.boolean().optional()
69
+ });
70
+ //#endregion
71
+ export { AgentQuerySchema as a, RouterQueryResultSchema as c, authRequestSchema as i, ScopeOverviewItemSchema as l, HealthRequestSchema as n, CandidateClaimSchema as o, HealthResponseSchema as r, DisputeRefSchema as s, AuthEnvelopeSchema as t, ScopesOverviewSnapshotSchema as u };
@@ -0,0 +1,188 @@
1
+ import { t as ClaimSchema, v as deriveTraceId, x as nowSeconds } from "./claim-DOAGe8ZK.js";
2
+ import { c as TranscriptStore, l as processedThrough } from "./structured-lyQCK-Zk.js";
3
+ import { C as StoreError, _ as JobError, c as readYamlOr, l as writeYamlAtomic, n as withFileLock } from "./lock-DbmlKOoX.js";
4
+ import { a as analysisIsStale, c as observeApplied, i as STALE_PLAN_WARNING, l as sameClaim, o as claimChanges, s as ensureKnowledgeReady, t as AnalysisChanged } from "./alignment-CwH0nBf-.js";
5
+ import { i as ClaimStore, r as reportedClaimSetKey, t as ReportedSetStore } from "./reported-sets-DdEKdeVb.js";
6
+ import { t as TraceSchema } from "./trace-Da0RnL5R.js";
7
+ import { t as TraceStore } from "./traces-CHBo8y1z.js";
8
+ import { t as DisputeSchema } from "./dispute-CtrInHzf.js";
9
+ import { r as UploadStore } from "./uploads-BCA2p92b.js";
10
+ import { t as DreamStore } from "./checkpoint-RgcdqifN.js";
11
+ import { n as ClaimEditStore, t as DisputeStore } from "./disputes-ByEmi43j.js";
12
+ import { z } from "zod";
13
+ //#region src/knowledge/disputes.ts
14
+ async function newDisputes(context, proposed, local) {
15
+ const sets = /* @__PURE__ */ new Set();
16
+ if (context.mode === "solo") for (const dispute of local) sets.add(reportedClaimSetKey(dispute.claims));
17
+ else {
18
+ for (const dispute of (await new UploadStore(context).read()).disputes) sets.add(reportedClaimSetKey(dispute.claims));
19
+ for (const key of Object.keys((await new ReportedSetStore(context).read()).reported_claim_sets)) sets.add(key);
20
+ }
21
+ return proposed.filter((dispute) => {
22
+ const key = reportedClaimSetKey(dispute.claims);
23
+ if (sets.has(key)) return false;
24
+ sets.add(key);
25
+ return true;
26
+ });
27
+ }
28
+ //#endregion
29
+ //#region src/formation/checkpoint.ts
30
+ const CheckpointSchema = z.strictObject({
31
+ schemaVersion: z.literal(1),
32
+ sessionId: z.string().regex(/^[a-zA-Z0-9_-]+$/),
33
+ jobId: z.string().regex(/^[a-zA-Z0-9_-]+$/),
34
+ kind: z.enum(["recap", "finalize"]),
35
+ fromSeq: z.number().int().min(-1),
36
+ untilSeq: z.number().int().nonnegative(),
37
+ status: z.enum(["prepared", "applied"]),
38
+ analysisClaims: z.array(ClaimSchema).nullable(),
39
+ preparedClaims: z.array(ClaimSchema),
40
+ appliedClaims: z.array(ClaimSchema),
41
+ teamAuthorized: z.boolean().optional(),
42
+ disputes: z.array(DisputeSchema),
43
+ trace: TraceSchema.nullable(),
44
+ warnings: z.array(z.string())
45
+ });
46
+ var FormationStore = class {
47
+ context;
48
+ transcript;
49
+ constructor(context) {
50
+ this.context = context;
51
+ this.transcript = new TranscriptStore(context);
52
+ }
53
+ async read(sessionId) {
54
+ const checkpoint = await readYamlOr(this.context.paths.finalizeCheckpoint(sessionId), CheckpointSchema, () => null);
55
+ if (checkpoint !== null && checkpoint.sessionId !== sessionId) throw new StoreError("decode", "Checkpoint session differs from its directory.");
56
+ return checkpoint;
57
+ }
58
+ write(checkpoint) {
59
+ return writeYamlAtomic(this.context.paths.finalizeCheckpoint(checkpoint.sessionId), checkpoint, CheckpointSchema, this.context.logger);
60
+ }
61
+ async recover() {
62
+ const ids = await this.transcript.sessions();
63
+ if ((await Promise.all(ids.map((id) => this.read(id)))).filter((value) => value !== null).length === 0) return;
64
+ await withFileLock(this.context.paths.knowledgeLock, () => this.recoverLocked(), { timeoutMs: this.context.lockTimeoutMs });
65
+ }
66
+ async recoverLocked() {
67
+ await new DreamStore(this.context).recoverLocked();
68
+ for (const id of await this.transcript.sessions()) {
69
+ const checkpoint = await this.read(id);
70
+ if (checkpoint === null) continue;
71
+ if (checkpoint.status === "prepared") await this.applyLocked(checkpoint);
72
+ else {
73
+ const state = await this.transcript.state(id);
74
+ if (processedThrough(state) < checkpoint.untilSeq || checkpoint.kind === "finalize" && state.finalizedThroughSeq < checkpoint.untilSeq) await this.transcript.advance(id, checkpoint.kind, checkpoint.untilSeq);
75
+ }
76
+ }
77
+ }
78
+ async commit(input, control) {
79
+ return withFileLock(this.context.paths.knowledgeLock, async () => {
80
+ await new DreamStore(this.context).recoverLocked();
81
+ await ensureKnowledgeReady(this.context.paths.root);
82
+ await new ClaimEditStore(this.context).recoverLocked();
83
+ await this.recoverLocked();
84
+ if (processedThrough(await this.transcript.state(input.sessionId)) >= input.untilSeq) return {
85
+ applied: false,
86
+ warnings: [],
87
+ claimCount: 0,
88
+ disputeCount: 0,
89
+ traceCount: 0
90
+ };
91
+ control.signal.throwIfAborted();
92
+ const { claims, disputes, usedClaimIds, warnings } = input.prepared;
93
+ if (claimChanges(input.analysisClaims, claims, [], await new ClaimStore(this.context).list()).length > 0) throw new AnalysisChanged();
94
+ const createdAt = nowSeconds();
95
+ const traceName = Array.from(input.task.split("\n").find((line) => line.trim()) ?? "session_recap").slice(0, 60).join("");
96
+ const existingTraces = new Set((await new TraceStore(this.context).list()).map((trace) => trace.id));
97
+ let traceId = deriveTraceId(createdAt, traceName, usedClaimIds, claims.map((claim) => claim.id));
98
+ for (let attempt = 0; existingTraces.has(traceId); attempt += 1) {
99
+ if (attempt >= 7) throw new JobError("id_collision", "Trace ID 冲突;请重试本次形成任务。");
100
+ traceId = deriveTraceId(createdAt, traceName, usedClaimIds, claims.map((claim) => claim.id));
101
+ }
102
+ const trace = claims.length === 0 && usedClaimIds.length === 0 ? null : TraceSchema.parse({
103
+ id: traceId,
104
+ name: traceName,
105
+ task: input.task,
106
+ agent: this.context.agentId,
107
+ input_claims: usedClaimIds,
108
+ output_claims: claims.map((claim) => claim.id),
109
+ created_at: createdAt
110
+ });
111
+ const existingDisputes = await new DisputeStore(this.context).list();
112
+ const uniqueDisputes = await newDisputes(this.context, disputes, existingDisputes);
113
+ if (uniqueDisputes.some((dispute) => existingDisputes.some((value) => value.id === dispute.id))) throw new JobError("id_collision", "Dispute ID 冲突;请重试本次形成任务。");
114
+ const checkpoint = CheckpointSchema.parse({
115
+ schemaVersion: 1,
116
+ sessionId: input.sessionId,
117
+ jobId: input.jobId,
118
+ kind: input.kind,
119
+ fromSeq: input.fromSeq,
120
+ untilSeq: input.untilSeq,
121
+ status: "prepared",
122
+ teamAuthorized: this.context.mode === "team",
123
+ analysisClaims: input.analysisClaims,
124
+ preparedClaims: claims,
125
+ appliedClaims: [],
126
+ disputes: uniqueDisputes,
127
+ trace,
128
+ warnings
129
+ });
130
+ control.signal.throwIfAborted();
131
+ control.prepared();
132
+ await this.write(checkpoint);
133
+ await this.applyLocked(checkpoint);
134
+ return {
135
+ applied: true,
136
+ warnings: checkpoint.warnings,
137
+ claimCount: checkpoint.appliedClaims.length,
138
+ disputeCount: checkpoint.disputes.length,
139
+ traceCount: checkpoint.trace === null ? 0 : 1,
140
+ entityIds: [
141
+ ...checkpoint.appliedClaims.map((claim) => claim.id),
142
+ ...checkpoint.disputes.map((dispute) => dispute.id),
143
+ ...checkpoint.trace === null ? [] : [checkpoint.trace.id]
144
+ ]
145
+ };
146
+ }, {
147
+ timeoutMs: this.context.lockTimeoutMs,
148
+ signal: control.signal
149
+ });
150
+ }
151
+ async applyLocked(checkpoint) {
152
+ await ensureKnowledgeReady(this.context.paths.root);
153
+ const current = await new ClaimStore(this.context).list();
154
+ observeApplied(checkpoint.preparedClaims, current, checkpoint.appliedClaims);
155
+ if (analysisIsStale(checkpoint.analysisClaims, claimChanges(checkpoint.analysisClaims, checkpoint.preparedClaims, checkpoint.appliedClaims, current))) {
156
+ if (checkpoint.preparedClaims.some((claim) => !checkpoint.appliedClaims.some((applied) => applied.id === claim.id)) || checkpoint.disputes.length > 0) {
157
+ checkpoint.warnings.push(STALE_PLAN_WARNING);
158
+ this.context.logger.warn(STALE_PLAN_WARNING);
159
+ }
160
+ checkpoint.preparedClaims = [];
161
+ checkpoint.disputes = [];
162
+ checkpoint.analysisClaims = current;
163
+ await this.write(checkpoint);
164
+ }
165
+ const targets = [...checkpoint.preparedClaims].sort((a, b) => Number(a.status === "deprecated") - Number(b.status === "deprecated"));
166
+ for (const claim of targets) if (!checkpoint.appliedClaims.some((applied) => applied.id === claim.id)) {
167
+ await new ClaimStore(this.context).write(claim);
168
+ checkpoint.appliedClaims.push(claim);
169
+ await this.write(checkpoint);
170
+ }
171
+ if (checkpoint.trace !== null) {
172
+ checkpoint.trace.output_claims = checkpoint.appliedClaims.map((claim) => claim.id);
173
+ if (checkpoint.trace.output_claims.length > 0 || checkpoint.trace.input_claims.length > 0) await new TraceStore(this.context).write(checkpoint.trace);
174
+ }
175
+ for (const dispute of checkpoint.disputes) await new DisputeStore(this.context).write(dispute);
176
+ if (checkpoint.teamAuthorized === void 0 && this.context.mode === "team") checkpoint.warnings.push("旧形成事务缺少团队共享授权,仅恢复本地效果。");
177
+ if (checkpoint.teamAuthorized === true && this.context.mode === "team") {
178
+ const actual = await new ClaimStore(this.context).list();
179
+ await new UploadStore(this.context).enqueue(checkpoint.appliedClaims.filter((claim) => actual.some((value) => sameClaim(value, claim))), checkpoint.disputes, true);
180
+ }
181
+ checkpoint.status = "applied";
182
+ await this.write(checkpoint);
183
+ await this.transcript.advance(checkpoint.sessionId, checkpoint.kind, checkpoint.untilSeq);
184
+ for (const warning of checkpoint.warnings) this.context.logger.warn(warning);
185
+ }
186
+ };
187
+ //#endregion
188
+ export { FormationStore as n, newDisputes as r, CheckpointSchema as t };
@@ -0,0 +1,318 @@
1
+ import { m as SourceIdSchema, v as deriveTraceId, x as nowSeconds } from "./claim-DOAGe8ZK.js";
2
+ import { A as valueHash, E as reviewInput, K as DreamStateSchema, S as contentHash, T as reaches, V as CheckpointSchema, Z as KeySchema, b as validateSelfReview, et as OriginSchema, pt as requireDream, r as EvidenceStore, rt as ProgressSchema, v as versions, w as prepareGroup, x as validateSemanticReview } from "./evidence-store-DLFvSuNa.js";
3
+ import { C as StoreError, c as readYamlOr, d as removeFile, f as writeTextAtomic, l as writeYamlAtomic, n as withFileLock, s as readYaml, w as hasCode } from "./lock-DbmlKOoX.js";
4
+ import { l as sameClaim } from "./alignment-CwH0nBf-.js";
5
+ import { i as ClaimStore } from "./reported-sets-DdEKdeVb.js";
6
+ import { t as TraceSchema } from "./trace-Da0RnL5R.js";
7
+ import { t as TraceStore } from "./traces-CHBo8y1z.js";
8
+ import { r as UploadStore } from "./uploads-BCA2p92b.js";
9
+ import { z } from "zod";
10
+ import fs from "node:fs/promises";
11
+ import { dirname, join, relative, resolve } from "node:path";
12
+ //#region src/dream/audit.ts
13
+ async function executionAudit(context, jobId, checkpoint) {
14
+ const id = checkpoint.operation?.validation_id ?? "final";
15
+ const note = `# Dream ${checkpoint.applied ? "已应用" : "prepared(尚未确认完成)"}\n\n这份记录核对结构、来源和版本,不保证语义正确。\n\n组:${checkpoint.operation?.group_id ?? "final"}。\n\n${checkpoint.groups.map((group) => `- completed=${group.completed} skipped=${group.skipped}:${group.before.map((claim) => claim.id).join(", ")}`).join("\n")}\n\n实际变更:${Object.keys(checkpoint.self_versions).join(", ") || "无"}\n\n\`\`\`json\n${JSON.stringify(checkpoint, null, 2)}\n\`\`\`\n`;
16
+ await writeTextAtomic(join(context.paths.dreamJob(jobId), "executions", `${id}.md`), note, context.logger);
17
+ }
18
+ async function jobReport(context, jobId, progress, coverage, records) {
19
+ const note = `# Dream ${progress.finished ? "本次已结束" : progress.autonomy?.wrap_up !== void 0 ? "额度收尾中" : "处理中"}\n\n模型轮数:${progress.autonomy === void 0 ? "旧阶段模式" : `${progress.autonomy.steps}/${progress.autonomy.limit};收尾 ${progress.autonomy.wrap_up?.steps ?? 0}/${progress.autonomy.wrap_up?.limit ?? 0}`}\n\n质量清理:${progress.discovery.review.quality}\n\n证据校准:${progress.discovery.review.evidence}\n\n主题整合:${progress.discovery.review.consolidation}\n\n覆盖:\`${JSON.stringify(coverage)}\`\n\n${progress.entries.map((entry) => `- ${entry.candidate.group_id}:${entry.status};${entry.reason || entry.candidate.reason}`).join("\n") || "本轮没有需要修改的候选。"}\n\n实际修改 ID:${[...new Set(records.flatMap((record) => Object.keys(record.self_versions)))].join(", ") || "无"}\n\n未探索不代表不存在;保持原样是合法结果。已提交组的保留信息与最终名称经过模型语义复核,硬校验不证明语义正确。\n`;
20
+ await writeTextAtomic(join(context.paths.dreamJob(jobId), "report.md"), note, context.logger);
21
+ }
22
+ //#endregion
23
+ //#region src/dream/checkpoint.ts
24
+ const sameJson = (a, b) => valueHash(a) === valueHash(b);
25
+ var DreamStore = class {
26
+ context;
27
+ settleRegular;
28
+ constructor(context, settleRegular) {
29
+ this.context = context;
30
+ this.settleRegular = settleRegular;
31
+ }
32
+ state() {
33
+ return readYamlOr(this.context.paths.dreamState, DreamStateSchema, () => DreamStateSchema.parse({}));
34
+ }
35
+ origin(jobId) {
36
+ return readYamlOr(join(this.context.paths.dreamJob(jobId), "origin.yaml"), OriginSchema, () => null);
37
+ }
38
+ progress(jobId) {
39
+ return readYamlOr(join(this.context.paths.dreamJob(jobId), "progress.yaml"), ProgressSchema, () => null);
40
+ }
41
+ final(jobId) {
42
+ return readYamlOr(this.context.paths.dreamFinal(jobId), CheckpointSchema, () => null);
43
+ }
44
+ async saveOrigin(jobId, origin) {
45
+ if (await this.origin(jobId) === null) await writeYamlAtomic(join(this.context.paths.dreamJob(jobId), "origin.yaml"), origin, OriginSchema, this.context.logger);
46
+ }
47
+ async saveProgress(jobId, progress) {
48
+ await writeYamlAtomic(join(this.context.paths.dreamJob(jobId), "progress.yaml"), progress, ProgressSchema, this.context.logger);
49
+ await this.report(jobId, progress);
50
+ }
51
+ async report(jobId, progress) {
52
+ await jobReport(this.context, jobId, progress, (await this.origin(jobId))?.coverage, (await this.records(jobId)).map((entry) => entry.checkpoint));
53
+ }
54
+ async records(jobId) {
55
+ const root = join(this.context.paths.dreamJob(jobId), "executions");
56
+ let files;
57
+ try {
58
+ files = (await fs.readdir(root)).filter((name) => /^[0-9a-f]{64}\.yaml$/.test(name));
59
+ } catch (error) {
60
+ if (hasCode(error, "ENOENT")) return [];
61
+ throw error;
62
+ }
63
+ return await Promise.all(files.sort().map(async (name) => {
64
+ const path = join(root, name);
65
+ const checkpoint = await readYaml(path, CheckpointSchema);
66
+ if (checkpoint.operation?.job_id !== jobId || checkpoint.operation.validation_id !== name.slice(0, -5)) throw new StoreError("conflict", "Dream execution identity differs from its directory.");
67
+ return {
68
+ path,
69
+ checkpoint
70
+ };
71
+ }));
72
+ }
73
+ async jobs() {
74
+ try {
75
+ return (await fs.readdir(this.context.paths.dreamRoot, { withFileTypes: true })).filter((entry) => entry.isDirectory() && KeySchema.safeParse(entry.name).success).map((entry) => entry.name);
76
+ } catch (error) {
77
+ if (hasCode(error, "ENOENT")) return [];
78
+ throw error;
79
+ }
80
+ }
81
+ async pending() {
82
+ const path = await readYamlOr(this.context.paths.dreamPending, z.string(), () => null);
83
+ if (path === null) return null;
84
+ const resolved = resolve(path);
85
+ const location = relative(this.context.paths.root, resolved).split("\\").join("/");
86
+ if (!/^dream\/[a-zA-Z0-9_-]+\/executions\/[0-9a-f]{64}\.yaml$/.test(location) && !/^runtime\/supervisor\/dream\/[a-zA-Z0-9_-]+\.yaml$/.test(location)) throw new StoreError("conflict", "Dream pending path is outside the allowed commit directories.");
87
+ return resolved;
88
+ }
89
+ async unfinished() {
90
+ const pending = await this.pending();
91
+ const paths = new Set(pending === null ? [] : [pending]);
92
+ for (const job of await this.jobs()) for (const record of await this.records(job)) if (!record.checkpoint.applied) paths.add(record.path);
93
+ const root = dirname(this.context.paths.dreamFinal("scan"));
94
+ let files = [];
95
+ try {
96
+ files = await fs.readdir(root);
97
+ } catch (error) {
98
+ if (!hasCode(error, "ENOENT")) throw error;
99
+ }
100
+ for (const file of files.filter((name) => /^[a-zA-Z0-9_-]+\.yaml$/.test(name)).sort()) {
101
+ const path = join(root, file);
102
+ if (!(await readYaml(path, CheckpointSchema)).applied) paths.add(path);
103
+ }
104
+ return [...paths];
105
+ }
106
+ async recover() {
107
+ if ((await this.unfinished()).length === 0) return;
108
+ await withFileLock(this.context.paths.knowledgeLock, () => this.recoverLocked(), { timeoutMs: this.context.lockTimeoutMs });
109
+ }
110
+ async recoverLocked() {
111
+ for (const path of await this.unfinished()) await this.applyLocked(path);
112
+ }
113
+ async commitGroup(jobId, groupId, group, validation, semantic, selfReview, control) {
114
+ const evidence = new EvidenceStore(this.context, jobId, groupId);
115
+ const receipts = z.record(z.string(), z.json()).parse((await evidence.read())?.receipts ?? {});
116
+ requireDream(sameJson(reviewInput(groupId, group, validation.input.before, receipts), validation), "草稿、真实查证回执与复核版本不一致。");
117
+ if (selfReview !== null) validateSelfReview(validation, selfReview);
118
+ validateSemanticReview(validation, semantic);
119
+ const prepared = prepareGroup(group, validation.input.before, this.context.agentId, nowSeconds(), {
120
+ enabled: group.kind === "evidence" || Object.keys(receipts).length > 0,
121
+ receipts,
122
+ semanticReview: selfReview === null
123
+ });
124
+ return withFileLock(this.context.paths.knowledgeLock, async () => {
125
+ await this.recoverLocked();
126
+ await this.settleRegular?.();
127
+ const path = this.context.paths.dreamExecution(jobId, validation.validation_id);
128
+ const existing = await readYamlOr(path, CheckpointSchema, () => null);
129
+ if (existing !== null) {
130
+ requireDream(existing.operation?.group_id === groupId, "执行回执属于其他组。");
131
+ return this.applyLocked(path);
132
+ }
133
+ const origin = await this.origin(jobId);
134
+ requireDream(origin !== null, "缺少 Dream 原始快照。");
135
+ const priorTargets = (await this.records(jobId)).flatMap(({ checkpoint }) => checkpoint.groups.filter((item) => item.completed && !item.skipped).flatMap((item) => item.after));
136
+ requireDream(prepared.before.every((claim) => origin.claims.some((original) => sameClaim(original, claim)) || selfReview === null && priorTargets.some((target) => sameClaim(target, claim))), "执行前 Claim 必须来自冻结快照或本轮已提交版本,不能采用外部并发修改。");
137
+ for (const item of semantic.claims) if (item.factual_correction || group.kind === "evidence") requireDream(origin.claims.some((claim) => claim.id === item.claim_id && claim.confidence !== "high"), "本轮原始 high Claim 不得先降级再进行事实校准。");
138
+ await evidence.authorize(validation.input.evidence, origin.workspace_root, prepared.before);
139
+ const snapshot_at = nowSeconds();
140
+ const checkpoint = CheckpointSchema.parse({
141
+ team_authorized: this.context.mode === "team",
142
+ snapshot_at,
143
+ input_versions: {},
144
+ coverage: origin.coverage,
145
+ plan: {
146
+ review: {
147
+ quality: "逐组复核",
148
+ evidence: "独立文件版本、逐 Claim 依据与引用校验;不保证语义正确",
149
+ consolidation: "逐输入核对信息去向"
150
+ },
151
+ groups: [group]
152
+ },
153
+ receipts: validation.input.evidence,
154
+ exploration_receipts: Object.keys(receipts).length,
155
+ groups: [prepared],
156
+ safety_reviews: [],
157
+ self_reviews: selfReview === null ? [] : [{
158
+ validation,
159
+ review: selfReview
160
+ }],
161
+ trace_id: deriveTraceId(snapshot_at, "dream_claim_review", prepared.before.map((claim) => claim.id), prepared.after.map((claim) => claim.id)),
162
+ applied: false,
163
+ success_at: null,
164
+ self_versions: {},
165
+ operation: {
166
+ job_id: jobId,
167
+ group_id: groupId,
168
+ validation_id: validation.validation_id,
169
+ review: semantic,
170
+ hard_validation_passed: true
171
+ }
172
+ });
173
+ control.signal.throwIfAborted();
174
+ control.prepared();
175
+ await writeYamlAtomic(path, checkpoint, CheckpointSchema, this.context.logger);
176
+ return this.applyLocked(path);
177
+ }, {
178
+ timeoutMs: this.context.lockTimeoutMs,
179
+ signal: control.signal
180
+ });
181
+ }
182
+ async finish(jobId, progress, control) {
183
+ requireDream(progress.entries.every((entry) => entry.status !== "pending"), "仍有已登记候选未执行或明确保留,不能结束。");
184
+ return withFileLock(this.context.paths.knowledgeLock, async () => {
185
+ await this.recoverLocked();
186
+ await this.settleRegular?.();
187
+ const path = this.context.paths.dreamFinal(jobId);
188
+ if (await readYamlOr(path, CheckpointSchema, () => null) !== null) return this.applyLocked(path);
189
+ const origin = await this.origin(jobId);
190
+ requireDream(origin !== null, "缺少 Dream 原始快照。");
191
+ const records = (await this.records(jobId)).map((record) => record.checkpoint);
192
+ requireDream(records.every((record) => record.applied), "整理组仍待恢复。");
193
+ const checkpoint = CheckpointSchema.parse({
194
+ team_authorized: this.context.mode === "team",
195
+ snapshot_at: origin.snapshot_at,
196
+ input_versions: versions(origin.claims),
197
+ coverage: origin.coverage,
198
+ plan: {
199
+ review: progress.discovery.review,
200
+ groups: records.flatMap((record) => record.plan.groups)
201
+ },
202
+ receipts: Object.fromEntries(records.flatMap((record) => Object.entries(record.receipts))),
203
+ exploration_receipts: records.reduce((count, record) => count + (record.exploration_receipts ?? 0), 0),
204
+ groups: records.flatMap((record) => record.groups),
205
+ safety_reviews: [],
206
+ self_reviews: records.flatMap((record) => record.self_reviews),
207
+ trace_id: deriveTraceId(nowSeconds(), "dream_claim_review", [], []),
208
+ applied: false,
209
+ success_at: null,
210
+ self_versions: Object.fromEntries(records.flatMap((record) => Object.entries(record.self_versions))),
211
+ operation: null
212
+ });
213
+ control.signal.throwIfAborted();
214
+ control.prepared();
215
+ await writeYamlAtomic(path, checkpoint, CheckpointSchema, this.context.logger);
216
+ return this.applyLocked(path);
217
+ }, {
218
+ timeoutMs: this.context.lockTimeoutMs,
219
+ signal: control.signal
220
+ });
221
+ }
222
+ async applyLocked(path) {
223
+ const checkpoint = await readYaml(path, CheckpointSchema);
224
+ const pointer = await this.pending();
225
+ if (pointer !== null && pointer !== path) throw new StoreError("conflict", "Another Dream group requires recovery first.");
226
+ if (checkpoint.applied && pointer === null) return checkpoint;
227
+ const jobId = checkpoint.operation?.job_id ?? KeySchema.parse(path.slice(dirname(path).length + 1, -5));
228
+ requireDream(checkpoint.operation === null || checkpoint.operation === void 0 || checkpoint.operation.hard_validation_passed, "执行记录尚未通过硬校验。");
229
+ requireDream(checkpoint.safety_reviews.length === 0, "不支持没有受限查证授权清单的旧 safety_reviews;不能跳过其证据依赖。");
230
+ requireDream(checkpoint.groups.length === checkpoint.plan.groups.length, "整理提交的组数量不一致。");
231
+ for (const group of checkpoint.groups) requireDream(group.before.length === group.after.length && group.before.every((claim, index) => claim.id === group.after[index]?.id && claim.holder === this.context.agentId && group.after[index]?.holder === this.context.agentId), "整理提交的 before/after 或 holder 不一致。");
232
+ await executionAudit(this.context, jobId, checkpoint);
233
+ if (!checkpoint.applied) {
234
+ if (checkpoint.team_authorized === void 0 && this.context.mode === "team") this.context.logger.warn("旧 Dream 事务缺少团队共享授权,仅恢复本地效果。");
235
+ await writeYamlAtomic(this.context.paths.dreamPending, path, z.string(), this.context.logger);
236
+ for (const [index, group] of checkpoint.groups.entries()) {
237
+ if (group.completed) continue;
238
+ const plan = checkpoint.plan.groups[index];
239
+ requireDream(plan !== void 0, "缺少提交计划。");
240
+ const selected = Object.fromEntries(plan.evidence_ids.map((id) => {
241
+ const receipt = checkpoint.receipts[id];
242
+ requireDream(receipt !== void 0, "执行记录缺少证据依赖。");
243
+ return [id, receipt];
244
+ }));
245
+ const origin = await this.origin(jobId);
246
+ const validEvidence = await new EvidenceStore(this.context, jobId, checkpoint.operation?.group_id ?? "legacy").authorize(selected, origin?.workspace_root, group.before);
247
+ const current = await new ClaimStore(this.context).list();
248
+ const graph = [...current.filter((claim) => !group.after.some((target) => target.id === claim.id)), ...group.after];
249
+ const conflict = !validEvidence || group.before.some((before, index) => !current.some((claim) => claim.id === before.id && (sameClaim(claim, before) || group.after[index] !== void 0 && sameClaim(claim, group.after[index])))) || group.after.some((after) => after.source_claim_ids.some((source) => !group.before.find((before) => before.id === after.id)?.source_claim_ids.includes(source) && graph.some((claim) => claim.id === source && reaches(claim.id, after.id, graph))));
250
+ if (!conflict) {
251
+ for (const target of [...group.after].sort((a, b) => Number(a.status === "deprecated") - Number(b.status === "deprecated"))) if (!current.some((claim) => sameClaim(claim, target))) await new ClaimStore(this.context).write(target);
252
+ }
253
+ const actual = await new ClaimStore(this.context).list();
254
+ const staged = group.after.filter((target) => actual.some((claim) => sameClaim(claim, target)));
255
+ const dependencies = plan.kind === "consolidation" ? staged.filter((claim) => claim.status === "deprecated").map((retired) => {
256
+ const before = group.before.find((claim) => claim.id === retired.id);
257
+ requireDream(before !== void 0, "整合缺少来源原文。");
258
+ const ids = plan.coverage.find((item) => item.input_id === retired.id)?.output_ids ?? [];
259
+ return {
260
+ before,
261
+ retired,
262
+ carriers: group.after.filter((claim) => ids.includes(claim.id) && claim.status !== "deprecated")
263
+ };
264
+ }) : [];
265
+ if (checkpoint.team_authorized === true) await new UploadStore(this.context).enqueue(staged, [], true, dependencies);
266
+ for (const claim of staged) if (!group.before.some((before) => sameClaim(before, claim))) checkpoint.self_versions[claim.id] = contentHash(claim);
267
+ group.skipped = conflict;
268
+ group.completed = true;
269
+ await writeYamlAtomic(path, checkpoint, CheckpointSchema, this.context.logger);
270
+ await executionAudit(this.context, jobId, checkpoint);
271
+ }
272
+ const input_claims = [...new Set(checkpoint.groups.flatMap((group) => group.before.map((claim) => claim.id)))].map((id) => SourceIdSchema.parse(id));
273
+ await new TraceStore(this.context).write(TraceSchema.parse({
274
+ id: checkpoint.trace_id,
275
+ name: "dream_claim_review",
276
+ task: JSON.stringify({
277
+ kind: "dream",
278
+ coverage: checkpoint.coverage,
279
+ review: checkpoint.plan,
280
+ evidence: checkpoint.receipts,
281
+ groups: checkpoint.groups,
282
+ self_reviews: checkpoint.self_reviews
283
+ }),
284
+ agent: this.context.agentId,
285
+ input_claims,
286
+ output_claims: Object.keys(checkpoint.self_versions),
287
+ created_at: checkpoint.snapshot_at
288
+ }));
289
+ checkpoint.applied = true;
290
+ checkpoint.success_at = nowSeconds();
291
+ await writeYamlAtomic(path, checkpoint, CheckpointSchema, this.context.logger);
292
+ }
293
+ await executionAudit(this.context, jobId, checkpoint);
294
+ const previous = await this.state();
295
+ const state = checkpoint.operation !== null && checkpoint.operation !== void 0 || previous.last_success_at !== void 0 && previous.last_success_at !== null && checkpoint.success_at !== null && checkpoint.success_at !== void 0 && Date.parse(previous.last_success_at) > Date.parse(checkpoint.success_at) ? {
296
+ ...previous,
297
+ known_versions: {
298
+ ...previous.known_versions,
299
+ ...checkpoint.self_versions
300
+ }
301
+ } : {
302
+ last_success_at: checkpoint.success_at,
303
+ last_input_snapshot_at: checkpoint.snapshot_at,
304
+ known_versions: {
305
+ ...checkpoint.input_versions,
306
+ ...checkpoint.self_versions
307
+ }
308
+ };
309
+ await writeYamlAtomic(this.context.paths.dreamState, state, DreamStateSchema, this.context.logger);
310
+ await removeFile(this.context.paths.dreamPending, this.context.logger);
311
+ return checkpoint;
312
+ }
313
+ async archive(jobId, key, value) {
314
+ await writeTextAtomic(join(this.context.paths.dreamJob(jobId), "history", `${KeySchema.parse(key)}.json`), JSON.stringify(value, null, 2), this.context.logger);
315
+ }
316
+ };
317
+ //#endregion
318
+ export { DreamStore as t };