cuelo 0.10.147 → 0.10.149
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.next/BUILD_ID +1 -1
- package/.next/app-path-routes-manifest.json +49 -49
- package/.next/build-manifest.json +2 -2
- package/.next/prerender-manifest.json +3 -3
- package/.next/required-server-files.js +1 -1
- package/.next/required-server-files.json +1 -1
- package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_global-error.html +1 -1
- package/.next/server/app/_global-error.rsc +1 -1
- package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_not-found.html +1 -1
- package/.next/server/app/_not-found.rsc +2 -2
- package/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
- package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
- package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/api/updates/apply/route.js +2 -2
- package/.next/server/app/api/updates/route.js +1 -1
- package/.next/server/app/api/upkeep/morning/route.js +1 -1
- package/.next/server/app/index.html +1 -1
- package/.next/server/app/index.rsc +4 -4
- package/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
- package/.next/server/app/index.segments/_full.segment.rsc +4 -4
- package/.next/server/app/index.segments/_head.segment.rsc +1 -1
- package/.next/server/app/index.segments/_index.segment.rsc +2 -2
- package/.next/server/app/index.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/page.js +2 -2
- package/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/server/app/recover/page_client-reference-manifest.js +1 -1
- package/.next/server/app/recover.html +1 -1
- package/.next/server/app/recover.rsc +2 -2
- package/.next/server/app/recover.segments/_full.segment.rsc +2 -2
- package/.next/server/app/recover.segments/_head.segment.rsc +1 -1
- package/.next/server/app/recover.segments/_index.segment.rsc +2 -2
- package/.next/server/app/recover.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/recover.segments/recover/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/recover.segments/recover.segment.rsc +1 -1
- package/.next/server/app-paths-manifest.json +49 -49
- package/.next/server/middleware-build-manifest.js +1 -1
- package/.next/server/pages/404.html +1 -1
- package/.next/server/pages/500.html +1 -1
- package/.next/server/server-reference-manifest.json +1 -1
- package/.next/static/chunks/app/{layout-91adba5cefb8102b.js → layout-ed1da61c25e61e2e.js} +1 -1
- package/.next/static/chunks/app/{page-caa39566310ddf02.js → page-61317647fde99232.js} +2 -2
- package/.next/trace +109 -109
- package/.next/trace-build +1 -1
- package/Tools/CUELO_Setup/files/native-runtime-patch.js +1 -1
- package/Tools/OMP_Global_Config/agent/RULES.md +3 -1
- package/Tools/OMP_Global_Config/agent/extensions/lib/cross-review.ts +5 -3
- package/Tools/OMP_Global_Config/agent/extensions/lib/docmap-lint.ts +9 -2
- package/Tools/OMP_Global_Config/agent/extensions/lib/docmap-search.ts +51 -9
- package/Tools/OMP_Global_Config/agent/extensions/lib/draft-coverage.ts +13 -4
- package/Tools/OMP_Global_Config/agent/extensions/lib/slop-gate.ts +7 -2
- package/Tools/OMP_Global_Config/agent/extensions/lib/turn-documents.ts +10 -5
- package/Tools/OMP_Global_Config/agent/prompt-copies/RULES.en.md +2 -2
- package/Tools/OMP_Global_Config/agent/rules/subagent.md +2 -2
- package/Tools/OMP_Global_Config/agent/tools/git-finalizer/index.ts +16 -2
- package/Tools/OMP_Global_Config/agent/tools/git-finalizer/sync-upstream.ts +173 -0
- package/package.json +1 -1
- /package/.next/static/{sq_V_M1IZtVQhSaGqswVO → Q9lFZtMAcVbr4bKTkYJY8}/_buildManifest.js +0 -0
- /package/.next/static/{sq_V_M1IZtVQhSaGqswVO → Q9lFZtMAcVbr4bKTkYJY8}/_ssgManifest.js +0 -0
package/.next/trace-build
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
[{"name":"run-webpack","duration":
|
|
1
|
+
[{"name":"run-webpack","duration":85026271,"timestamp":478936,"id":14,"parentId":1,"tags":{},"startTime":1793853314408,"traceId":"aa95134eaa4bf8e0"},{"name":"run-typescript","duration":19836398,"timestamp":85890609,"id":11202,"parentId":1,"tags":{},"startTime":1793853399820,"traceId":"aa95134eaa4bf8e0"},{"name":"static-check","duration":2909794,"timestamp":105815735,"id":11205,"parentId":1,"tags":{},"startTime":1793853419745,"traceId":"aa95134eaa4bf8e0"},{"name":"static-generation","duration":6716072,"timestamp":108816384,"id":11397,"parentId":1,"tags":{},"startTime":1793853422746,"traceId":"aa95134eaa4bf8e0"},{"name":"collect-build-traces","duration":20106101,"timestamp":108795277,"id":11394,"parentId":1,"tags":{},"startTime":1793853422725,"traceId":"aa95134eaa4bf8e0"},{"name":"telemetry-flush","duration":94,"timestamp":128907573,"id":11406,"parentId":1,"tags":{},"startTime":1793853442837,"traceId":"aa95134eaa4bf8e0"},{"name":"next-build","duration":128506960,"timestamp":400757,"id":1,"tags":{"buildMode":"default","version":"16.2.12","bundler":"webpack","has-custom-webpack-config":"true","use-build-worker":"false"},"startTime":1793853314330,"traceId":"aa95134eaa4bf8e0"}]
|
|
@@ -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.
|
|
12
|
+
version: '0.10.149',
|
|
13
13
|
distribution: 'cuelo',
|
|
14
14
|
coreVersion: '18.16.0',
|
|
15
15
|
};
|
|
@@ -119,7 +119,9 @@
|
|
|
119
119
|
remote·upstream·ancestry·mutex 계약의 정본은 `rule://subagent`의 「프로젝트와 Git 경계」다.
|
|
120
120
|
네 조건을 모두 확인하기 전에는 fallback을 쓰지 않는다.
|
|
121
121
|
- lock·ancestry·경로·non-fast-forward 실패는 raw Git 명령으로 우회하거나 자동 rebase·reset·
|
|
122
|
-
통합하지 않고 상태를 보존해 보고한다.
|
|
122
|
+
통합하지 않고 상태를 보존해 보고한다. 작업 사본이 원격보다 뒤처지기만 했으면(로컬 커밋 없음)
|
|
123
|
+
`git_finalize`가 원격 커밋을 fast-forward로 먼저 받고, 양쪽이 고친 파일은 충돌 없는 3-way 병합일 때만
|
|
124
|
+
합친다(사용자 결정 2026-11-05). 갈라짐·충돌은 그대로 멈춘다. 자기 wt 브랜치(`wt/<주제>` worktree)를 `git_integrate`로
|
|
123
125
|
fetch한 `origin/main`(또는 지정한 대상) 위에 rebase하는 것만 예외다. 충돌이 나면 양쪽 커밋 의도를 보고
|
|
124
126
|
파일을 고친 뒤 `git_integrate` `continue`(포기는 `abort`)로 잇고 raw `git rebase`·`merge`·`pull`로 풀지
|
|
125
127
|
않으며, 검사나 교차검증이 실패하면 멈추고 보고한다. `index.lock`·워크트리 락은 같은 저장소에서 다른
|
|
@@ -123,13 +123,15 @@ const TEST_DIR: Record<string, true> = { test: true, tests: true, __tests__: tru
|
|
|
123
123
|
const GENERATED_FILE = /(?:^|\/)(?:source-integrity\.json|runtime-integrity\.json|package-lock\.json|bun\.lockb?|pnpm-lock\.yaml|yarn\.lock|memories\.jsonl)$/i;
|
|
124
124
|
// 하위 프로젝트의 작업 기록(`Tools/X/doc/history/…`)에 남긴 측정·판정 데이터는 코드가 아니다(사용자 결정, 2026-10-23).
|
|
125
125
|
// 같은 자리의 스크립트는 그대로 코드로 본다. 맨 위 `doc/`는 아래에서 통째로 빠진다.
|
|
126
|
-
const RECORD_DATA_FILE = /(?:^|\/)
|
|
126
|
+
const RECORD_DATA_FILE = /(?:^|\/)docs?\/history\/.+\.(?:jsonl|ndjson|json|csv|tsv|log)$/i;
|
|
127
|
+
// 맨 위 문서 폴더 이름의 대소문자는 프로젝트마다 다르다(`Docs/`).
|
|
128
|
+
const TOP_DOC_DIR = /^docs?$/i;
|
|
127
129
|
|
|
128
130
|
/** 문서·테스트·생성물·작업 기록 데이터는 게이트 대상이 아니다. 나머지는 모두 코드로 본다. */
|
|
129
131
|
export function isCodeFile(path: string): boolean {
|
|
130
132
|
const normalized = path.replaceAll("\\", "/");
|
|
131
133
|
const segments = normalized.split("/");
|
|
132
|
-
if (DOC_FILE.test(normalized) || segments[0]
|
|
134
|
+
if (DOC_FILE.test(normalized) || TOP_DOC_DIR.test(segments[0]!)) return false;
|
|
133
135
|
if (RECORD_DATA_FILE.test(normalized)) return false;
|
|
134
136
|
if (TEST_FILE.test(normalized) || segments.slice(0, -1).some((segment) => Object.hasOwn(TEST_DIR, segment))) return false;
|
|
135
137
|
return !GENERATED_FILE.test(normalized);
|
|
@@ -139,7 +141,7 @@ export function isCodeFile(path: string): boolean {
|
|
|
139
141
|
export function isDocFile(path: string): boolean {
|
|
140
142
|
const normalized = path.replaceAll("\\", "/");
|
|
141
143
|
const segments = normalized.split("/");
|
|
142
|
-
return DOC_FILE.test(normalized) || segments[0]
|
|
144
|
+
return DOC_FILE.test(normalized) || TOP_DOC_DIR.test(segments[0]!) || RECORD_DATA_FILE.test(normalized);
|
|
143
145
|
}
|
|
144
146
|
|
|
145
147
|
// git이 바이너리로 본 이 확장자의 파일은 사람이 읽는 실행 코드가 아니다(이미지·미디어·오피스·글꼴). 실행 파일·라이브러리는 그대로 코드다.
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
*/
|
|
14
14
|
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
15
15
|
import { basename, dirname, join, relative, resolve, sep } from "node:path";
|
|
16
|
-
import { buildDocmapCorpus, docmapTokens, findDocmapMaps, findDocmapProject, type DocmapUnit } from "./docmap-search";
|
|
16
|
+
import { buildDocmapCorpus, docmapTokens, findDocmapMaps, findDocmapProject, findDocRoot, mapCodeRecords, type DocmapUnit } from "./docmap-search";
|
|
17
17
|
|
|
18
18
|
/** docmap-search의 SUPERSEDE_HOPS와 같다. 그보다 긴 사슬은 검색이 끝까지 따라가지 않는다. */
|
|
19
19
|
const MAX_SUPERSEDE_HOPS = 3;
|
|
@@ -181,6 +181,13 @@ export function lintDocmap(cwd: string): DocmapLintReport | undefined {
|
|
|
181
181
|
const base = dirname(file);
|
|
182
182
|
linksBySource.set(file, extractRelativeLinks(readText(file, bad)).map((l) => ({ ...l, target: resolveHref(base, l.href) })));
|
|
183
183
|
}
|
|
184
|
+
// 지도는 코드 표기로 적은 기록 경로도 그 기록을 가리키는 것으로 센다(실제로 있는 기록만이라 끊어진 링크에는 영향이 없다).
|
|
185
|
+
for (const map of maps) {
|
|
186
|
+
const lines = readText(map, bad).split("\n");
|
|
187
|
+
const own = linksBySource.get(map) ?? [];
|
|
188
|
+
lines.forEach((text, index) => { for (const target of mapCodeRecords(text, dirname(map))) own.push({ line: index + 1, href: target, target }); });
|
|
189
|
+
linksBySource.set(map, own);
|
|
190
|
+
}
|
|
184
191
|
|
|
185
192
|
// 1. 지도에 없는 기록
|
|
186
193
|
// 기록 폴더 자체나 그 폴더의 .md 기록 파일로 가는 링크만 센다. evidence/ 파일로만 가는 링크는 기록을 가리키지 않는다.
|
|
@@ -264,7 +271,7 @@ export function lintDocmap(cwd: string): DocmapLintReport | undefined {
|
|
|
264
271
|
const text = readText(f, bad);
|
|
265
272
|
coverText.push([/^#\s+(.+)$/m.exec(text)?.[1] ?? "", headings(text)].join(" "));
|
|
266
273
|
}
|
|
267
|
-
const synthesis = synthesisCandidates(root, records, new Set(coverText.flatMap(docmapTokens)), loadAliases(join(project, "doc", ALIAS_FILE), bad));
|
|
274
|
+
const synthesis = synthesisCandidates(root, records, new Set(coverText.flatMap(docmapTokens)), loadAliases(join(findDocRoot(project) ?? join(project, "doc"), ALIAS_FILE), bad));
|
|
268
275
|
|
|
269
276
|
return {
|
|
270
277
|
root,
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// 하위 지도에만 있던 정답 기록 2건을 놓쳤다. 본문까지 색인하면 무관 질문 점수가 같이 올라 헤더 전용이 낫다
|
|
4
4
|
// (hit@3 37/45 대 31/45). 상시 색인·캐시·LLM 호출은 두지 않는다. 읽기 실패는 호출부가 조용히 버린다.
|
|
5
5
|
import { closeSync, existsSync, openSync, readdirSync, readFileSync, readSync, statSync } from "node:fs";
|
|
6
|
-
import { dirname, join, relative, resolve, sep } from "node:path";
|
|
6
|
+
import { basename, dirname, join, relative, resolve, sep } from "node:path";
|
|
7
7
|
|
|
8
8
|
// 근거: doc/history/2026/10/16-rag-reinvestigation/maker-DocmapRoute.md(처음 보정),
|
|
9
9
|
// doc/history/2026/10/17-rag-fixes/maker-DocmapFloor.md(기록 수·질의 길이에 묶이지 않는 두 조건으로 재보정).
|
|
@@ -177,28 +177,70 @@ function mapLinks(line: string, base: string): string[] {
|
|
|
177
177
|
return out;
|
|
178
178
|
}
|
|
179
179
|
|
|
180
|
-
/**
|
|
180
|
+
/**
|
|
181
|
+
* 지도 줄에 코드 표기로 적은 기록 경로(`` `Docs/history/2026/10/19-x/main.md` ``). 링크 대신 이렇게 기록 목록을 쓰는 프로젝트가
|
|
182
|
+
* 있다(2026-11-05 한세ERP: 37건 전부 이 형식이라 "지도에 없음"으로 잡혔다). 지도 폴더 또는 그 위(프로젝트) 기준으로 풀어
|
|
183
|
+
* 그 지도의 history 안에 실제로 있는 것만 돌려준다. 소스 경로 같은 다른 코드 표기는 기록이 아니므로 버린다.
|
|
184
|
+
*/
|
|
185
|
+
export function mapCodeRecords(line: string, base: string): string[] {
|
|
186
|
+
const history = join(base, "history") + sep;
|
|
187
|
+
const out: string[] = [];
|
|
188
|
+
for (const m of line.matchAll(/`([^`\s]+)`/g)) {
|
|
189
|
+
const hit = [resolve(base, m[1]!), resolve(dirname(base), m[1]!)].find((path) => path.startsWith(history) && existsSync(path));
|
|
190
|
+
if (hit) out.push(hit);
|
|
191
|
+
}
|
|
192
|
+
return out;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const DOC_DIR = /^docs?$/i;
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* 프로젝트 문서 루트(지도 README.md와 history/가 있는 폴더). 정확한 `doc`이 있으면 그것을 쓴다. 없으면 이름이 대소문자를
|
|
199
|
+
* 무시하고 `doc`·`docs`이면서 `history` 폴더를 가진 곳(예: `Docs/`), 그다음 대소문자만 다른 `doc`(예: `Doc/`)을 쓴다.
|
|
200
|
+
* 대소문자를 구분하는 드라이브에서 `Docs/`를 쓰는 프로젝트를 "기록 0건"으로 오판하지 않기 위함이다(2026-11-05).
|
|
201
|
+
* history 없는 `docs/`는 공개 문서일 수 있어 문서 루트로 보지 않는다.
|
|
202
|
+
*/
|
|
203
|
+
export function findDocRoot(project: string): string | undefined {
|
|
204
|
+
if (isDir(join(project, "doc"))) return join(project, "doc");
|
|
205
|
+
let names: string[];
|
|
206
|
+
try { names = readdirSync(project, { withFileTypes: true }).filter((e) => e.isDirectory() && DOC_DIR.test(e.name)).map((e) => e.name).sort(); }
|
|
207
|
+
catch { return undefined; }
|
|
208
|
+
const withHistory = names.find((n) => isDir(join(project, n, "history")));
|
|
209
|
+
if (withHistory) return join(project, withHistory);
|
|
210
|
+
const variant = names.find((n) => n.toLowerCase() === "doc");
|
|
211
|
+
return variant ? join(project, variant) : undefined;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** 루트·프로젝트 지도, 그 지도가 링크한 하위 지도, 루트 아래 1~2단 문서 루트의 README.md(옆에 history가 있는 것). */
|
|
181
215
|
export function findDocmapMaps(root: string, project: string): string[] {
|
|
182
216
|
const maps = new Set<string>();
|
|
183
217
|
const add = (path: string) => { if (isFile(path)) maps.add(path); };
|
|
184
|
-
|
|
185
|
-
|
|
218
|
+
for (const dir of [root, project]) {
|
|
219
|
+
const docRoot = findDocRoot(dir);
|
|
220
|
+
if (docRoot) add(join(docRoot, "README.md"));
|
|
221
|
+
}
|
|
186
222
|
for (const map of [...maps]) {
|
|
187
223
|
for (const line of readFileSync(map, "utf8").split("\n")) {
|
|
188
224
|
for (const target of mapLinks(line, dirname(map))) {
|
|
189
|
-
|
|
225
|
+
// 링크된 하위 지도: 정확한 `doc`은 예전처럼 받고, 다른 표기(`Docs`·`docs`)는 옆에 history가 있을 때만(공개 docs/README.md 제외).
|
|
226
|
+
const folder = dirname(target);
|
|
227
|
+
const isMap = basename(target) === "README.md" && (basename(folder) === "doc" || (DOC_DIR.test(basename(folder)) && isDir(join(folder, "history"))));
|
|
228
|
+
if (isMap && target.startsWith(root + sep)) add(target);
|
|
190
229
|
}
|
|
191
230
|
}
|
|
192
231
|
}
|
|
193
232
|
const skip = (name: string) => name.startsWith(".") || name === "node_modules";
|
|
233
|
+
const addWithHistory = (dir: string) => {
|
|
234
|
+
const docRoot = findDocRoot(dir);
|
|
235
|
+
if (docRoot && isDir(join(docRoot, "history"))) add(join(docRoot, "README.md"));
|
|
236
|
+
};
|
|
194
237
|
for (const a of readdirSync(root, { withFileTypes: true })) {
|
|
195
238
|
if (!a.isDirectory() || skip(a.name)) continue;
|
|
196
239
|
const first = join(root, a.name);
|
|
197
|
-
|
|
240
|
+
addWithHistory(first);
|
|
198
241
|
for (const b of readdirSync(first, { withFileTypes: true })) {
|
|
199
242
|
if (!b.isDirectory() || skip(b.name)) continue;
|
|
200
|
-
|
|
201
|
-
if (isDir(join(second, "doc", "history"))) add(join(second, "doc", "README.md"));
|
|
243
|
+
addWithHistory(join(first, b.name));
|
|
202
244
|
}
|
|
203
245
|
}
|
|
204
246
|
return [...maps];
|
|
@@ -286,7 +328,7 @@ export function buildDocmapCorpus(root: string, maps: readonly string[]): Docmap
|
|
|
286
328
|
for (const map of maps) {
|
|
287
329
|
const base = dirname(map);
|
|
288
330
|
for (const line of readFileSync(map, "utf8").split("\n")) {
|
|
289
|
-
for (const target of mapLinks(line, base)) {
|
|
331
|
+
for (const target of [...mapLinks(line, base), ...mapCodeRecords(line, base)]) {
|
|
290
332
|
let unit = byKey.get(target) ?? byKey.get(dirname(target));
|
|
291
333
|
// 지도 줄이 가리키는 history 밖의 정본 문서(HANDOFF·규칙·운영 문서)도 그 줄의 글로 찾을 수 있게 단위로 둔다.
|
|
292
334
|
if (!unit && isCanonicalTarget(root, target, mapSet)) {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { statSync } from "node:fs";
|
|
1
2
|
import { homedir, tmpdir } from "node:os";
|
|
2
|
-
import { isAbsolute, relative, resolve } from "node:path";
|
|
3
|
+
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
3
4
|
import { htmlText } from "../slop-gate/extract";
|
|
4
5
|
|
|
5
6
|
/**
|
|
@@ -46,9 +47,17 @@ export function inScope(abs: string, cwd: string): boolean {
|
|
|
46
47
|
if (!inside && (p.startsWith(`${slash(tmpdir())}/`) || p.startsWith("/tmp/") || p.startsWith(`${slash(homedir())}/.omp/`))) return false;
|
|
47
48
|
const segments = p.split("/");
|
|
48
49
|
if (RULE_NAME.test(segments.at(-1) ?? "")) return false;
|
|
49
|
-
// slop-gate internalRecord와 같은 기준: `doc` 바로 아래 history 폴더 안, 또는
|
|
50
|
-
|
|
51
|
-
|
|
50
|
+
// slop-gate internalRecord와 같은 기준: 문서 루트(`doc`·`Doc`·`Docs` 등) 바로 아래 history 폴더 안, 또는 지도 README.md.
|
|
51
|
+
// `docs/README.md`는 공개 문서일 수 있어 옆에 history가 있을 때만 지도로 본다.
|
|
52
|
+
const record = segments.some((segment, at) => {
|
|
53
|
+
const name = segment.toLowerCase();
|
|
54
|
+
if (name !== "doc" && name !== "docs") return false;
|
|
55
|
+
if (segments[at + 1] === "history" && segments.length > at + 2) return true;
|
|
56
|
+
if (segments[at + 1] !== "README.md" || segments.length !== at + 2) return false;
|
|
57
|
+
if (name === "doc") return true;
|
|
58
|
+
try { return statSync(join(dirname(abs), "history")).isDirectory(); } catch { return false; }
|
|
59
|
+
});
|
|
60
|
+
if (record) return false;
|
|
52
61
|
return !segments.slice(0, -1).some((segment) => SKIP_SEGMENT[segment]);
|
|
53
62
|
}
|
|
54
63
|
|
|
@@ -49,8 +49,13 @@ const COPY_EXT = /\.(?:json|ts|js|mjs|ya?ml|po)$/i;
|
|
|
49
49
|
|
|
50
50
|
/** 내부 기록만 면제: doc/history/**, doc/README.md. HANDOFF.md는 INTERNAL_NAME이 맡는다. 그 밖의 doc 폴더 파일은 형식으로 분류한다. */
|
|
51
51
|
function internalRecord(segments: readonly string[]): boolean {
|
|
52
|
-
|
|
53
|
-
return
|
|
52
|
+
// 문서 루트 이름의 대소문자는 프로젝트마다 다르다(`Docs/`; docmap-search findDocRoot). `docs`는 공개 문서일 수 있어 history 아래만 기록이다.
|
|
53
|
+
return segments.some((segment, at) => {
|
|
54
|
+
const name = segment.toLowerCase();
|
|
55
|
+
if (name !== "doc" && name !== "docs") return false;
|
|
56
|
+
if (segments[at + 1] === "history" && segments.length > at + 2) return true;
|
|
57
|
+
return name === "doc" && segments[at + 1] === "README.md" && segments.length === at + 2;
|
|
58
|
+
});
|
|
54
59
|
}
|
|
55
60
|
|
|
56
61
|
/** 저장소 밖 절대 경로 중 보지 않는 곳: 임시·에이전트 내부·캐시·생성물·의존성. 이유를 돌려주고, 대상이면 undefined. */
|
|
@@ -2,12 +2,15 @@ import { existsSync, realpathSync, statSync } from "node:fs";
|
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
3
|
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { findDocRoot } from "./docmap-search";
|
|
5
6
|
|
|
6
7
|
// Only explicit filesystem tool contracts are observed; never inspect shell/eval code or result prose.
|
|
7
8
|
type Result = { toolName: string; input?: unknown; details?: unknown; isError?: boolean };
|
|
8
9
|
const SOURCE = /\.(?:[cm]?[jt]sx?|vue|svelte|astro|html?|css|scss|sass|less|jsonc?|ya?ml|toml|ini|cfg|conf|config|xml|resx|vb|frm|bas|cs|fs|csproj|vbproj|slnx?|props|targets|c|cc|cpp|cxx|h|hpp|rs|go|py|rb|php|java|kt|kts|swift|sh|bash|ps1|bat|cmd|sql|gradle|cmake|proto)$/i;
|
|
9
10
|
const SOURCE_NAME = /^(?:Dockerfile|Makefile|CMakeLists\.txt|\.gitignore|\.gitattributes|\.editorconfig|\.npmrc|\.env(?:\..+)?)$/i;
|
|
10
11
|
const EXCLUDED: Record<string, true> = { ".git": true, node_modules: true, dist: true, build: true, coverage: true, ".next": true, doc: true, docs: true, evidence: true };
|
|
12
|
+
// 문서 루트 이름은 프로젝트마다 대소문자가 다르다(`Docs/`). findDocRoot와 같은 기준.
|
|
13
|
+
const RECORD_PATH = /(?:^|\/)(?:HANDOFF\.md|docs?\/README\.md|docs?\/history\/\d{4}\/\d{2}\/\d{2}-[^/]+\/(?:main|maker-[^/]+)\.md)$/i;
|
|
11
14
|
const URI = /^[A-Za-z][A-Za-z0-9+.-]+:\//;
|
|
12
15
|
const PREFIXED_URI = /[\\/][A-Za-z][A-Za-z0-9+.-]+:\/\//;
|
|
13
16
|
const record = (value: unknown): Record<string, unknown> => value !== null && typeof value === "object" ? value as Record<string, unknown> : {};
|
|
@@ -90,7 +93,7 @@ export function createTurnDocuments() {
|
|
|
90
93
|
try { base = realpathSync(cwd); } catch { return; }
|
|
91
94
|
const path = localPath(savedPath, base, false);
|
|
92
95
|
if (path && within(base, path) && isFile(path)
|
|
93
|
-
&&
|
|
96
|
+
&& RECORD_PATH.test(path.split(sep).join("/"))) written.add(path);
|
|
94
97
|
return;
|
|
95
98
|
}
|
|
96
99
|
if (!cwd || event.isError || !["read", "write", "edit"].includes(event.toolName)) return;
|
|
@@ -106,7 +109,7 @@ export function createTurnDocuments() {
|
|
|
106
109
|
written.add(path);
|
|
107
110
|
if (!within(base, path)) continue;
|
|
108
111
|
const parts = relative(base, path).split(sep);
|
|
109
|
-
if (parts.some((part) => EXCLUDED[part])) continue;
|
|
112
|
+
if (parts.some((part) => EXCLUDED[part.toLowerCase()])) continue;
|
|
110
113
|
if (SOURCE.test(path) || SOURCE_NAME.test(basename(path))) sources.add(path);
|
|
111
114
|
}
|
|
112
115
|
},
|
|
@@ -126,13 +129,15 @@ export function createTurnDocuments() {
|
|
|
126
129
|
}
|
|
127
130
|
const notices: string[] = [];
|
|
128
131
|
for (const [project, uncertain] of projects) {
|
|
129
|
-
const
|
|
132
|
+
const docRoot = findDocRoot(project) ?? join(project, "doc");
|
|
133
|
+
const docName = relative(project, docRoot).split(sep).join("/");
|
|
134
|
+
const handoff = join(project, "HANDOFF.md"), map = join(docRoot, "README.md"), history = join(docRoot, "history");
|
|
130
135
|
const absent: string[] = [], unseen: string[] = [];
|
|
131
|
-
for (const [path, name] of [[handoff, "HANDOFF.md"], [map,
|
|
136
|
+
for (const [path, name] of [[handoff, "HANDOFF.md"], [map, `${docName}/README.md`]] as const) {
|
|
132
137
|
if (!isFile(path)) absent.push(name);
|
|
133
138
|
else if (!reviewed.has(path) && !written.has(path)) unseen.push(`${name} 읽기/쓰기`);
|
|
134
139
|
}
|
|
135
|
-
if (!isDir(history)) absent.push(
|
|
140
|
+
if (!isDir(history)) absent.push(`${docName}/history 작업 기록`);
|
|
136
141
|
else if (![...written].some((path) => within(history, path) && /^\d{4}\/\d{2}\/\d{2}-[^/]+\/(?:main|maker-[^/]+)\.md$/.test(relative(history, path).split(sep).join("/")) && isFile(path))) unseen.push("작업 기록 쓰기");
|
|
137
142
|
if (!absent.length && !unseen.length) continue;
|
|
138
143
|
const label = relative(base, project).split(sep).join("/") || ".";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
<!-- source-fingerprint:
|
|
1
|
+
<!-- source-fingerprint: 25bfb62fec35dbec -->
|
|
2
2
|
# Global Rules
|
|
3
3
|
|
|
4
4
|
(Model-facing English copy of the Korean source `RULES.md`.)
|
|
@@ -52,4 +52,4 @@
|
|
|
52
52
|
- When `git_finalize` will commit code files its gate selects (high-risk declarations, trigger markers, the deterministic 10% sample; the `git_finalize` tool description is the source of truth for targets and exclusions), first get a `cross_review` from the other model family and close every finding with evidence (`rule://cross-review-procedure`). For other ordinary changes Main decides from the `maker_route` review-necessity advice, and that advice cannot waive a gate requirement. A review is advisory evidence, never a PASS. Never waive this gate without an explicit user instruction. The source of truth is `harness-policy.json` `mainLane.workerReview.crossFamilyReview`. **Reviewer models come only from the user's cross-review route (user correction, 2026-10-26).** Any model used to review, verify, or decide a gate for code, documents, or deliverables is read from the `config.yml` `modelRoles` slots `crossReviewOpenAI` and `crossReviewAnthropic` (same family rule as `cross_review`). The advisory slot was removed by user decision on 2026-10-29; only slop checks use the dedicated slot `slopReviewOpenAI` (Luna alone). Never name another model (for example Sonnet) in a new review feature or a Maker brief for cost or speed, and never call a result from a model outside that route a cross-review or a passed review. To change the route, ask the user first (2026-10-26: Main put Sonnet into the slop-gate brief as the reviewer and the user corrected it).
|
|
53
53
|
- `git_finalize` accepts only relative canonical targets and finalizes one repository per call. The source of truth for path resolution and rejected targets, allowing a separate Git repository outside cwd, Main's four-condition raw Git fallback and its pre-checks, and the remote/upstream/ancestry/mutex contract is `rule://subagent` 「프로젝트와 Git 경계」. Do not use the fallback before confirming all four conditions.
|
|
54
54
|
<!-- /main-only -->
|
|
55
|
-
- Do not work around lock, ancestry, path, or non-fast-forward failures with raw Git commands, and do not auto rebase/reset/integrate; preserve the state and report. The only exception is rebasing your own wt branch (`wt/<topic>` worktree) onto the fetched `origin/main` (or the named target) with `git_integrate`. On a conflict, read both sides' commit intent, fix the files, and resume with `git_integrate` `continue` (or give up with `abort`); never resolve it with raw `git rebase`/`merge`/`pull`, and stop and report when the checks or cross-review fail. Another agent may be working in the same repository, so never delete `index.lock` or worktree locks; retry once after a short wait, and stop if it still fails.
|
|
55
|
+
- Do not work around lock, ancestry, path, or non-fast-forward failures with raw Git commands, and do not auto rebase/reset/integrate; preserve the state and report. When the working copy is only behind the remote (no local commits), `git_finalize` itself fast-forwards to the remote commits first and merges files both sides changed only when the 3-way merge is conflict-free (user decision, 2026-11-05); a diverged branch or a conflict still stops. The only other exception is rebasing your own wt branch (`wt/<topic>` worktree) onto the fetched `origin/main` (or the named target) with `git_integrate`. On a conflict, read both sides' commit intent, fix the files, and resume with `git_integrate` `continue` (or give up with `abort`); never resolve it with raw `git rebase`/`merge`/`pull`, and stop and report when the checks or cross-review fail. Another agent may be working in the same repository, so never delete `index.lock` or worktree locks; retry once after a short wait, and stop if it still fails.
|
|
@@ -834,8 +834,8 @@ evidence locator·이유를 남긴다. `held`는 같은 identity와 보류 이
|
|
|
834
834
|
같은 이름의 `refs/heads/<branch>`다.
|
|
835
835
|
- 존재 확인은 read-only exact-ref 조회로 부재와 인증·네트워크 오류를 구분한다. 없는 remote branch는
|
|
836
836
|
첫 ordinary push가 만들고 tracking은 push 성공 뒤 설정한다. 있는 branch는 fetch 후 upstream이
|
|
837
|
-
캡처한 로컬 HEAD의 ancestor인지 확인해 같거나 앞선 상태만
|
|
838
|
-
staging 전에 거부한다. commit parent는 commit 직전 HEAD와 같아야 하고 push는 생성 SHA의
|
|
837
|
+
캡처한 로컬 HEAD의 ancestor인지 확인해 같거나 앞선 상태만 허용한다. 뒤처지기만 한 상태는 게이트 전에
|
|
838
|
+
fast-forward로 받고(양쪽 수정 파일은 충돌 없는 3-way만), 갈라졌거나 충돌하면 staging 전에 거부한다. commit parent는 commit 직전 HEAD와 같아야 하고 push는 생성 SHA의
|
|
839
839
|
non-force push로 remote ref까지 확인한다.
|
|
840
840
|
- lock·ancestry·경로·non-fast-forward 실패는 우회하거나 자동 rebase·reset하지 않고 상태를 보존해
|
|
841
841
|
보고한다. 자기 wt 브랜치를 `git_integrate`로 대상 위에 rebase하는 것만 예외다(아래). `index.lock`이나
|
|
@@ -7,6 +7,7 @@ import { fileURLToPath } from "node:url";
|
|
|
7
7
|
import { currentBlobs, type Exec, ledgerPath, resolveRepoTargets, runGate, spawnExec } from "../../extensions/lib/cross-review";
|
|
8
8
|
import { mergeGateBlobs, runSlopGate, slopLedgerPath } from "../../extensions/lib/slop-gate";
|
|
9
9
|
import { integrateTool } from "./integrate";
|
|
10
|
+
import { syncBehindUpstream } from "./sync-upstream";
|
|
10
11
|
import { hasPosixGitdirWorktree, isWindowsDrivePath, selectGitExecutor, usesWindowsDriveRepo } from "./wsl-git";
|
|
11
12
|
|
|
12
13
|
export { hasPosixGitdirWorktree };
|
|
@@ -295,7 +296,7 @@ export const finalizeTool = (pi: ToolApi): CustomTool<any, any> => ({
|
|
|
295
296
|
label: "Git Finalize",
|
|
296
297
|
loadMode: "essential",
|
|
297
298
|
description:
|
|
298
|
-
"Atomically finalize relative exact files in one repository. Resolve every target from its nearest existing parent. Treat matching git common-dir values as the same repository: restrict those targets to paths inside cwd or an exact direct child file of the cwd repository root, while allowing one distinct repository; reject mixed repositories before staging. Serialize by repository/upstream, verify exact paths and ancestry, commit, then push the created SHA. If an earlier run committed but its push failed, call again with the same files: unchanged files found in unpushed upstream..HEAD commits are accepted and HEAD is pushed without a new commit. Cross-family review gate (stage `cross-review`): when there is something new to commit, a code file needs a passed cross_review resolve for its exact current content if it is listed in crossReviewHighRisk (paths from files), a high-risk marker hits its changed lines, or the deterministic 10% sample selects the commit (then at most the 5 code files with the most changed lines, project/style/designer files excluded); otherwise the call is refused with the files, the reason and the next step. Docs, tests, generated files, binary media/office/font assets, TS/JS edits the TypeScript parser proves comment-only and edits that only change version strings (against HEAD or the last passed content) are not targets. crossReviewWaiver is allowed only on the user's explicit instruction and is recorded. AI-slop gate (stage `slop-gate`, after cross-review): every visible artifact among the files that has something new to commit (slides, html, pptx/docx/xlsx/pdf/hwpx, report csv, UI copy packs, manuals, plus markdown declared by a .slop-gate.json visible glob; no publication declaration is needed, and .publicignore does not exempt anything) needs a slop_check pass for its exact current content (sha256); otherwise the call is refused with the files and the next step. Markdown not declared that way (README, CHANGELOG, docs, doc maps), source code, comments, logs, tests, fixtures, generated files and internal records (rules, prompts, skills, HANDOFF.md, doc/history, doc/README.md) are not slop targets. slopGateWaiver is allowed only on the user's explicit instruction and is recorded. Main only.",
|
|
299
|
+
"Atomically finalize relative exact files in one repository. Resolve every target from its nearest existing parent. Treat matching git common-dir values as the same repository: restrict those targets to paths inside cwd or an exact direct child file of the cwd repository root, while allowing one distinct repository; reject mixed repositories before staging. Serialize by repository/upstream, verify exact paths and ancestry, commit, then push the created SHA. When the working copy is only behind the upstream (no local commits, nothing staged), it first fast-forwards to the remote commits before the gates (stage `upstream-sync`); uncommitted edits stay, and a file both sides changed is merged only when git's 3-way merge is conflict-free. A diverged branch, a conflict, or an incoming change to a locally new/deleted file leaves the working copy untouched and the call stops as before. If an earlier run committed but its push failed, call again with the same files: unchanged files found in unpushed upstream..HEAD commits are accepted and HEAD is pushed without a new commit. Cross-family review gate (stage `cross-review`): when there is something new to commit, a code file needs a passed cross_review resolve for its exact current content if it is listed in crossReviewHighRisk (paths from files), a high-risk marker hits its changed lines, or the deterministic 10% sample selects the commit (then at most the 5 code files with the most changed lines, project/style/designer files excluded); otherwise the call is refused with the files, the reason and the next step. Docs, tests, generated files, binary media/office/font assets, TS/JS edits the TypeScript parser proves comment-only and edits that only change version strings (against HEAD or the last passed content) are not targets. crossReviewWaiver is allowed only on the user's explicit instruction and is recorded. AI-slop gate (stage `slop-gate`, after cross-review): every visible artifact among the files that has something new to commit (slides, html, pptx/docx/xlsx/pdf/hwpx, report csv, UI copy packs, manuals, plus markdown declared by a .slop-gate.json visible glob; no publication declaration is needed, and .publicignore does not exempt anything) needs a slop_check pass for its exact current content (sha256); otherwise the call is refused with the files and the next step. Markdown not declared that way (README, CHANGELOG, docs, doc maps), source code, comments, logs, tests, fixtures, generated files and internal records (rules, prompts, skills, HANDOFF.md, doc/history, doc/README.md) are not slop targets. slopGateWaiver is allowed only on the user's explicit instruction and is recorded. Main only.",
|
|
299
300
|
parameters: pi.zod.object({
|
|
300
301
|
files: pi.zod.array(pi.zod.string()),
|
|
301
302
|
message: pi.zod.string(),
|
|
@@ -311,6 +312,18 @@ export const finalizeTool = (pi: ToolApi): CustomTool<any, any> => ({
|
|
|
311
312
|
if (!message) throw new Error("git_finalize requires a non-empty commit message.");
|
|
312
313
|
|
|
313
314
|
const exec: Exec = (command, args, options) => pi.exec(command, args, { ...options, signal });
|
|
315
|
+
// 뒤처지기만 한 작업 사본은 원격 커밋을 먼저 받는다(사용자 결정 2026-11-05). 게이트가 받은 뒤의 내용(합친 파일 포함)을 보도록 맨 앞에서 한다.
|
|
316
|
+
let upstreamNote = "";
|
|
317
|
+
const repo = await resolveRepoTargets(pi.cwd, requested, exec).catch(() => undefined);
|
|
318
|
+
if (repo && !("failure" in repo)) {
|
|
319
|
+
try {
|
|
320
|
+
// 작업 사본을 바꾸는 단계는 취소 신호 없이 끝까지 돌려 반쯤 바뀐 채 남지 않게 한다(조회·fetch만 취소된다).
|
|
321
|
+
upstreamNote = (await syncBehindUpstream(spawnExec(signal), (await selectGitExecutor(repo.root)).command, repo.root, spawnExec())).note ?? "";
|
|
322
|
+
} catch (error) {
|
|
323
|
+
throw new Error(`git_finalize failed at upstream-sync: ${error instanceof Error ? error.message : String(error)}`);
|
|
324
|
+
}
|
|
325
|
+
if (upstreamNote) onUpdate?.({ content: [{ type: "text", text: upstreamNote }], details: { phase: "upstream-sync" } });
|
|
326
|
+
}
|
|
314
327
|
await checkSourceManifest(pi.cwd, requested, exec);
|
|
315
328
|
// 계열 교차검증 게이트: 새로 커밋할 코드가 trigger·표본에 걸리면 통과한 검토 기록이 있어야 한다.
|
|
316
329
|
// 기억 transport(memory.file)는 생성물이라 요청 파일에만 적용한다.
|
|
@@ -370,7 +383,7 @@ export const finalizeTool = (pi: ToolApi): CustomTool<any, any> => ({
|
|
|
370
383
|
const parsed = parseResult(result.stdout);
|
|
371
384
|
if (result.code !== 0 || !parsed?.ok) {
|
|
372
385
|
const detail = parsed?.error || result.stderr.trim() || result.stdout.trim() || `exit ${result.code}`;
|
|
373
|
-
throw new Error(`git_finalize failed${parsed?.stage ? ` at ${parsed.stage}` : ""}: ${detail}`);
|
|
386
|
+
throw new Error(`git_finalize failed${parsed?.stage ? ` at ${parsed.stage}` : ""}: ${detail}${upstreamNote ? ` (${upstreamNote})` : ""}`);
|
|
374
387
|
}
|
|
375
388
|
// 게시 뒤 Windows 대응 사본 반영(deploy-ops)에 붙여 넣을 명령: 손으로 40자 리비전을 옮기던 일을 덜어 준다(10-25~27 54회).
|
|
376
389
|
// 대응 사본은 PC·저장소마다 달라 정본이 없으므로 대상만 자리표시로 두고, 짝이 있는지는 Main이 운영 문서로 정한다.
|
|
@@ -394,6 +407,7 @@ export const finalizeTool = (pi: ToolApi): CustomTool<any, any> => ({
|
|
|
394
407
|
{
|
|
395
408
|
type: "text",
|
|
396
409
|
text: `Committed and pushed ${parsed.commitSha} to ${parsed.remote} ${parsed.upstreamRef}.`
|
|
410
|
+
+ (upstreamNote ? ` ${upstreamNote}` : "")
|
|
397
411
|
+ (parsed.resumedPush ? " 이미 커밋돼 있던 미전송 커밋을 함께 다시 보냈다." : "")
|
|
398
412
|
+ (memory.file ? ` 기억 transport(${memory.file})를 함께 커밋했다.` : "")
|
|
399
413
|
+ (memory.note ? ` ${memory.note}` : "")
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import type { Exec } from "../../extensions/lib/cross-review";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* git_finalize 앞단: 작업 사본이 원격보다 "뒤처지기만" 했을 때(로컬 HEAD가 원격의 조상, 로컬 커밋 없음) 원격 커밋을
|
|
8
|
+
* fast-forward로 받는다. 사용자 결정(2026-11-05): 다른 세션이 올린 커밋 때문에 커밋이 멈추고 사람에게 "받아도 되냐"고
|
|
9
|
+
* 묻던 일을 없앤다. 역사를 다시 쓰지 않으므로 rebase·HEAD reset·merge commit은 하지 않는다.
|
|
10
|
+
*
|
|
11
|
+
* - 갈라진 경우, stage된 변경, 원격 브랜치 없음, 분리된 HEAD는 아무것도 바꾸지 않고 안내만 돌려준다. 그 뒤 판정(멈춤)은
|
|
12
|
+
* finalizer.ps1이 그대로 한다. index는 읽기만 한다(`--no-optional-locks`).
|
|
13
|
+
* - 원격 커밋이 고친 파일과 로컬의 커밋 안 한 수정이 겹치면 작업 트리 바이트 공간에서 3-way 병합한다: 로컬은 원래 바이트
|
|
14
|
+
* (`hash-object --no-filters`, 이것이 객체 백업이다), 기준판·원격판은 이 작업 사본에 놓일 바이트(`cat-file --filters`).
|
|
15
|
+
* `merge-file --object-id`가 충돌 없이 끝날 때만 진행하므로 합친 결과도 줄바꿈·인코딩 바이트가 그대로다.
|
|
16
|
+
* 새 파일·삭제가 겹치면 건드리지 않고, 무시 파일은 `--no-overwrite-ignore`로 git이 덮어쓰기를 거절한다.
|
|
17
|
+
* - 작업 사본 쓰기는 모두 Node가 바이트로 하고, 받은 뒤에는 파일 바이트로 판정한다: 원격판이면 병합 결과, 기준판이면
|
|
18
|
+
* (받지 못했다) 원래 바이트, 그 밖이면 누가 고친 것이라 건드리지 않는다. git 조회·파일 쓰기가 실패해도 파일마다 따로
|
|
19
|
+
* 되돌리며, 깨끗하게 끝나지 않으면(받는 도중 다른 쪽이 새로 저장한 파일 포함) 원래 바이트를 복사한 임시 폴더와 백업 객체를 알린다.
|
|
20
|
+
* - `commitExec`는 작업 사본을 바꾸는 fast-forward에 쓴다. 호출부가 취소 신호 없는 실행기를 주면 취소가 그 단계를 반쯤
|
|
21
|
+
* 끊지 않는다(조회·fetch는 `exec`로 취소된다). `readBytes`는 바이트 그대로의 출력이 필요한 git 호출이다.
|
|
22
|
+
*/
|
|
23
|
+
export interface UpstreamSync {
|
|
24
|
+
/** 받은 원격 커밋 수. 0이면 아무것도 바꾸지 않았다. */
|
|
25
|
+
pulled: number;
|
|
26
|
+
/** 3-way로 합친 로컬 수정 파일(저장소 상대 경로). */
|
|
27
|
+
merged: string[];
|
|
28
|
+
/** 사용자·Main에게 보일 한 줄 안내. 받지 않은 이유도 여기에 담는다. */
|
|
29
|
+
note?: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export type ReadBytes = (git: string, args: string[], cwd: string) => Promise<Buffer>;
|
|
33
|
+
|
|
34
|
+
interface Plan { path: string; abs: string; raw: Buffer; rawOid: string; base: Buffer; theirs: Buffer; merged: Buffer }
|
|
35
|
+
|
|
36
|
+
const SHA = /^[0-9a-f]{40,64}$/;
|
|
37
|
+
const message = (error: unknown) => error instanceof Error ? error.message : String(error);
|
|
38
|
+
|
|
39
|
+
/** 문자열로 풀지 않고 stdout 바이트를 그대로 받는다(cp949·CRLF 보존). */
|
|
40
|
+
export const spawnBytes: ReadBytes = async (git, args, cwd) => {
|
|
41
|
+
const child = Bun.spawn([git, ...args], { cwd, stdout: "pipe", stderr: "pipe", stdin: "ignore" });
|
|
42
|
+
const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).arrayBuffer(), new Response(child.stderr).text(), child.exited]);
|
|
43
|
+
if (code !== 0) throw new Error(`git ${args.join(" ")} failed: ${stderr.trim()}`);
|
|
44
|
+
return Buffer.from(stdout);
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
export async function syncBehindUpstream(exec: Exec, git: string, root: string, commitExec: Exec = exec, readBytes: ReadBytes = spawnBytes): Promise<UpstreamSync> {
|
|
48
|
+
const run = (args: string[], stdin?: Buffer) => exec(git, args, { cwd: root, ...(stdin ? { stdin } : {}) });
|
|
49
|
+
const out = async (args: string[], stdin?: Buffer) => {
|
|
50
|
+
const result = await run(args, stdin);
|
|
51
|
+
if (result.code !== 0) throw new Error(`git ${args.join(" ")} failed: ${(result.stderr || result.stdout).trim()}`);
|
|
52
|
+
return result.stdout.trim();
|
|
53
|
+
};
|
|
54
|
+
const skip = (note: string): UpstreamSync => ({ pulled: 0, merged: [], note });
|
|
55
|
+
|
|
56
|
+
// finalizer.ps1의 remote·upstream 선택과 같은 기준.
|
|
57
|
+
const branch = (await run(["rev-parse", "--abbrev-ref", "HEAD"])).stdout.trim();
|
|
58
|
+
if (!branch || branch === "HEAD") return skip("분리된 HEAD라 원격 커밋을 확인하지 않았다.");
|
|
59
|
+
const config = async (key: string) => { const r = await run(["config", "--get", key]); return r.code === 0 ? r.stdout.trim() : ""; };
|
|
60
|
+
const remotes = (await run(["remote"])).stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
|
|
61
|
+
const configured = await config(`branch.${branch}.remote`);
|
|
62
|
+
const remote = configured && configured !== "." ? configured : remotes.includes("origin") ? "origin" : remotes.length === 1 ? remotes[0] : "";
|
|
63
|
+
if (!remote || !remotes.includes(remote)) return skip("push할 원격을 정하지 못해 원격 커밋을 확인하지 않았다.");
|
|
64
|
+
const upstreamRef = (await config(`branch.${branch}.merge`)) || `refs/heads/${branch}`;
|
|
65
|
+
if (!upstreamRef.startsWith("refs/heads/")) return skip(`지원하지 않는 upstream(${upstreamRef})이라 원격 커밋을 확인하지 않았다.`);
|
|
66
|
+
if ((await run(["ls-remote", "--exit-code", "--refs", remote, upstreamRef])).code !== 0) {
|
|
67
|
+
return skip(`원격에 ${upstreamRef}가 아직 없어 받을 커밋이 없다.`);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
await out(["fetch", "--no-tags", remote, upstreamRef]);
|
|
71
|
+
const upstream = await out(["rev-parse", "FETCH_HEAD"]);
|
|
72
|
+
const head = await out(["rev-parse", "HEAD"]);
|
|
73
|
+
if (!SHA.test(upstream) || !SHA.test(head) || upstream === head) return { pulled: 0, merged: [] };
|
|
74
|
+
if ((await run(["merge-base", "--is-ancestor", upstream, head])).code === 0) return { pulled: 0, merged: [] }; // 앞서 있다.
|
|
75
|
+
if ((await run(["merge-base", "--is-ancestor", head, upstream])).code !== 0) {
|
|
76
|
+
return skip("작업 사본이 원격과 갈라져(로컬에만 있는 커밋이 있다) 자동으로 받지 않았다.");
|
|
77
|
+
}
|
|
78
|
+
if ((await run(["diff", "--cached", "--quiet"])).code !== 0) return skip("stage된 변경이 있어 원격 커밋을 자동으로 받지 않았다.");
|
|
79
|
+
|
|
80
|
+
const pulled = Number(await out(["rev-list", "--count", `${head}..${upstream}`]));
|
|
81
|
+
const split = (text: string) => text.split("\0").filter(Boolean);
|
|
82
|
+
const incoming = new Set(split((await run(["-c", "core.quotepath=false", "diff", "--no-renames", "--name-only", "-z", head, upstream])).stdout));
|
|
83
|
+
// `--no-optional-locks`: 거절하고 끝나는 경우에도 index의 stat 갱신을 쓰지 않는다. porcelain -z 한 항목은 "XY path".
|
|
84
|
+
const entries = split((await run(["--no-optional-locks", "status", "--porcelain", "-z", "--untracked-files=all", "--no-renames"])).stdout);
|
|
85
|
+
const overlap = entries.map((entry) => ({ path: entry.slice(3), untracked: entry.startsWith("??"), deleted: entry[1] === "D" }))
|
|
86
|
+
.filter((file) => incoming.has(file.path));
|
|
87
|
+
const blocked = overlap.filter((file) => file.untracked || file.deleted).map((file) => file.path);
|
|
88
|
+
if (blocked.length) return skip(`원격 커밋 ${pulled}개가 로컬의 새 파일·삭제와 겹쳐 자동으로 받지 않았다: ${blocked.join(", ")}`);
|
|
89
|
+
|
|
90
|
+
// 겹치는 파일을 작업 트리 바이트 공간에서 미리 병합한다. 충돌이 하나라도 있으면 작업 사본을 건드리지 않는다.
|
|
91
|
+
const plans: Plan[] = [];
|
|
92
|
+
const conflicts: string[] = [];
|
|
93
|
+
for (const { path } of overlap) {
|
|
94
|
+
if ((await run(["cat-file", "-e", `${upstream}:${path}`])).code !== 0) { conflicts.push(`${path}(원격에서 삭제)`); continue; }
|
|
95
|
+
const abs = join(root, path);
|
|
96
|
+
const raw = readFileSync(abs);
|
|
97
|
+
// 확인한 바로 그 바이트를 객체로 남기고 병합한다(경로를 다시 읽으면 그 사이 바뀐 내용이 들어갈 수 있다).
|
|
98
|
+
const rawOid = await out(["hash-object", "-w", "--no-filters", "--stdin"], raw);
|
|
99
|
+
const base = await readBytes(git, ["cat-file", "--filters", `--path=${path}`, `${head}:${path}`], root);
|
|
100
|
+
const theirs = await readBytes(git, ["cat-file", "--filters", `--path=${path}`, `${upstream}:${path}`], root);
|
|
101
|
+
const baseOid = await out(["hash-object", "-w", "--no-filters", "--stdin"], base);
|
|
102
|
+
const theirsOid = await out(["hash-object", "-w", "--no-filters", "--stdin"], theirs);
|
|
103
|
+
const merge = await run(["merge-file", "--object-id", rawOid, baseOid, theirsOid]);
|
|
104
|
+
const mergedOid = merge.stdout.trim();
|
|
105
|
+
if (merge.code !== 0 || !SHA.test(mergedOid)) { conflicts.push(path); continue; }
|
|
106
|
+
const merged = await readBytes(git, ["cat-file", "blob", mergedOid], root);
|
|
107
|
+
plans.push({ path, abs, raw, rawOid, base, theirs, merged });
|
|
108
|
+
}
|
|
109
|
+
if (conflicts.length) return skip(`원격 커밋 ${pulled}개가 로컬 수정과 충돌해 자동으로 받지 않았다: ${conflicts.join(", ")}. 작업 사본은 그대로다.`);
|
|
110
|
+
|
|
111
|
+
// 원래 바이트 복사(객체 백업과 별도). 깨끗하게 끝나지 않으면 이 폴더를 남겨 되살릴 수 있게 한다.
|
|
112
|
+
const backupDir = plans.length ? mkdtempSync(join(tmpdir(), "git-finalize-sync-")) : "";
|
|
113
|
+
for (const plan of plans) {
|
|
114
|
+
mkdirSync(dirname(join(backupDir, plan.path)), { recursive: true });
|
|
115
|
+
writeFileSync(join(backupDir, plan.path), plan.raw);
|
|
116
|
+
}
|
|
117
|
+
const dropBackup = () => { if (backupDir) rmSync(backupDir, { recursive: true, force: true }); };
|
|
118
|
+
const recovery = () => `겹친 파일의 원래 내용: ${backupDir} (백업 객체 ${plans.map((plan) => `${plan.path}=${plan.rawOid}`).join(", ")})`;
|
|
119
|
+
// 준비하는 동안 파일이 또 바뀌었으면(편집기·다른 작업) 그 수정을 덮지 않도록 손대기 전에 멈춘다.
|
|
120
|
+
const changed = plans.filter((plan) => !readFileSync(plan.abs).equals(plan.raw)).map((plan) => plan.path);
|
|
121
|
+
if (changed.length) {
|
|
122
|
+
dropBackup();
|
|
123
|
+
return skip(`병합을 준비하는 동안 ${changed.join(", ")}가 다시 바뀌어 원격 커밋을 받지 않았다. 작업 사본은 그대로다.`);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// 파일 바이트로 상태를 판정해 한 파일씩 마무리한다: 원격판 → 병합 결과(받았을 때만), 기준판 → 원래 바이트, 그 밖 → 건드리지 않는다.
|
|
127
|
+
// 받지 못했으면(HEAD가 원격이 아니거나 확인 실패) 기준판을 쓰다 잘린 내용(기준판의 앞부분)도 원래 바이트로 되돌린다.
|
|
128
|
+
// 그 밖의 바이트(받지 못했는데 원격판과 같은 내용 포함)는 받는 도중 편집기·다른 작업이 저장한 것이라 건드리지 않고 백업을 남긴다.
|
|
129
|
+
const touched = new Set<string>();
|
|
130
|
+
const settle = (received: boolean) => {
|
|
131
|
+
const result = { merged: 0, restored: 0, untouched: [] as string[], errors: [] as string[] };
|
|
132
|
+
for (const plan of plans) {
|
|
133
|
+
try {
|
|
134
|
+
const current = readFileSync(plan.abs);
|
|
135
|
+
if (received && current.equals(plan.theirs)) { writeFileSync(plan.abs, plan.merged); result.merged++; }
|
|
136
|
+
else if (current.equals(plan.base) || current.equals(plan.raw)
|
|
137
|
+
|| (!received && touched.has(plan.path) && current.length < plan.base.length && plan.base.subarray(0, current.length).equals(current))) {
|
|
138
|
+
if (!current.equals(plan.raw)) writeFileSync(plan.abs, plan.raw);
|
|
139
|
+
result.restored++;
|
|
140
|
+
}
|
|
141
|
+
else result.untouched.push(plan.path);
|
|
142
|
+
} catch (error) {
|
|
143
|
+
result.errors.push(`${plan.path}: ${message(error)}`);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return result;
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
// 겹친 파일을 기준판으로 돌려놓아야 fast-forward가 진행된다. 확인과 쓰기 사이에 await가 없다.
|
|
150
|
+
let ffError: string | undefined;
|
|
151
|
+
try {
|
|
152
|
+
for (const plan of plans) { touched.add(plan.path); writeFileSync(plan.abs, plan.base); }
|
|
153
|
+
const ff = await commitExec(git, ["merge", "--ff-only", "--no-overwrite-ignore", upstream], { cwd: root });
|
|
154
|
+
if (ff.code !== 0) ffError = (ff.stderr || ff.stdout).trim();
|
|
155
|
+
} catch (error) {
|
|
156
|
+
ffError = message(error);
|
|
157
|
+
}
|
|
158
|
+
const now = await commitExec(git, ["rev-parse", "HEAD"], { cwd: root }).then((r) => r.code === 0 ? r.stdout.trim() : "", () => "");
|
|
159
|
+
const settled = settle(now === upstream);
|
|
160
|
+
const paths = plans.map((plan) => plan.path);
|
|
161
|
+
if (now === upstream && settled.merged === plans.length) {
|
|
162
|
+
dropBackup();
|
|
163
|
+
const mergedNote = paths.length ? ` 양쪽이 고친 ${paths.join(", ")}는 충돌 없이 합쳤다.` : "";
|
|
164
|
+
return { pulled, merged: paths, note: `작업 사본이 원격보다 뒤처져 있어 원격 커밋 ${pulled}개를 fast-forward로 먼저 받았다.${mergedNote}` };
|
|
165
|
+
}
|
|
166
|
+
if (now === head && settled.restored === plans.length) {
|
|
167
|
+
dropBackup();
|
|
168
|
+
return skip(`원격 커밋 ${pulled}개를 fast-forward로 받지 못해 작업 사본을 원래대로 두었다: ${ffError ?? "알 수 없는 이유"}`);
|
|
169
|
+
}
|
|
170
|
+
throw new Error(`원격 커밋을 받는 도중 상태가 어긋났다(HEAD ${now || "확인 실패"}, 받기 전 ${head}, 원격 ${upstream}${ffError ? `, ${ffError}` : ""}).`
|
|
171
|
+
+ `${settled.untouched.length ? ` 그 사이 다시 바뀐 파일은 건드리지 않았다: ${settled.untouched.join(", ")}.` : ""}`
|
|
172
|
+
+ `${settled.errors.length ? ` 마무리하지 못한 파일: ${settled.errors.join("; ")}.` : ""} ${recovery()}`);
|
|
173
|
+
}
|
package/package.json
CHANGED
|
File without changes
|
|
File without changes
|