cuelo 0.10.340 → 0.10.341

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 (116) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +53 -53
  3. package/.next/build-manifest.json +2 -2
  4. package/.next/prerender-manifest.json +3 -3
  5. package/.next/required-server-files.js +1 -1
  6. package/.next/required-server-files.json +1 -1
  7. package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  8. package/.next/server/app/_global-error.html +1 -1
  9. package/.next/server/app/_global-error.rsc +1 -1
  10. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  11. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  12. package/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  13. package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  14. package/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  15. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  16. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  17. package/.next/server/app/_not-found.html +1 -1
  18. package/.next/server/app/_not-found.rsc +2 -2
  19. package/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
  20. package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  21. package/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
  22. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  23. package/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  24. package/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  25. package/.next/server/app/api/agent/[id]/account/route.js +1 -1
  26. package/.next/server/app/api/agent/[id]/computer-takeover/route.js +1 -1
  27. package/.next/server/app/api/agent/[id]/events/route.js +1 -1
  28. package/.next/server/app/api/agent/[id]/route.js +1 -1
  29. package/.next/server/app/api/agent/new/route.js +1 -1
  30. package/.next/server/app/api/agent/running/route.js +1 -1
  31. package/.next/server/app/api/gpt6/handles/route.js +1 -1
  32. package/.next/server/app/api/gpt6/reply/route.js +1 -1
  33. package/.next/server/app/api/gpt6/token/route.js +1 -1
  34. package/.next/server/app/api/gpt6/web6-session/route.js +1 -1
  35. package/.next/server/app/api/live/call/[callId]/route.js +1 -1
  36. package/.next/server/app/api/live/draft-secret/route.js +1 -1
  37. package/.next/server/app/api/live/events/route.js +1 -1
  38. package/.next/server/app/api/live/interpret/assist/route.js +1 -1
  39. package/.next/server/app/api/live/interpret/reading/route.js +1 -1
  40. package/.next/server/app/api/live/interpret/route.js +1 -1
  41. package/.next/server/app/api/live/interpret/scan/route.js +1 -1
  42. package/.next/server/app/api/live/interpret/text/route.js +1 -1
  43. package/.next/server/app/api/live/offer/route.js +1 -1
  44. package/.next/server/app/api/live/voices/route.js +1 -1
  45. package/.next/server/app/api/project-trust/route.js +1 -1
  46. package/.next/server/app/api/runs/[runId]/prelude/route.js +1 -1
  47. package/.next/server/app/api/sessions/[id]/auto-name/route.js +1 -1
  48. package/.next/server/app/api/sessions/[id]/context/route.js +1 -1
  49. package/.next/server/app/api/sessions/[id]/route.js +1 -1
  50. package/.next/server/app/api/sessions/[id]/state/route.js +1 -1
  51. package/.next/server/app/api/sessions/route.js +1 -1
  52. package/.next/server/app/api/skills/check/route.js +1 -1
  53. package/.next/server/app/api/skills/install/route.js +1 -1
  54. package/.next/server/app/api/skills/install/route.js.nft.json +1 -1
  55. package/.next/server/app/api/skills/route.js +1 -1
  56. package/.next/server/app/api/skills/update/route.js +1 -1
  57. package/.next/server/app/api/tool-image/route.js +1 -1
  58. package/.next/server/app/api/update-maintenance/route.js +1 -1
  59. package/.next/server/app/api/updates/apply/route.js +2 -2
  60. package/.next/server/app/api/updates/route.js +1 -1
  61. package/.next/server/app/api/upkeep/check/route.js +1 -1
  62. package/.next/server/app/api/upkeep/morning/route.js +1 -1
  63. package/.next/server/app/api/upkeep/nightly/export/route.js +1 -1
  64. package/.next/server/app/api/upkeep/nightly/result/route.js +1 -1
  65. package/.next/server/app/api/upkeep/nightly/route.js +1 -1
  66. package/.next/server/app/api/upkeep/route.js +1 -1
  67. package/.next/server/app/api/worktrees/route.js +1 -1
  68. package/.next/server/app/index.html +1 -1
  69. package/.next/server/app/index.rsc +4 -4
  70. package/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
  71. package/.next/server/app/index.segments/_full.segment.rsc +4 -4
  72. package/.next/server/app/index.segments/_head.segment.rsc +1 -1
  73. package/.next/server/app/index.segments/_index.segment.rsc +2 -2
  74. package/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  75. package/.next/server/app/page.js +2 -2
  76. package/.next/server/app/page_client-reference-manifest.js +1 -1
  77. package/.next/server/app/recover/page_client-reference-manifest.js +1 -1
  78. package/.next/server/app/recover.html +1 -1
  79. package/.next/server/app/recover.rsc +2 -2
  80. package/.next/server/app/recover.segments/_full.segment.rsc +2 -2
  81. package/.next/server/app/recover.segments/_head.segment.rsc +1 -1
  82. package/.next/server/app/recover.segments/_index.segment.rsc +2 -2
  83. package/.next/server/app/recover.segments/_tree.segment.rsc +1 -1
  84. package/.next/server/app/recover.segments/recover/__PAGE__.segment.rsc +1 -1
  85. package/.next/server/app/recover.segments/recover.segment.rsc +1 -1
  86. package/.next/server/app-paths-manifest.json +53 -53
  87. package/.next/server/chunks/2235.js +2 -2
  88. package/.next/server/chunks/5228.js +1 -1
  89. package/.next/server/chunks/8685.js +4 -4
  90. package/.next/server/chunks/9467.js +2 -2
  91. package/.next/server/middleware-build-manifest.js +1 -1
  92. package/.next/server/pages/404.html +1 -1
  93. package/.next/server/pages/500.html +1 -1
  94. package/.next/server/server-reference-manifest.json +1 -1
  95. package/.next/static/chunks/app/{layout-21f6af530e431195.js → layout-6ee169c5af9a4d8e.js} +1 -1
  96. package/.next/static/chunks/app/{page-1b8437381ed0a136.js → page-6b7ae42a86e2c837.js} +2 -2
  97. package/.next/trace +113 -113
  98. package/.next/trace-build +1 -1
  99. package/Tools/CUELO_Setup/files/native-runtime-patch.js +1 -1
  100. package/Tools/OMP_Global_Config/agent/extensions/consult.ts +7 -7
  101. package/Tools/OMP_Global_Config/agent/extensions/cross-review.ts +6 -7
  102. package/Tools/OMP_Global_Config/agent/extensions/lib/cross-review.ts +31 -23
  103. package/Tools/OMP_Global_Config/agent/extensions/lib/finalize-checks.ts +213 -40
  104. package/Tools/OMP_Global_Config/agent/extensions/lib/helper-usage.ts +55 -0
  105. package/Tools/OMP_Global_Config/agent/extensions/lib/interpreter.ts +5 -6
  106. package/Tools/OMP_Global_Config/agent/extensions/lib/preflight-check.ts +44 -12
  107. package/Tools/OMP_Global_Config/agent/extensions/skim.ts +22 -24
  108. package/Tools/OMP_Global_Config/agent/rules/cross-review-procedure.md +3 -1
  109. package/Tools/OMP_Global_Config/agent/rules/subagent.md +1 -1
  110. package/Tools/OMP_Global_Config/agent/tools/git-finalizer/finalizer.ps1 +14 -0
  111. package/Tools/OMP_Global_Config/agent/tools/git-finalizer/index.ts +9 -9
  112. package/Tools/OMP_Global_Config/patches/apply-core-patch.mjs +4 -3
  113. package/bin/ci-local.mjs +4 -1
  114. package/package.json +1 -1
  115. /package/.next/static/{4XtQSNswpweUHnrOc9NYK → T48PfNOAbH9vZjSnZ4tXV}/_buildManifest.js +0 -0
  116. /package/.next/static/{4XtQSNswpweUHnrOc9NYK → T48PfNOAbH9vZjSnZ4tXV}/_ssgManifest.js +0 -0
package/.next/trace-build CHANGED
@@ -1 +1 @@
1
- [{"name":"run-webpack","duration":66459482,"timestamp":306169,"id":14,"parentId":1,"tags":{},"startTime":1795334733344,"traceId":"81e4a3cf54f10e2b"},{"name":"run-typescript","duration":13385863,"timestamp":67122970,"id":11556,"parentId":1,"tags":{},"startTime":1795334800161,"traceId":"81e4a3cf54f10e2b"},{"name":"static-check","duration":2219798,"timestamp":80573736,"id":11559,"parentId":1,"tags":{},"startTime":1795334813612,"traceId":"81e4a3cf54f10e2b"},{"name":"static-generation","duration":6081203,"timestamp":82863118,"id":11777,"parentId":1,"tags":{},"startTime":1795334815901,"traceId":"81e4a3cf54f10e2b"},{"name":"collect-build-traces","duration":13114218,"timestamp":82849139,"id":11774,"parentId":1,"tags":{},"startTime":1795334815887,"traceId":"81e4a3cf54f10e2b"},{"name":"telemetry-flush","duration":42,"timestamp":95966214,"id":11786,"parentId":1,"tags":{},"startTime":1795334829004,"traceId":"81e4a3cf54f10e2b"},{"name":"next-build","duration":95712230,"timestamp":254038,"id":1,"tags":{"buildMode":"default","version":"16.2.12","bundler":"webpack","has-custom-webpack-config":"true","use-build-worker":"false"},"startTime":1795334733292,"traceId":"81e4a3cf54f10e2b"}]
1
+ [{"name":"run-webpack","duration":90087900,"timestamp":416720,"id":14,"parentId":1,"tags":{},"startTime":1795352779828,"traceId":"ebd2889994d839d2"},{"name":"run-typescript","duration":18514994,"timestamp":90912585,"id":11556,"parentId":1,"tags":{},"startTime":1795352870324,"traceId":"ebd2889994d839d2"},{"name":"static-check","duration":2862114,"timestamp":109513695,"id":11559,"parentId":1,"tags":{},"startTime":1795352888925,"traceId":"ebd2889994d839d2"},{"name":"static-generation","duration":5345928,"timestamp":112467530,"id":11777,"parentId":1,"tags":{},"startTime":1795352891879,"traceId":"ebd2889994d839d2"},{"name":"collect-build-traces","duration":17128413,"timestamp":112448291,"id":11774,"parentId":1,"tags":{},"startTime":1795352891860,"traceId":"ebd2889994d839d2"},{"name":"telemetry-flush","duration":78,"timestamp":129584879,"id":11786,"parentId":1,"tags":{},"startTime":1795352908996,"traceId":"ebd2889994d839d2"},{"name":"next-build","duration":129245513,"timestamp":339474,"id":1,"tags":{"buildMode":"default","version":"16.2.12","bundler":"webpack","has-custom-webpack-config":"true","use-build-worker":"false"},"startTime":1795352779751,"traceId":"ebd2889994d839d2"}]
@@ -9,7 +9,7 @@ const MEMORY_RE = /(const phase1Model = await resolveMemoryModel\(\{[^}]*?fallba
9
9
  const MEMORY_DONE = /const phase1Model = await resolveMemoryModel\(\{[^}]*?fallbackRole: "smol"/;
10
10
  const EXPECTED = {
11
11
  name: 'cuelo',
12
- version: '0.10.340',
12
+ version: '0.10.341',
13
13
  distribution: 'cuelo',
14
14
  coreVersion: '19.1.0',
15
15
  };
@@ -1,6 +1,7 @@
1
1
  import type { AssistantMessage } from "@oh-my-pi/pi-ai";
2
- import type { ExtensionAPI, ExtensionContext, SessionManager } from "@oh-my-pi/pi-coding-agent";
2
+ import type { ExtensionAPI, ExtensionContext } from "@oh-my-pi/pi-coding-agent";
3
3
  import { SECRET_CONTENT, toolResult, type HelperResult } from "./skim";
4
+ import { helperAttemptRecorder } from "./lib/helper-usage";
4
5
  // 런타임 패키지는 legacy-pi 확장 loader가 host SDK 경로로 재작성하므로 아래에서 지연 import한다.
5
6
 
6
7
  /**
@@ -79,6 +80,7 @@ export async function consultModel(input: ConsultInput, ctx: ExtensionContext, s
79
80
  }
80
81
  }
81
82
  const sessionId = ctx.sessionManager.getSessionId();
83
+ const usage = helperAttemptRecorder(ctx, { purpose: "consult", model: target });
82
84
  try {
83
85
  if (!(await ctx.modelRegistry.getApiKey(target, sessionId, { signal }))) return reject(`${resolved} 자격을 찾지 못했습니다.`, resolved);
84
86
  const { completeSimple } = await import("@oh-my-pi/pi-ai");
@@ -92,13 +94,11 @@ export async function consultModel(input: ConsultInput, ctx: ExtensionContext, s
92
94
  // 한 번 묻고 끝나는 본문이라 캐시가 다시 읽히지 않는다(cross_review와 같은 이유로 Anthropic 캐시 쓰기를 끈다).
93
95
  ...(target.provider === "anthropic" ? { cacheRetention: "none" as const } : {}),
94
96
  signal: AbortSignal.any([signal, AbortSignal.timeout(TIMEOUT_MS)]),
95
- // 응답이 돌아온 시도는 오류·잘린 답도 청구되므로 판정 전에 장부에 남긴다(skim completeRole과 같다). core의 thinking-loop
96
- // 재시도는 같은 모델을 다시 부르므로 시도마다 남긴다. 저장 실패는 삼키지 않고 오류로 알린다.
97
- onAttempt: (attempt: AssistantMessage) => (ctx.sessionManager as Partial<Pick<SessionManager, "appendModelUsage">>).appendModelUsage?.({
98
- purpose: "consult", api: target.api, provider: target.provider, model: target.id,
99
- usage: attempt.usage, stopReason: attempt.stopReason, errorMessage: attempt.errorMessage,
100
- }, { sessionId, parentId: ctx.sessionManager.getLeafId() }),
97
+ // 응답이 돌아온 시도는 오류·잘린 답도 청구되므로 판정 전에 장부에 남긴다. core의 thinking-loop 재시도는 같은 모델을
98
+ // 다시 부르므로 시도마다 남긴다. 저장 실패는 삼키지 않고 오류로 알린다.
99
+ onAttempt: usage.onAttempt,
101
100
  });
101
+ usage.assertSaved();
102
102
  const answer = response.content.filter((part) => part.type === "text").map((part) => part.text).join("").trim();
103
103
  const respondedName = `${response.provider}/${response.model}`;
104
104
  const done: Report = { ...base, resolved, responded: respondedName !== resolved ? respondedName : undefined, status: "complete", answer: answer || undefined };
@@ -1,6 +1,6 @@
1
1
  import { chmodSync, mkdirSync } from "node:fs";
2
2
  import { isAbsolute, resolve } from "node:path";
3
- import type { ExtensionAPI, ExtensionContext, SessionManager } from "@oh-my-pi/pi-coding-agent";
3
+ import type { ExtensionAPI, ExtensionContext } from "@oh-my-pi/pi-coding-agent";
4
4
  // 런타임 패키지는 legacy-pi 확장 loader가 host SDK 경로로 재작성하므로 아래에서 지연 import한다.
5
5
  import {
6
6
  authorFamily,
@@ -20,6 +20,7 @@ import {
20
20
  type ReviewProgress,
21
21
  type ResolveInput,
22
22
  } from "./lib/cross-review";
23
+ import { helperAttemptRecorder } from "./lib/helper-usage";
23
24
  import { beforeModelAbort } from "./lib/model-routes";
24
25
  import { createRoutingLedger, readCrossReviewRecords } from "./lib/routing-ledger";
25
26
  import { onSessionLifecycle } from "./lib/session-identity";
@@ -51,6 +52,7 @@ export async function completeReviewer(
51
52
  if (!ok) throw new ReviewerCallError(`modelRoles.${slot} resolved to ${name}, which is not a ${lane} model.`, name);
52
53
  const sessionId = ctx.sessionManager.getSessionId();
53
54
  const attempt = AbortSignal.any([signal, AbortSignal.timeout(REVIEW_TIMEOUT_MS)]);
55
+ const usage = helperAttemptRecorder(ctx, { purpose: options.purpose ?? "cross-review", role: slot, model });
54
56
  let response;
55
57
  try {
56
58
  response = await beforeModelAbort(attempt, async () => {
@@ -63,18 +65,15 @@ export async function completeReviewer(
63
65
  apiKey: ctx.modelRegistry.resolver(model, sessionId), sessionId, maxTokens: model.maxTokens ?? undefined,
64
66
  reasoning: "high" as never,
65
67
  ...(model.provider === "anthropic" ? { cacheRetention: "none" as const } : {}),
66
- signal: attempt,
68
+ signal: attempt, onAttempt: usage.onAttempt,
67
69
  });
68
70
  });
69
71
  } catch (error) {
70
72
  if (error instanceof ReviewerCallError) throw error;
71
73
  throw new ReviewerCallError(error instanceof Error ? error.message : String(error), name, undefined, { cause: error });
72
74
  }
73
- // 응답이 돌아온 시도는 오류·빈 답도 청구되므로 먼저 장부에 남긴다(skim completeRole과 같다).
74
- (ctx.sessionManager as Partial<Pick<SessionManager, "appendModelUsage">>).appendModelUsage?.({
75
- purpose: options.purpose ?? "cross-review", role: slot, api: model.api, provider: model.provider, model: model.id,
76
- usage: response.usage, stopReason: response.stopReason, errorMessage: response.errorMessage,
77
- }, { sessionId, parentId: ctx.sessionManager.getLeafId() });
75
+ // 응답이 돌아온 시도는 오류·빈 답도 청구되므로 시도마다 onAttempt가 장부에 남겼다. 저장 실패는 여기서 알린다.
76
+ usage.assertSaved();
78
77
  const text = response.content.filter((part) => part.type === "text").map((part) => part.text).join("").trim();
79
78
  // Preserve partial output for diagnosis without treating it as a usable review.
80
79
  if (response.stopReason !== "stop") throw new ReviewerCallError(response.errorMessage ?? `Model stopped: ${response.stopReason}`, name, text || undefined, { cause: response });
@@ -1121,11 +1121,30 @@ export interface CoveringPass { reviewId: string; inputs: readonly CrossReviewFi
1121
1121
  /** 의존 입력이 일반 파일이 아닌 상태(링크·디렉터리·읽을 수 없음)를 나타내는 값. git blob이 아니므로 어떤 기록과도 같을 수 없다. */
1122
1122
  export const NOT_REGULAR_BLOB = "not-a-regular-file";
1123
1123
 
1124
- /** 통과한 resolve 기록이 덮는 (경로, blob) 쌍과 그 쌍을 덮는 기록들. 통과하지 못한 resolve는 아무것도 덮지 않는다. */
1125
- export function coveredBlobs(records: readonly CrossReviewLedgerRecord[]): Map<string, Map<string, CoveringPass[]>> {
1126
- const covered = new Map<string, Map<string, CoveringPass[]>>();
1124
+ /**
1125
+ * root 저장소에서 통과한 resolve 기록. 저장소는 resolve 기록이 가리키는 라운드 기록의 root로 가르며, 그 라운드 기록이 없거나 root가 없거나 다르면
1126
+ * (한 reviewId가 서로 다른 root로 기록된 경우 포함) 어느 저장소의 통과인지 정할 수 없으므로 포함하지 않는다. 통과하지 못한 resolve도 포함하지 않는다.
1127
+ * 저장소 루트는 git이 돌려준 실제 경로 그대로 비교한다(철자만 다른 root는 같은 저장소로 합치지 않아 덮지 않는다: fail-closed).
1128
+ */
1129
+ function passedResolvesInRoot(records: readonly CrossReviewLedgerRecord[], root: string): CrossReviewResolveRecord[] {
1130
+ const rootOf = new Map<string, string | null>();
1127
1131
  for (const record of records) {
1128
- if (record.type !== "cross-review-resolve" || record.pass !== true) continue;
1132
+ if (record.type !== "cross-review") continue;
1133
+ const next = typeof record.root === "string" && record.root ? pathKey(record.root) : null;
1134
+ rootOf.set(record.reviewId, rootOf.has(record.reviewId) && rootOf.get(record.reviewId) !== next ? null : next);
1135
+ }
1136
+ const wanted = pathKey(root);
1137
+ return records.filter((record): record is CrossReviewResolveRecord => {
1138
+ if (record.type !== "cross-review-resolve" || record.pass !== true) return false;
1139
+ const recordRoot = rootOf.get(record.reviewId);
1140
+ return !!recordRoot && recordRoot === wanted;
1141
+ });
1142
+ }
1143
+
1144
+ /** 같은 저장소(root)에서 통과한 resolve 기록이 덮는 (경로, blob) 쌍과 그 쌍을 덮는 기록들. 다른 저장소의 같은 경로·blob은 덮지 않는다. */
1145
+ export function coveredBlobs(records: readonly CrossReviewLedgerRecord[], root: string): Map<string, Map<string, CoveringPass[]>> {
1146
+ const covered = new Map<string, Map<string, CoveringPass[]>>();
1147
+ for (const record of passedResolvesInRoot(records, root)) {
1129
1148
  const pass: CoveringPass = { reviewId: record.reviewId, inputs: record.inputs ?? [] };
1130
1149
  for (const { path, blob } of record.files) {
1131
1150
  const blobs = covered.get(path) ?? new Map<string, CoveringPass[]>();
@@ -1138,23 +1157,11 @@ export function coveredBlobs(records: readonly CrossReviewLedgerRecord[]): Map<s
1138
1157
 
1139
1158
  /**
1140
1159
  * 같은 저장소에서 통과한 resolve 기록이 덮은 blob → 그 blob을 덮은 (경로, 통과) 목록. 경로가 달라도 같은 바이트면 그 통과가 덮은 것으로 본다
1141
- * (사용자 결정 2026-11-19: 통과 기록이 있는 같은 바이트만, HEAD에 있다는 것만으로는 아님). 저장소는 resolve 기록이 가리키는 라운드 기록의 root로 가르며,
1142
- * 그 라운드 기록이 없거나 root가 다르면 덮지 않는다. 통과하지 못한 resolve는 아무것도 덮지 않는다.
1160
+ * (사용자 결정 2026-11-19: 통과 기록이 있는 같은 바이트만, HEAD에 있다는 것만으로는 아님). 저장소 구분은 passedResolvesInRoot를 따른다.
1143
1161
  */
1144
1162
  export function passedBlobsInRoot(records: readonly CrossReviewLedgerRecord[], root: string): Map<string, { path: string; pass: CoveringPass }[]> {
1145
- // 한 reviewId가 서로 다른 root로 기록돼 있으면 어느 저장소의 통과인지 정할 수 없으므로 아무것도 덮지 않는다.
1146
- const rootOf = new Map<string, string | null>();
1147
- // 저장소 루트는 git이 돌려준 실제 경로 그대로 비교한다(철자만 다른 root는 같은 저장소로 합치지 않아 덮지 않는다: fail-closed).
1148
- for (const record of records) {
1149
- if (record.type !== "cross-review") continue;
1150
- const next = typeof record.root === "string" && record.root ? pathKey(record.root) : null;
1151
- rootOf.set(record.reviewId, rootOf.has(record.reviewId) && rootOf.get(record.reviewId) !== next ? null : next);
1152
- }
1153
1163
  const byBlob = new Map<string, { path: string; pass: CoveringPass }[]>();
1154
- for (const record of records) {
1155
- if (record.type !== "cross-review-resolve" || record.pass !== true) continue;
1156
- const recordRoot = rootOf.get(record.reviewId);
1157
- if (!recordRoot || recordRoot !== pathKey(root)) continue;
1164
+ for (const record of passedResolvesInRoot(records, root)) {
1158
1165
  const pass: CoveringPass = { reviewId: record.reviewId, inputs: record.inputs ?? [] };
1159
1166
  for (const { path, blob } of record.files) byBlob.set(blob, [...(byBlob.get(blob) ?? []), { path, pass }]);
1160
1167
  }
@@ -1175,7 +1182,7 @@ function changedInputs(inputs: readonly CrossReviewFile[], now: ReadonlyMap<stri
1175
1182
  * 입력 없는 통과만 있으면 비어 있다.
1176
1183
  */
1177
1184
  export function boundInputPaths(changes: readonly ChangedFile[], records: readonly CrossReviewLedgerRecord[], anyBlob = false, root?: string): string[] {
1178
- const covered = coveredBlobs(records);
1185
+ const covered = root === undefined ? new Map<string, Map<string, CoveringPass[]>>() : coveredBlobs(records, root);
1179
1186
  const elsewhere = root === undefined ? undefined : passedBlobsInRoot(records, root);
1180
1187
  const paths = new Set<string>();
1181
1188
  for (const change of changes) {
@@ -1270,7 +1277,8 @@ export function decideGate(changes: readonly ChangedFile[], highRisk: Iterable<s
1270
1277
  if (reasons.length > 0) required.push({ path: change.path, blob: change.blob, reasons });
1271
1278
  }
1272
1279
  if (required.length === 0) return { required, uncovered: [] };
1273
- const covered = coveredBlobs(records);
1280
+ // root를 모르면 같은 경로의 통과도 어느 저장소의 것인지 알 수 없으므로 덮지 않는다(fail-closed).
1281
+ const covered = root === undefined ? new Map<string, Map<string, CoveringPass[]>>() : coveredBlobs(records, root);
1274
1282
  // 같은 저장소에서 같은 바이트를 통과시킨 다른 경로의 기록(root를 모르면 쓰지 않는다). 같은 경로의 통과가 우선한다.
1275
1283
  const elsewhere = root === undefined ? new Map<string, { path: string; pass: CoveringPass }[]>() : passedBlobsInRoot(records, root);
1276
1284
  const current = new Map(changes.map((change) => [change.path, change.content] as const));
@@ -1345,11 +1353,11 @@ export async function earlyReviewNotice(cwd: string, absolutePath: string, exec:
1345
1353
  const hits = detectMarkers(change.path, change.changedLines);
1346
1354
  if (hits.length === 0) return undefined;
1347
1355
  const records = readRecords();
1348
- if (coveredBlobs(records).get(change.path)?.get(change.blob)?.length || passedBlobsInRoot(records, resolved.root).get(change.blob)?.length) return undefined;
1356
+ if (coveredBlobs(records, resolved.root).get(change.path)?.get(change.blob)?.length || passedBlobsInRoot(records, resolved.root).get(change.blob)?.length) return undefined;
1349
1357
  const seen = new Set<string>();
1350
1358
  const shown = hits.filter((hit) => !seen.has(hit.trigger) && seen.add(hit.trigger)).slice(0, 3)
1351
1359
  .map((hit) => `${hit.trigger}${hit.line ? ` at ${hit.removed ? "removed " : ""}L${hit.line}` : ""}`);
1352
- return `cross_review early notice: ${change.path} hits a review marker (${shown.join(", ")}), so it will need a passed cross_review before git_finalize. Review it once the file has settled, together with your other changed code files in one call, instead of at publish time (rule://cross-review-procedure). This notice is sent once per file in this session; it is not a gate.`;
1360
+ return `cross_review early notice: ${change.path} hits a review marker (${shown.join(", ")}), so it needs a passed cross_review before you report the work as done, whether or not you commit (git_finalize also requires it). Review it once the file has settled, together with your other changed code files in one call (rule://cross-review-procedure). This notice is sent once per file in this session; it is not a gate.`;
1353
1361
  } catch {
1354
1362
  return undefined;
1355
1363
  }
@@ -1431,7 +1439,7 @@ export async function runGate(options: GateOptions): Promise<GateOutcome> {
1431
1439
  // 옛 내용에만 통과가 있는 파일은 그 옛 내용을 찾아(git 객체, 없으면 검토 사본) 버전 문자열·주석만 바뀌었는지 본다. 찾지 못하면 이어받지 않는다.
1432
1440
  const older = decision.uncovered.filter((file) => file.note?.startsWith("a passed review exists for an older version"));
1433
1441
  if (older.length > 0) {
1434
- const covered = coveredBlobs(records);
1442
+ const covered = coveredBlobs(records, resolved.root);
1435
1443
  const passedContent = new Map<string, string>();
1436
1444
  for (const file of older) {
1437
1445
  for (const blob of covered.get(file.path)?.keys() ?? []) {
@@ -1,11 +1,13 @@
1
1
  import { execFile, spawn } from "node:child_process";
2
2
  import { createHash } from "node:crypto";
3
- import { lstat, mkdir, mkdtemp, open, readFile, readlink, realpath, writeFile } from "node:fs/promises";
3
+ import { lstat, mkdir, mkdtemp, open, readFile, readlink, realpath, rm, writeFile } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
4
5
  import { isAbsolute, join, relative, resolve, sep } from "node:path";
5
6
  import type { CustomToolContext } from "@oh-my-pi/pi-coding-agent";
6
7
  import { Process } from "@oh-my-pi/pi-natives";
7
8
  import { getAgentDir } from "@oh-my-pi/pi-utils";
8
9
  import { spawnExec, type Exec } from "./cross-review";
10
+ import { windowsPathToPosix } from "../../tools/git-finalizer/wsl-git";
9
11
 
10
12
  export const FINALIZE_CHECKS_CONFIG = ".finalize-checks.json";
11
13
  const DEFAULT_TIMEOUT_SECONDS = 1_200;
@@ -15,7 +17,13 @@ const TAIL_BYTES = 12_000;
15
17
 
16
18
  type Check = { name: string; paths: string[]; command: [string, ...string[]]; timeoutSeconds: number };
17
19
  type CheckResult = { name: string; seconds: number; reused: boolean };
18
- export type FinalizeChecksResult = { checks: CheckResult[]; waiver?: string };
20
+ export type FinalizeChecksResult = {
21
+ checks: CheckResult[];
22
+ waiver?: string;
23
+ publicationHead?: string;
24
+ candidateTree?: string;
25
+ candidateContext?: string;
26
+ };
19
27
 
20
28
  type Options = {
21
29
  root: string;
@@ -27,7 +35,7 @@ type Options = {
27
35
  signal?: AbortSignal;
28
36
  git?: string;
29
37
  exec?: Exec;
30
- showDirtyTracked?: boolean;
38
+ publicationCandidate?: boolean;
31
39
  };
32
40
 
33
41
  function objectWithKeys(value: unknown, keys: string[]): value is Record<string, unknown> {
@@ -40,7 +48,7 @@ function validPath(value: unknown): value is string {
40
48
  && value.replace(/\/$/, "").split("/").every((part) => part !== "" && part !== "." && part !== "..");
41
49
  }
42
50
 
43
- async function loadConfig(path: string): Promise<{ source: string; checks: Check[] } | undefined> {
51
+ async function readConfigSource(path: string): Promise<string | undefined> {
44
52
  try {
45
53
  const stat = await lstat(path).catch((error: NodeJS.ErrnoException) => {
46
54
  if (error.code !== "ENOENT") throw error;
@@ -48,13 +56,20 @@ async function loadConfig(path: string): Promise<{ source: string; checks: Check
48
56
  });
49
57
  if (!stat) return undefined;
50
58
  if (!stat.isFile()) throw new Error("expected a regular file");
51
- const source = await readFile(path, "utf8");
59
+ return await readFile(path, "utf8");
60
+ } catch (error) {
61
+ throw new Error(`${path}: ${error instanceof Error ? error.message : String(error)}`);
62
+ }
63
+ }
64
+
65
+ function parseConfig(path: string, source: string): Check[] {
66
+ try {
52
67
  const config: unknown = JSON.parse(source);
53
68
  if (!objectWithKeys(config, ["version", "checks"]) || config.version !== 1 || !Array.isArray(config.checks)) {
54
69
  throw new Error("expected version 1 and a checks array");
55
70
  }
56
71
  const names = new Set<string>();
57
- const checks = config.checks.map((entry: unknown, index: number): Check => {
72
+ return config.checks.map((entry: unknown, index: number): Check => {
58
73
  if (!objectWithKeys(entry, ["name", "paths", "command", "timeoutSeconds"])) throw new Error(`checks[${index}] has unknown fields or is not an object`);
59
74
  const { name, paths, command, timeoutSeconds = DEFAULT_TIMEOUT_SECONDS } = entry;
60
75
  if (typeof name !== "string" || name.trim() !== name || !name || /[\x00-\x1f\x7f]/.test(name) || names.has(name)) {
@@ -70,7 +85,6 @@ async function loadConfig(path: string): Promise<{ source: string; checks: Check
70
85
  names.add(name);
71
86
  return { name, paths, command: command as Check["command"], timeoutSeconds };
72
87
  });
73
- return { source, checks };
74
88
  } catch (error) {
75
89
  throw new Error(`${path}: ${error instanceof Error ? error.message : String(error)}`);
76
90
  }
@@ -122,10 +136,13 @@ async function fileFingerprint(root: string, path: string, checkPaths: readonly
122
136
  }
123
137
 
124
138
  type ReadGit = (args: string[]) => ReturnType<Exec>;
125
- type Snapshot = { hash: string; complete: boolean };
139
+ type Snapshot = { hash: string; sourceHash: string; complete: boolean };
126
140
 
127
141
  /** Hash raw working bytes rather than `git diff`, which can hide changes behind clean filters and index flags. */
128
- async function fingerprint(root: string, files: readonly string[], paths: readonly string[], git: ReadGit, signal?: AbortSignal): Promise<Snapshot | undefined> {
142
+ async function fingerprint(
143
+ root: string, files: readonly string[], paths: readonly string[], git: ReadGit,
144
+ signal?: AbortSignal, publication = false,
145
+ ): Promise<Snapshot | undefined> {
129
146
  try {
130
147
  const [head, tracked, committed, untracked] = await Promise.all([
131
148
  git(["rev-parse", "--verify", "HEAD"]),
@@ -145,15 +162,26 @@ async function fingerprint(root: string, files: readonly string[], paths: readon
145
162
  if (!entry.slice(0, tab).endsWith(" 0") || entry.startsWith("160000 ")) complete = false;
146
163
  inputs.add(entry.slice(tab + 1));
147
164
  }
148
- for (const path of untracked.stdout.split("\0")) if (path && matches(paths, path)) inputs.add(path);
165
+ const outputs = new Set<string>();
166
+ for (const path of untracked.stdout.split("\0")) {
167
+ if (!path || !matches(paths, path) || inputs.has(path)) continue;
168
+ inputs.add(path);
169
+ if (publication) outputs.add(path);
170
+ }
149
171
  const hash = createHash("sha256").update(JSON.stringify([head.stdout.trim(), tracked.stdout, files]));
172
+ const sourceHash = outputs.size ? hash.copy() : undefined;
173
+ const update = (path: string, value: string | null) => {
174
+ const data = JSON.stringify([path, value]);
175
+ hash.update(data);
176
+ if (!outputs.has(path)) sourceHash?.update(data);
177
+ };
150
178
  const ordered: string[] = [];
151
179
  for (const path of [...inputs].sort()) {
152
180
  // The text Git adapter cannot distinguish invalid UTF-8 from U+FFFD. Keep
153
181
  // that part opaque instead of dropping the evidence from all other paths.
154
182
  if (path.includes("\uFFFD")) {
155
183
  complete = false;
156
- hash.update(JSON.stringify([path, null]));
184
+ update(path, null);
157
185
  } else ordered.push(path);
158
186
  }
159
187
  for (let index = 0; index < ordered.length; index += 32) {
@@ -164,14 +192,15 @@ async function fingerprint(root: string, files: readonly string[], paths: readon
164
192
  const entry = entries[offset];
165
193
  if (entry.status === "rejected") {
166
194
  complete = false;
167
- hash.update(JSON.stringify([batch[offset], null]));
195
+ update(batch[offset], null);
168
196
  } else {
169
197
  if (entry.value.opaque) complete = false;
170
- hash.update(JSON.stringify([batch[offset], entry.value.value]));
198
+ update(batch[offset], entry.value.value);
171
199
  }
172
200
  }
173
201
  }
174
- return { hash: hash.digest("hex"), complete };
202
+ const digest = hash.digest("hex");
203
+ return { hash: digest, sourceHash: sourceHash?.digest("hex") ?? digest, complete };
175
204
  } catch {
176
205
  // Cache evidence is optional. Unknown, inaccessible or unsupported inputs require a fresh run.
177
206
  return undefined;
@@ -244,25 +273,131 @@ async function runCommand(check: Check, cwd: string, env: NodeJS.ProcessEnv, fd:
244
273
  }
245
274
  }
246
275
 
247
- async function failureContext(root: string, files: readonly string[], git: ReadGit): Promise<string> {
248
- const result = await git(["--no-optional-locks", "status", "--porcelain=v1", "--no-renames", "--untracked-files=no", "-z"]);
249
- const label = "Dirty tracked paths outside this publication";
250
- const paths = result.stdout.split("\0").filter(Boolean).map((line) => line.slice(3))
251
- .filter((path) => !matches(files, path));
252
- const names = result.code !== 0 ? "could not be determined" : paths.length === 0 ? "none"
253
- : paths.slice(0, 8).map((path) => JSON.stringify(path)).join(", ") + (paths.length > 8 ? ` (+${paths.length - 8} more)` : "");
254
- return `The check ran on the working tree at ${root}. ${label}: ${names}.`;
276
+ async function gitOutput(git: ReadGit, args: string[]): Promise<string> {
277
+ const result = await git(args);
278
+ if (result.code !== 0) throw new Error(`git ${args.join(" ")}: ${(result.stderr || result.stdout).trim() || `exit ${result.code}`}`);
279
+ return result.stdout;
280
+ }
281
+
282
+ async function verifyPublicationConfig(git: ReadGit, head: string, source: string | undefined) {
283
+ const entry = (await gitOutput(git, ["ls-tree", head, "--", FINALIZE_CHECKS_CONFIG])).trim();
284
+ const blob = /^100(?:644|755) blob ([0-9a-f]+)\t/.exec(entry)?.[1];
285
+ const committed = blob === undefined ? undefined : await gitOutput(git, ["cat-file", "blob", blob]);
286
+ // Git can store LF for a CRLF checkout. The actual checkout bytes still bind the receipt.
287
+ if ((entry && !blob) || committed?.replaceAll("\r\n", "\n") !== source?.replaceAll("\r\n", "\n")) {
288
+ throw new Error(`${FINALIZE_CHECKS_CONFIG} differs from the publication candidate. Include it in the publication or restore its committed version.`);
289
+ }
290
+ }
291
+
292
+ async function excludedPaths(git: ReadGit, files: readonly string[], checkIndexFlags = false): Promise<string[]> {
293
+ const [status, flags] = await Promise.all([
294
+ gitOutput(git, ["--no-optional-locks", "-c", "core.fsmonitor=false", "-c", "core.untrackedCache=false",
295
+ "status", "--porcelain=v1", "--no-renames", `--untracked-files=${checkIndexFlags ? "all" : "no"}`, "--ignore-submodules=none", "-z"]),
296
+ checkIndexFlags ? gitOutput(git, ["ls-files", "-v", "-z"]) : "",
297
+ ]);
298
+ const paths = new Set(status.split("\0").filter(Boolean).map((line) => line.slice(3)));
299
+ // Skip-worktree and assume-unchanged paths can hide divergence from status.
300
+ for (const entry of flags.split("\0")) if (/^[Sa-z] /.test(entry)) paths.add(entry.slice(2));
301
+ return [...paths].filter((path) => !matches(files, path));
302
+ }
303
+
304
+ async function withCandidate<T>(
305
+ options: Options, root: string, head: string, files: readonly string[], git: ReadGit,
306
+ run: (cwd: string, git: ReadGit, tree: string, cache: string) => Promise<T>,
307
+ ): Promise<T> {
308
+ const parent = await realpath(tmpdir());
309
+ const fromRepo = relative(root, parent);
310
+ if (!isAbsolute(fromRepo) && fromRepo !== ".." && !fromRepo.startsWith(`..${sep}`)) {
311
+ throw new Error("The temporary directory for publication candidates must be outside the repository.");
312
+ }
313
+ // Repository-local overrides would redirect writes away from the private index.
314
+ for (const name of ["GIT_DIR", "GIT_COMMON_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_OBJECT_DIRECTORY"]) {
315
+ if (process.env[name] !== undefined) throw new Error(`Unset ${name} before constructing the publication candidate.`);
316
+ }
317
+ // Windows Git locates the source; native WSL Git creates a POSIX gitdir for native checks.
318
+ const wslWindowsGit = options.git === "git.exe" && process.platform === "linux";
319
+ const gitDir = (await gitOutput(git, ["rev-parse", "--path-format=absolute", "--git-common-dir"])).trim();
320
+ const commonDir = wslWindowsGit ? windowsPathToPosix(gitDir) : gitDir;
321
+ const temp = await mkdtemp(join(parent, "omp-publication-"));
322
+ const cwd = join(temp, "candidate");
323
+ const exec = options.exec ?? spawnExec(options.signal);
324
+ const command = wslWindowsGit ? "git" : options.git ?? "git";
325
+ const flags = ["-c", `core.hooksPath=${join(temp, "no-hooks")}`, "-c", "core.fsmonitor=false",
326
+ "-c", "core.sparseCheckout=false", "-c", "core.untrackedCache=false"];
327
+ const repoArgs = [`--git-dir=${commonDir}`, ...flags];
328
+ const candidateGit: ReadGit = (args) => exec(command, [...flags, ...args], { cwd });
329
+ const uncancelled = spawnExec();
330
+ const worktreeGit: ReadGit = (args) => uncancelled(command, [...repoArgs, ...args], { cwd: root });
331
+ let registered = false;
332
+ let failure: unknown;
333
+ try {
334
+ // No checkout/hook sees the wrong tree. Git stages from the source under
335
+ // the same repository config, but only in the candidate's private index.
336
+ await gitOutput(worktreeGit, ["worktree", "add", "--detach", "--no-checkout", cwd, head]);
337
+ registered = true;
338
+ options.signal?.throwIfAborted();
339
+ await gitOutput(candidateGit, ["read-tree", head]);
340
+ if (wslWindowsGit) {
341
+ // Stage with the same Git that will publish (including Windows filter/EOL config).
342
+ // Pass its private gitdir directly: the temporary checkout's .git file uses POSIX paths.
343
+ const privateDir = (await gitOutput(candidateGit, ["rev-parse", "--absolute-git-dir"])).trim();
344
+ const paths = await Promise.all([privateDir, root].map(async (path) => {
345
+ const converted = await exec("wslpath", ["-w", path], { cwd: root });
346
+ if (converted.code !== 0 || !converted.stdout.trim()) throw new Error(`Could not convert ${path}: ${converted.stderr || converted.stdout}`);
347
+ return converted.stdout.trim();
348
+ }));
349
+ await gitOutput(git, [`--git-dir=${paths[0]}`, `--work-tree=${paths[1]}`, "-c", "core.fsmonitor=false",
350
+ "-c", "core.sparseCheckout=false", "--literal-pathspecs", "add", "-A", "--", ...files]);
351
+ } else {
352
+ await gitOutput(candidateGit, [`--work-tree=${root}`, "--literal-pathspecs", "add", "-A", "--", ...files]);
353
+ }
354
+ const tree = (await gitOutput(candidateGit, ["write-tree"])).trim();
355
+ await gitOutput(candidateGit, ["checkout-index", "--all", "--index"]);
356
+ return await run(cwd, candidateGit, tree, join(temp, "bun-cache"));
357
+ } catch (error) {
358
+ failure = error;
359
+ throw error;
360
+ } finally {
361
+ // Cleanup is uncancelled. Preserve the check's log/error even if teardown fails.
362
+ let unregisterError: unknown;
363
+ const remove = ["worktree", "remove", "--force", cwd];
364
+ if (registered || await lstat(join(cwd, ".git")).catch(() => undefined)) {
365
+ await gitOutput(worktreeGit, remove).catch((error) => { unregisterError = error; });
366
+ }
367
+ let directoryError: unknown;
368
+ await rm(temp, { recursive: true, force: true, maxRetries: 2 }).catch((error) => { directoryError = error; });
369
+ if (unregisterError && !directoryError) {
370
+ // The filesystem changed: retry only the owned registry entry after removing its tree.
371
+ unregisterError = undefined;
372
+ await gitOutput(worktreeGit, remove).catch((error) => { unregisterError = error; });
373
+ }
374
+ if (unregisterError || directoryError) {
375
+ const details = [unregisterError, directoryError].filter(Boolean).map(String).join("; ");
376
+ throw new Error(`${failure ? `${failure instanceof Error ? failure.message : String(failure)}\n` : ""}Publication candidate cleanup failed (${temp}): ${details}`, { cause: failure });
377
+ }
378
+ }
255
379
  }
256
380
 
257
381
  export async function runFinalizeChecks(options: Options): Promise<FinalizeChecksResult | undefined> {
258
382
  const configPath = join(options.root, FINALIZE_CHECKS_CONFIG);
259
- const config = await loadConfig(configPath);
260
- if (!config?.checks.length) return undefined;
261
- const files = typeof options.files === "function" ? await options.files() : options.files;
262
- const selected = config.checks.filter((check) => files.some((file) => matches(check.paths, file)));
263
- if (!selected.length) return undefined;
383
+ const exec = options.exec ?? spawnExec(options.signal);
384
+ const git: ReadGit = (args) => exec(options.git ?? "git", args, { cwd: options.root });
385
+ const publicationHead = options.publicationCandidate ? (await gitOutput(git, ["rev-parse", "--verify", "HEAD"])).trim() : undefined;
386
+ const source = await readConfigSource(configPath);
387
+ const files = options.files;
388
+ const publicationFiles = publicationHead ? (typeof files === "function" ? await files() : files) : undefined;
389
+ if (publicationHead && publicationFiles && !matches(publicationFiles, FINALIZE_CHECKS_CONFIG)) {
390
+ await verifyPublicationConfig(git, publicationHead, source);
391
+ }
392
+ const noChecks = publicationHead ? { checks: [], publicationHead } : undefined;
393
+ if (source === undefined) return noChecks;
394
+ const checks = parseConfig(configPath, source);
395
+ if (!checks.length) return noChecks;
396
+ const paths = publicationFiles ?? (typeof files === "function" ? await files() : files);
397
+ const selected = checks.filter((check) => paths.some((file) => matches(check.paths, file)));
398
+ if (!selected.length) return noChecks;
264
399
  const waiver = options.waiver?.trim();
265
- if (waiver) return { checks: [], waiver };
400
+ if (waiver) return { checks: [], waiver, publicationHead };
266
401
  const trust = options.sessionManager && Reflect.get(options.sessionManager, Symbol.for("cuelo.finalizeChecksProjectTrust"));
267
402
  const inCuelo = Reflect.get(globalThis, Symbol.for("cuelo.finalizeChecksBrowser")) === true;
268
403
  if ((inCuelo || trust !== undefined) && (typeof trust !== "function" || trust(options.root) !== true)) {
@@ -270,24 +405,57 @@ export async function runFinalizeChecks(options: Options): Promise<FinalizeCheck
270
405
  }
271
406
  await options.authorize?.();
272
407
 
273
- const exec = options.exec ?? spawnExec(options.signal);
274
- const git: ReadGit = (args) => exec(options.git ?? "git", args, { cwd: options.root });
408
+ options.signal?.throwIfAborted();
275
409
  const root = await realpath(options.root);
410
+ if (!publicationHead) return runSelectedChecks(options, root, paths, source, selected, root, git);
411
+ const excluded = await excludedPaths(git, paths, true);
412
+ const context = excluded.length
413
+ ? `The checks ran on an isolated publication candidate. Excluded dirty or index-hidden paths: ${excluded.slice(0, 8).map((path) => JSON.stringify(path)).join(", ")}${excluded.length > 8 ? ` (+${excluded.length - 8} more)` : ""}.`
414
+ : "The checks ran on the publication candidate in place; no dirty paths were excluded.";
415
+ if (!excluded.length) {
416
+ const result = await runSelectedChecks(options, root, paths, source, selected, root, git, context);
417
+ if ((await excludedPaths(git, paths)).length) throw new Error("Paths outside the publication changed during the checks; call the publication tool again.");
418
+ return { ...result, publicationHead };
419
+ }
420
+ return withCandidate(options, root, publicationHead, paths, git, async (cwd, candidateGit, candidateTree, bunCache) => {
421
+ const candidateSource = await readConfigSource(join(cwd, FINALIZE_CHECKS_CONFIG));
422
+ if (candidateSource === undefined || candidateSource.replaceAll("\r\n", "\n") !== source.replaceAll("\r\n", "\n")) {
423
+ throw new Error(`${configPath} differs from the materialized publication candidate. Include it in the publication or restore its committed version.`);
424
+ }
425
+ const result = await runSelectedChecks(options, root, paths, candidateSource, selected, cwd, candidateGit, context, candidateTree, bunCache);
426
+ if (await readFile(configPath, "utf8").catch(() => undefined) !== source) {
427
+ throw new Error(`${configPath} changed during the checks; call the publication tool again.`);
428
+ }
429
+ return { ...result, publicationHead, candidateTree };
430
+ });
431
+ }
432
+
433
+ async function runSelectedChecks(
434
+ options: Options, root: string, files: readonly string[], source: string, selected: readonly Check[],
435
+ cwd: string, git: ReadGit, candidateContext?: string, candidateTree?: string, bunCache?: string,
436
+ ): Promise<FinalizeChecksResult> {
276
437
  const agentDir = getAgentDir();
277
438
  const ledgerDir = resolve(options.ledgerDir ?? (process.env.OMP_FINALIZE_CHECKS_LEDGER || join(agentDir, "finalize-checks-ledger")));
278
439
  const env = { ...process.env };
279
440
  const envKey = createHash("sha256").update(JSON.stringify(Object.entries(env).sort())).digest("hex");
441
+ // No ignored paths are transferred. CUELO installs and prepares SDK/native
442
+ // dependencies in cwd; a private Bun cache cannot hardlink back into the source.
443
+ if (bunCache) {
444
+ env.BUN_INSTALL_CACHE_DIR = bunCache;
445
+ env.PWD = cwd;
446
+ }
280
447
  const results: CheckResult[] = [];
281
448
  const verified: { check: Check; fingerprint: string }[] = [];
282
449
  let ranAfterVerification = false;
283
450
  let logDir: string | undefined;
284
451
  for (const check of selected) {
285
452
  options.signal?.throwIfAborted();
286
- const prior = await fingerprint(root, files, check.paths, git, options.signal);
453
+ const prior = await fingerprint(cwd, files, check.paths, git, options.signal, options.publicationCandidate);
287
454
  options.signal?.throwIfAborted();
288
455
  const slot = createHash("sha256").update(JSON.stringify([root, check.name])).digest("hex");
289
456
  const ledgerFile = join(ledgerDir, slot);
290
- const key = prior?.complete ? createHash("sha256").update(JSON.stringify([2, envKey, check, prior.hash])).digest("hex") : undefined;
457
+ const key = prior?.complete ? createHash("sha256").update(JSON.stringify(options.publicationCandidate
458
+ ? [3, envKey, check, candidateTree ?? null, prior.hash] : [2, envKey, check, prior.hash])).digest("hex") : undefined;
291
459
  if (key && await readFile(ledgerFile, "utf8").catch(() => undefined) === key) {
292
460
  results.push({ name: check.name, seconds: 0, reused: true });
293
461
  verified.push({ check, fingerprint: prior!.hash });
@@ -305,7 +473,7 @@ export async function runFinalizeChecks(options: Options): Promise<FinalizeCheck
305
473
  let failure: string | undefined;
306
474
  let tail = "";
307
475
  try {
308
- failure = await runCommand(check, root, env, handle.fd, options.signal).catch((error: Error) => `could not start: ${error.message}`);
476
+ failure = await runCommand(check, cwd, env, handle.fd, options.signal).catch((error: Error) => `could not start: ${error.message}`);
309
477
  if (failure) {
310
478
  const size = (await handle.stat()).size;
311
479
  const buf = Buffer.allocUnsafe(Math.min(size, TAIL_BYTES));
@@ -317,12 +485,14 @@ export async function runFinalizeChecks(options: Options): Promise<FinalizeCheck
317
485
  }
318
486
  const seconds = Math.round(performance.now() - started) / 1_000;
319
487
  if (failure) {
320
- const context = options.showDirtyTracked ? await failureContext(root, files, git) : undefined;
321
- throw new Error([`${check.name} ${failure} (${seconds}s).`, context, tail && `Last output:\n${tail}`, `Full log: ${log}`, "Fix the failing check, then call the publication tool again."].filter(Boolean).join("\n"));
488
+ throw new Error([`${check.name} ${failure} (${seconds}s).`, candidateContext, tail && `Last output:\n${tail}`, `Full log: ${log}`, "Fix the failing check, then call the publication tool again."].filter(Boolean).join("\n"));
322
489
  }
323
490
  results.push({ name: check.name, seconds, reused: false });
324
491
  ranAfterVerification = verified.length > 0;
325
- const after = await fingerprint(root, files, check.paths, git, options.signal);
492
+ const after = await fingerprint(cwd, files, check.paths, git, options.signal, options.publicationCandidate);
493
+ if (options.publicationCandidate && prior?.sourceHash !== after?.sourceHash) {
494
+ throw new Error(`${check.name}'s publication candidate inputs changed during the check. Call the publication tool again when the inputs are stable.`);
495
+ }
326
496
  if (after) verified.push({ check, fingerprint: after.hash });
327
497
  if (key && after?.complete && after.hash === prior?.hash) {
328
498
  try {
@@ -334,20 +504,23 @@ export async function runFinalizeChecks(options: Options): Promise<FinalizeCheck
334
504
  // Subsequent checks can touch inputs of earlier checks. Do not publish based on a stale pass.
335
505
  if (ranAfterVerification) {
336
506
  for (const entry of verified) {
337
- if ((await fingerprint(root, files, entry.check.paths, git, options.signal))?.hash !== entry.fingerprint) {
507
+ if ((await fingerprint(cwd, files, entry.check.paths, git, options.signal))?.hash !== entry.fingerprint) {
338
508
  throw new Error(`${entry.check.name}'s working-tree inputs changed after it passed. Call the publication tool again when the inputs are stable.`);
339
509
  }
340
510
  }
341
511
  }
342
512
  options.signal?.throwIfAborted();
343
- if (await readFile(configPath, "utf8").catch(() => undefined) !== config.source) {
513
+ const configPath = join(cwd, FINALIZE_CHECKS_CONFIG);
514
+ if (await readFile(configPath, "utf8").catch(() => undefined) !== source) {
344
515
  throw new Error(`${configPath} changed during the checks; call the publication tool again.`);
345
516
  }
346
- return { checks: results };
517
+ return { checks: results, candidateContext };
347
518
  }
348
519
 
349
520
  export function finalizeChecksNote(result?: FinalizeChecksResult): string {
350
521
  if (!result) return "";
351
522
  if (result.waiver) return `Finalize checks waived by explicit user instruction: ${result.waiver}.`;
352
- return `Finalize checks: ${result.checks.map(({ name, seconds, reused }) => reused ? `${name} reused` : `${name} ran (${seconds}s)`).join("; ")}.`;
523
+ if (!result.checks.length) return "";
524
+ return `Finalize checks: ${result.checks.map(({ name, seconds, reused }) => reused ? `${name} reused` : `${name} ran (${seconds}s)`).join("; ")}.`
525
+ + (result.candidateContext ? ` ${result.candidateContext}` : "");
353
526
  }