cuelo 0.10.95 → 0.10.97

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 (85) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +32 -32
  3. package/.next/build-manifest.json +2 -2
  4. package/.next/prerender-manifest.json +3 -3
  5. package/.next/required-server-files.js +2 -2
  6. package/.next/required-server-files.json +2 -2
  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/updates/apply/route.js +2 -2
  26. package/.next/server/app/api/updates/route.js +1 -1
  27. package/.next/server/app/index.html +1 -1
  28. package/.next/server/app/index.rsc +4 -4
  29. package/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
  30. package/.next/server/app/index.segments/_full.segment.rsc +4 -4
  31. package/.next/server/app/index.segments/_head.segment.rsc +1 -1
  32. package/.next/server/app/index.segments/_index.segment.rsc +2 -2
  33. package/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  34. package/.next/server/app/page.js +2 -2
  35. package/.next/server/app/page_client-reference-manifest.js +1 -1
  36. package/.next/server/app/recover/page_client-reference-manifest.js +1 -1
  37. package/.next/server/app/recover.html +1 -1
  38. package/.next/server/app/recover.rsc +2 -2
  39. package/.next/server/app/recover.segments/_full.segment.rsc +2 -2
  40. package/.next/server/app/recover.segments/_head.segment.rsc +1 -1
  41. package/.next/server/app/recover.segments/_index.segment.rsc +2 -2
  42. package/.next/server/app/recover.segments/_tree.segment.rsc +1 -1
  43. package/.next/server/app/recover.segments/recover/__PAGE__.segment.rsc +1 -1
  44. package/.next/server/app/recover.segments/recover.segment.rsc +1 -1
  45. package/.next/server/app-paths-manifest.json +32 -32
  46. package/.next/server/middleware-build-manifest.js +1 -1
  47. package/.next/server/pages/404.html +1 -1
  48. package/.next/server/pages/500.html +1 -1
  49. package/.next/server/server-reference-manifest.json +1 -1
  50. package/.next/static/chunks/app/{layout-cf209ec1ffc50146.js → layout-e946c4e8f6b1554d.js} +1 -1
  51. package/.next/static/chunks/app/{page-248f0f6ee3f5b6ee.js → page-0b878506cec78452.js} +2 -2
  52. package/.next/trace +108 -108
  53. package/.next/trace-build +1 -1
  54. package/README.md +1 -9
  55. package/Tools/CUELO_Setup/files/native-runtime-patch.js +3 -3
  56. package/Tools/OMP_Global_Config/agent/agents/maker.md +3 -3
  57. package/Tools/OMP_Global_Config/agent/extensions/command-guard/index.ts +174 -31
  58. package/Tools/OMP_Global_Config/agent/extensions/command-guard/matcher.ts +417 -54
  59. package/Tools/OMP_Global_Config/agent/extensions/command-guard/task-guard.ts +206 -48
  60. package/Tools/OMP_Global_Config/agent/extensions/cross-review.ts +1 -1
  61. package/Tools/OMP_Global_Config/agent/extensions/jev-runtime.ts +39 -59
  62. package/Tools/OMP_Global_Config/agent/extensions/lib/cross-review.ts +214 -43
  63. package/Tools/OMP_Global_Config/agent/extensions/lib/draft-coverage.ts +7 -2
  64. package/Tools/OMP_Global_Config/agent/extensions/lib/job-observation.ts +6 -5
  65. package/Tools/OMP_Global_Config/agent/extensions/lib/maker-routing.ts +35 -7
  66. package/Tools/OMP_Global_Config/agent/extensions/lib/prepared-task.ts +7 -5
  67. package/Tools/OMP_Global_Config/agent/extensions/lib/slop-gate.ts +31 -6
  68. package/Tools/OMP_Global_Config/agent/extensions/report-chart-guard.ts +21 -4
  69. package/Tools/OMP_Global_Config/agent/extensions/slop-gate/review.ts +67 -16
  70. package/Tools/OMP_Global_Config/agent/extensions/slop-gate.ts +2 -2
  71. package/Tools/OMP_Global_Config/agent/extensions/todo-nudge.ts +14 -4
  72. package/Tools/OMP_Global_Config/agent/rules/deploy-ops.md +1 -0
  73. package/Tools/OMP_Global_Config/agent/rules/harness-policy.json +14 -10
  74. package/Tools/OMP_Global_Config/agent/rules/subagent.md +17 -12
  75. package/Tools/OMP_Global_Config/agent/rules/task-guard.md +5 -3
  76. package/Tools/OMP_Global_Config/agent/sop/_writer.md +1 -1
  77. package/Tools/OMP_Global_Config/agent/sop/maker.md +1 -1
  78. package/Tools/OMP_Global_Config/agent/tools/ci-chain/index.ts +166 -4
  79. package/Tools/OMP_Global_Config/agent/tools/ci-chain/paths-filter.ts +130 -0
  80. package/Tools/OMP_Global_Config/agent/tools/git-finalizer/index.ts +20 -1
  81. package/Tools/OMP_Global_Config/patches/apply-core-patch.mjs +176 -0
  82. package/bin/self-update.js +2 -1
  83. package/package.json +7 -7
  84. /package/.next/static/{njFeZPW-f3RTy2-iTWbzY → VSLxmLHaJ0rBK71SMfdbr}/_buildManifest.js +0 -0
  85. /package/.next/static/{njFeZPW-f3RTy2-iTWbzY → VSLxmLHaJ0rBK71SMfdbr}/_ssgManifest.js +0 -0
@@ -1,4 +1,4 @@
1
- import { isAbsolute, resolve } from "node:path";
1
+ import { basename, isAbsolute, resolve } from "node:path";
2
2
 
3
3
  export interface GuardContext {
4
4
  /** bash tool_call이 지정한 cwd. 없으면 세션 cwd. */
@@ -9,6 +9,61 @@ export interface GuardContext {
9
9
  * 주어진 디렉터리를 하네스가 Windows `git.exe`로 다루는지(WSL의 `/mnt/<드라이브>` 저장소). 미제공이면 판정하지 않는다.
10
10
  */
11
11
  usesWindowsGit?: (dir: string) => boolean;
12
+ /**
13
+ * 주어진 디렉터리(아직 없을 수 있다)가 git이 찾는 어느 저장소에도 속하지 않음이 증명되는지. 미제공이면 판정하지 않는다.
14
+ * `isSessionRepository`가 막는 대상 중 이것이 참인 곳의 add·commit·commit-tree·update-ref만 허용한다(push는 제외).
15
+ */
16
+ isOutsideRepository?: (dir: string) => boolean;
17
+ /**
18
+ * 주어진 디렉터리(아직 없을 수 있다)가 임시 루트(/tmp·os.tmpdir()) 아래의 실제 경로이고 세션 작업 트리가 아닌지.
19
+ * 미제공이면 임시 면제를 쓰지 않는다. 그 아래 작업 트리를 버리는 checkout·switch·restore·worktree remove만 허용한다.
20
+ */
21
+ isTemporaryDirectory?: (dir: string) => boolean;
22
+ /** 인자 없는 mktemp가 만드는 위치. 미제공이면 /tmp다. */
23
+ temporaryRoot?: string;
24
+ }
25
+
26
+ /**
27
+ * 한 명령 전체(하위 셸 포함)가 앞 세그먼트에서 바꾼 파일 시스템 위치. 실행 전 관측에 기댄 판정을 그 위치에 쓰지 않는다.
28
+ * 하위 셸(`bash -c`)이 만든 것도 바깥 명령의 뒤 세그먼트에 보여야 하므로 한 객체를 참조로 넘긴다. ""는 어디든이다.
29
+ */
30
+ interface CommandEffects {
31
+ /** `git worktree add`가 만든 worktree. 세션 저장소의 것이므로 "저장소 밖" 추론을 쓰지 않는다. */
32
+ addedWorktrees: string[];
33
+ /** `ln`·`mv`·`cp`·`rsync`의 피연산자. 심볼릭 링크일 수 있어 실행 전 실제 경로 판정(임시·저장소 밖)을 쓰지 않는다. */
34
+ relinked: string[];
35
+ /**
36
+ * 명령 글(역슬래시·따옴표를 뺀 것)이 git의 저장소 찾기를 바꿀 수 있는 것을 언급한다(`.git` 경로, `gitdir:`, `--git-dir`·
37
+ * `--work-tree`·`--separate-git-dir`, GIT_* 위치 변수, core.worktree). 같은 명령이 `.git` 링크·파일을 만들면 실행 전
38
+ * "저장소 밖"·"임시 작업 트리" 관측이 틀리므로 그 두 면제를 쓰지 않는다.
39
+ */
40
+ repositoryRedirect: boolean;
41
+ }
42
+
43
+ const REPOSITORY_REDIRECT =
44
+ /--git-dir|--work-tree|--separate-git-dir|gitdir|core\.worktree|\bGIT_(?:DIR|WORK_TREE|COMMON_DIR|INDEX_FILE|OBJECT_DIRECTORY|ALTERNATE_OBJECT_DIRECTORIES|CEILING_DIRECTORIES|DISCOVERY_ACROSS_FILESYSTEM)\b|(?:^|[\s/=:;&|(<>])\.git(?![\w.-])/i;
45
+
46
+ /**
47
+ * git이 저장소를 찾지 못했을 때의 stderr 전체(LC_ALL=C)인가. 일반형(git 2.43.0 실측)과 파일 시스템 경계형(setup.c)만 받는다.
48
+ * 다른 진단(소유권 의심 등)이 경로 속에 이 문구를 담아도 통째로 같아야 하므로 "어느 저장소도 아님"의 증명으로 쓰지 않는다.
49
+ */
50
+ export function isNotRepositoryDiagnostic(stderr: string): boolean {
51
+ return /^fatal: not a git repository \((?:or any of the parent directories\): \.git|or any parent up to mount point [^\n]*\)\nStopping at filesystem boundary \(GIT_DISCOVERY_ACROSS_FILESYSTEM not set\)\.)\n?$/.test(
52
+ stderr,
53
+ );
54
+ }
55
+
56
+ /** 한 세그먼트를 판정할 때의 위치 정보: 앞서 대입한 변수 중 경로로 확정한 값과 같은 명령이 바꾼 위치. */
57
+ interface SegmentContext extends GuardContext {
58
+ variables?: ReadonlyMap<string, string>;
59
+ effects?: CommandEffects;
60
+ /** 명령(또는 그것을 부른 바깥 명령)이 GIT_DIR·GIT_WORK_TREE를 써 위치가 저장소를 정하지 않는다. 위치에 기댄 면제를 쓰지 않는다. */
61
+ locationOverridden?: boolean;
62
+ }
63
+
64
+ /** `path`가 `bases` 중 하나이거나 그 아래인가. ""는 어디든이다. */
65
+ function withinAny(path: string, bases: readonly string[]): boolean {
66
+ return bases.some((base) => base === "" || path === base || path.startsWith(`${base}/`));
12
67
  }
13
68
 
14
69
  type Separator = ";" | "&&" | "||" | "|" | "&" | "\n";
@@ -1133,6 +1188,24 @@ function hasShellExpansion(value: string): boolean {
1133
1188
  return /[$%`*?]|(?:^|[=:])~/.test(value);
1134
1189
  }
1135
1190
 
1191
+ /**
1192
+ * 셸 확장이 없는 낱말은 그대로, `$NAME`·`${NAME}`(뒤에 `/…`만 올 수 있다)은 같은 명령에서 앞서 경로로 확정한 변수 값으로
1193
+ * 바꾼다. 그 밖의 확장(`~`, 모르는 변수, 글롭, 명령 치환)은 위치를 알 수 없어 undefined다.
1194
+ */
1195
+ function expandPath(value: string, variables: ReadonlyMap<string, string> | undefined): string | undefined {
1196
+ if (!hasShellExpansion(value)) return value;
1197
+ const match = /^\$(?:\{([A-Za-z_]\w*)\}|([A-Za-z_]\w*))(\/.*)?$/s.exec(value);
1198
+ const base = match ? variables?.get(match[1] ?? match[2]!) : undefined;
1199
+ const rest = match?.[3] ?? "";
1200
+ if (base === undefined || hasShellExpansion(rest)) return undefined;
1201
+ return base + rest;
1202
+ }
1203
+
1204
+ /** 절대경로는 그대로, 상대경로는 `directory` 기준으로 푼다. 기준을 모르면 undefined다. */
1205
+ function resolveFrom(directory: string | undefined, path: string): string | undefined {
1206
+ return isAbsolute(path) ? resolve(path) : directory === undefined ? undefined : resolve(directory, path);
1207
+ }
1208
+
1136
1209
  /**
1137
1210
  * git이 실제로 여는 위치. `cwd`가 null이면(앞선 cd를 확정할 수 없음) 절대경로 `-C`·`--git-dir`만으로 정해질 때만
1138
1211
  * 값을 돌려주고, 그 밖에는 undefined다. undefined `cwd`는 현재 프로세스 위치(".")다.
@@ -1140,6 +1213,7 @@ function hasShellExpansion(value: string): boolean {
1140
1213
  function gitTargetDirectory(
1141
1214
  git: GitInvocation,
1142
1215
  cwd: string | null | undefined,
1216
+ variables?: ReadonlyMap<string, string>,
1143
1217
  ): string | undefined {
1144
1218
  let directory = cwd === null ? undefined : resolve(cwd ?? ".");
1145
1219
  let gitDirectoryPath: string | undefined;
@@ -1149,25 +1223,25 @@ function gitTargetDirectory(
1149
1223
  if (value === "--") break;
1150
1224
 
1151
1225
  if (value === "-C" || value === "--git-dir") {
1152
- const path = git.globalArgs[index + 1];
1153
- if (path === undefined || hasShellExpansion(path)) return undefined;
1154
- if (value === "-C") {
1155
- directory = isAbsolute(path) ? resolve(path) : directory === undefined ? undefined : resolve(directory, path);
1156
- } else gitDirectoryPath = path;
1226
+ const raw = git.globalArgs[index + 1];
1227
+ const path = raw === undefined ? undefined : expandPath(raw, variables);
1228
+ if (path === undefined) return undefined;
1229
+ if (value === "-C") directory = resolveFrom(directory, path);
1230
+ else gitDirectoryPath = path;
1157
1231
  index += 1;
1158
1232
  continue;
1159
1233
  }
1160
1234
 
1161
1235
  if (value.startsWith("-C") && value.length > 2) {
1162
- const path = value.slice(2);
1163
- if (hasShellExpansion(path)) return undefined;
1164
- directory = isAbsolute(path) ? resolve(path) : directory === undefined ? undefined : resolve(directory, path);
1236
+ const path = expandPath(value.slice(2), variables);
1237
+ if (path === undefined) return undefined;
1238
+ directory = resolveFrom(directory, path);
1165
1239
  continue;
1166
1240
  }
1167
1241
 
1168
1242
  if (value.startsWith("--git-dir=")) {
1169
- const path = value.slice("--git-dir=".length);
1170
- if (hasShellExpansion(path)) return undefined;
1243
+ const path = expandPath(value.slice("--git-dir=".length), variables);
1244
+ if (path === undefined) return undefined;
1171
1245
  gitDirectoryPath = path;
1172
1246
  continue;
1173
1247
  }
@@ -1231,39 +1305,80 @@ function isWorktreeWidePathspec(value: string): boolean {
1231
1305
 
1232
1306
  /**
1233
1307
  * 작업 트리·stash의 변경을 되돌릴 수 없게 버리는 git 명령. 파일 하나를 지정한 복원, 브랜치 전환, `restore --staged`처럼
1234
- * index만 바꾸는 명령, 새 stash 저장·적용은 막지 않는다.
1308
+ * index만 바꾸는 명령, 새 stash 저장·적용은 막지 않는다. 버릴 작업 트리가 임시 루트 아래면(discardsTemporaryTree) 막지 않는다.
1235
1309
  */
1236
- function matchWorkDiscard(git: GitInvocation): string | undefined {
1310
+ function matchWorkDiscard(git: GitInvocation, context: SegmentContext | undefined): string | undefined {
1237
1311
  const flags = shortFlags(git.args);
1238
1312
  const force = flags.has("f") || hasLongOption(git.args, ["--force"], 3);
1239
1313
  const action = git.args.find((value) => !value.startsWith("-"))?.toLowerCase();
1314
+ let discards: boolean;
1240
1315
 
1241
1316
  switch (git.subcommand) {
1242
1317
  case "checkout":
1243
- return force || positionalArguments(git.args, {}).some(isWorktreeWidePathspec)
1244
- ? REASONS.gitDiscard
1245
- : undefined;
1318
+ discards = force || positionalArguments(git.args, {}).some(isWorktreeWidePathspec);
1319
+ break;
1246
1320
  case "switch":
1247
- return force || hasLongOption(git.args, ["--discard-changes"], 4) ? REASONS.gitDiscard : undefined;
1321
+ discards = force || hasLongOption(git.args, ["--discard-changes"], 4);
1322
+ break;
1248
1323
  case "restore": {
1249
1324
  const staged = flags.has("S") || hasLongOption(git.args, ["--staged"], 4);
1250
1325
  const worktree = flags.has("W") || hasLongOption(git.args, ["--worktree"], 4);
1251
1326
  const wide = positionalArguments(git.args, {}).some(isWorktreeWidePathspec);
1252
- return wide && (worktree || !staged) ? REASONS.gitDiscard : undefined;
1327
+ discards = wide && (worktree || !staged);
1328
+ break;
1253
1329
  }
1254
1330
  case "stash":
1331
+ // stash는 저장소 전체가 함께 쓰므로 어느 작업 트리에서 지워도 세션 저장소의 stash가 사라진다. 면제하지 않는다.
1255
1332
  return action === "clear" || action === "drop" ? REASONS.gitDiscard : undefined;
1256
1333
  case "worktree":
1257
- return action === "remove" && force ? REASONS.gitDiscard : undefined;
1334
+ discards = action === "remove" && force;
1335
+ break;
1258
1336
  default:
1259
1337
  return undefined;
1260
1338
  }
1339
+ return discards && !discardsTemporaryTree(git, context) ? REASONS.gitDiscard : undefined;
1340
+ }
1341
+
1342
+ /**
1343
+ * 버리는 작업 트리가 임시 루트(/tmp·os.tmpdir()) 아래의 임시 작업공간인가. 2026-10-28 사용자 승인(가드 감사 오탐: /tmp scratch의
1344
+ * checkout -f, 같은 명령이 만든 /tmp worktree의 remove --force). `worktree remove`는 지울 경로를, 나머지는 git이 여는 위치를 본다.
1345
+ * GIT_DIR·GIT_WORK_TREE·`--git-dir`·`--work-tree`를 쓰면 위치가 작업 트리를 정하지 않으므로 면제하지 않는다.
1346
+ */
1347
+ function discardsTemporaryTree(git: GitInvocation, context: SegmentContext | undefined): boolean {
1348
+ if (!context?.isTemporaryDirectory || context.locationOverridden) return false;
1349
+ if (git.globalArgs.some((value) => /^--(?:git-dir|work-tree)(?:=|$)/.test(value))) return false;
1350
+ let target: string | undefined;
1351
+ if (git.subcommand === "worktree") {
1352
+ const path = positionalArguments(git.args, {})[1];
1353
+ const expanded = path === undefined ? undefined : expandPath(path, context.variables);
1354
+ const base = gitTargetDirectory(git, context.cwd, context.variables);
1355
+ target = expanded === undefined ? undefined : resolveFrom(base, expanded);
1356
+ } else {
1357
+ target = gitTargetDirectory(git, context.cwd, context.variables);
1358
+ }
1359
+ if (!target || context.effects?.repositoryRedirect || withinAny(target, context.effects?.relinked ?? [])) return false;
1360
+ try {
1361
+ return context.isTemporaryDirectory(target);
1362
+ } catch {
1363
+ return false;
1364
+ }
1365
+ }
1366
+
1367
+ /**
1368
+ * `git add -N`(`--intent-to-add`)는 나중에 더할 경로를 내용 없이 index에 적기만 한다. 내용을 stage하지 않으므로 막지 않는다.
1369
+ * 뒤의 `--no-intent-to-add`는 -N을 끄고 실제 내용을 stage하므로(git 2.x 실측) 어디에 있든 면제하지 않는다.
1370
+ */
1371
+ function isIntentToAdd(git: GitInvocation): boolean {
1372
+ if (git.subcommand !== "add") return false;
1373
+ if (hasLongOption(git.args, ["--chmod", "--renormalize"], 5)) return false;
1374
+ if (hasLongOption(git.args, ["--no-intent-to-add"], 6)) return false;
1375
+ return shortFlags(git.args).has("N") || hasLongOption(git.args, ["--intent-to-add"], 8);
1261
1376
  }
1262
1377
 
1263
1378
  function matchGit(
1264
1379
  tokens: ShellToken[],
1265
1380
  invocation: Invocation,
1266
- context?: GuardContext,
1381
+ context?: SegmentContext,
1267
1382
  ): string | undefined {
1268
1383
  const git = parseGitInvocation(tokens, invocation);
1269
1384
  if (!git) return undefined;
@@ -1274,14 +1389,24 @@ function matchGit(
1274
1389
  (git.subcommand === "add" || git.subcommand === "commit" || git.subcommand === "push") &&
1275
1390
  (hasLongOption(git.args, ["--dry-run"]) ||
1276
1391
  (git.subcommand !== "commit" && shortFlags(git.args).has("n")));
1277
- if (dryRun) return undefined;
1392
+ if (dryRun || isIntentToAdd(git)) return undefined;
1278
1393
  if (!context?.isSessionRepository) return REASONS.gitFinalize;
1279
- const targetDirectory = gitTargetDirectory(git, context.cwd);
1394
+ const targetDirectory = gitTargetDirectory(git, context.cwd, context.variables);
1280
1395
  if (!targetDirectory) return REASONS.gitFinalize;
1281
1396
  try {
1282
- return context.isSessionRepository(targetDirectory)
1283
- ? REASONS.gitFinalize
1284
- : undefined;
1397
+ if (!context.isSessionRepository(targetDirectory)) return undefined;
1398
+ // 어느 저장소에도 속하지 않음이 증명된 곳(아직 없는 mktemp 폴더, 같은 명령의 git init 대상)은 세션 저장소가 아니다.
1399
+ // push는 원격에 닿으므로, 같은 명령이 만든 worktree는 세션 저장소의 것이므로, 같은 명령이 링크·이동으로 바꾼 위치는
1400
+ // 실행 전 관측과 다를 수 있으므로, 위치가 저장소를 정하지 않으면 쓰지 않는다.
1401
+ const effects = context.effects;
1402
+ const provenOutside =
1403
+ git.subcommand !== "push" &&
1404
+ !withinAny(targetDirectory, effects?.addedWorktrees ?? []) &&
1405
+ !withinAny(targetDirectory, effects?.relinked ?? []) &&
1406
+ !effects?.repositoryRedirect &&
1407
+ !context.locationOverridden &&
1408
+ context.isOutsideRepository?.(targetDirectory) === true;
1409
+ return provenOutside ? undefined : REASONS.gitFinalize;
1285
1410
  } catch {
1286
1411
  return REASONS.gitFinalize;
1287
1412
  }
@@ -1299,7 +1424,7 @@ function matchGit(
1299
1424
  if (force && !dryRun) return REASONS.gitClean;
1300
1425
  }
1301
1426
 
1302
- const discardReason = matchWorkDiscard(git);
1427
+ const discardReason = matchWorkDiscard(git, context);
1303
1428
  if (discardReason) return discardReason;
1304
1429
 
1305
1430
  if (git.subcommand === "rm") {
@@ -2124,40 +2249,220 @@ export function invokedCommands(command: string): string[] {
2124
2249
  return invoked;
2125
2250
  }
2126
2251
 
2252
+ /** 같은 명령에서 `NAME=…`로 대입한 값 중 경로로 쓸 수 있는 것. 대입 시점의 위치(`cwd`)에 기대는 mktemp 결과만 미리 푼다. */
2253
+ function assignedPath(
2254
+ value: string,
2255
+ variables: ReadonlyMap<string, string>,
2256
+ cwd: string | null | undefined,
2257
+ temporaryRoot: string,
2258
+ ): string | undefined {
2259
+ const substitution = /^\$\(([\s\S]*)\)$/.exec(value) ?? /^`([\s\S]*)`$/.exec(value);
2260
+ if (substitution) return mktempPath(substitution[1]!, variables, cwd, temporaryRoot);
2261
+ return expandPath(value, variables);
2262
+ }
2263
+
2264
+ /**
2265
+ * `$(mktemp …)`가 만드는 경로(GNU mktemp): 템플릿이 없거나 `-p`·`--tmpdir`·`-t`가 있으면 그 폴더(없으면 임시 루트) 아래,
2266
+ * 템플릿만 있으면 현재 위치 기준이다. mktemp 하나가 아니거나 폴더를 정할 수 없으면 undefined다.
2267
+ */
2268
+ function mktempPath(
2269
+ inner: string,
2270
+ variables: ReadonlyMap<string, string>,
2271
+ cwd: string | null | undefined,
2272
+ temporaryRoot: string,
2273
+ ): string | undefined {
2274
+ const { segments } = tokenizeShell(inner);
2275
+ if (segments.length !== 1) return undefined;
2276
+ const tokens = segments[0]!.tokens;
2277
+ const invocation = resolveInvocation(tokens);
2278
+ if (invocation?.name !== "mktemp") return undefined;
2279
+ const args = tokens.slice(invocation.index + 1).map((token) => token.value);
2280
+ let directory: string | undefined;
2281
+ let inTemporaryDirectory = false;
2282
+ let template: string | undefined;
2283
+ for (let index = 0; index < args.length; index += 1) {
2284
+ const value = args[index]!;
2285
+ if (value === "-p") {
2286
+ directory = args[(index += 1)];
2287
+ if (directory === undefined) return undefined;
2288
+ } else if (value.startsWith("--tmpdir=")) directory = value.slice("--tmpdir=".length);
2289
+ else if (value === "--tmpdir" || value === "-t") inTemporaryDirectory = true;
2290
+ else if (value === "--suffix") index += 1;
2291
+ else if (value.startsWith("-")) {
2292
+ if (!value.startsWith("--") && value.includes("p")) return undefined;
2293
+ } else template ??= value;
2294
+ }
2295
+ const base = cwd === null ? undefined : resolve(cwd ?? ".");
2296
+ if (template !== undefined && directory === undefined && !inTemporaryDirectory) {
2297
+ const path = expandPath(template, variables);
2298
+ return path === undefined ? undefined : resolveFrom(base, path);
2299
+ }
2300
+ const folder = directory === undefined ? temporaryRoot : expandPath(directory, variables);
2301
+ const resolvedFolder = folder === undefined ? undefined : resolveFrom(base, folder);
2302
+ return resolvedFolder === undefined ? undefined : resolve(resolvedFolder, template ?? "tmp.XXXXXXXXXX");
2303
+ }
2304
+
2305
+ /** `git worktree add <path>`가 만드는 worktree 경로. worktree add가 아니면 undefined, 경로를 정할 수 없으면 ""(어디든)다. */
2306
+ function addedWorktreePath(tokens: ShellToken[], invocation: Invocation, context: SegmentContext | undefined): string | undefined {
2307
+ const git = parseGitInvocation(tokens, invocation);
2308
+ if (git?.subcommand !== "worktree") return undefined;
2309
+ const [action, path] = positionalArguments(git.args, { "-b": true, "-B": true, "--reason": true });
2310
+ if (action?.toLowerCase() !== "add") return undefined;
2311
+ const expanded = path === undefined ? undefined : expandPath(path, context?.variables);
2312
+ const base = context ? gitTargetDirectory(git, context.cwd, context.variables) : undefined;
2313
+ return (expanded === undefined ? undefined : resolveFrom(base, expanded)) ?? "";
2314
+ }
2315
+
2316
+ const RELINKING_COMMANDS: StringLookup = { ln: true, mv: true, cp: true, rsync: true };
2317
+
2318
+ /**
2319
+ * `ln`·`mv`·`cp`·`rsync`가 만들거나 바꿀 수 있는 위치. 목적지만 고르지 않고 옵션이 아닌 인자를 모두 바뀐 위치로 본다(그 자체와
2320
+ * 그 아래). 값을 받는 GNU 옵션 `-S`/`--suffix`(값은 경로가 아니다)와 `-t`/`--target-directory`(값은 목적지)는 줄인 긴 이름까지
2321
+ * 따로 읽는다. rsync는 값 받는 옵션이 많아 옵션 아닌 인자를 모두 넣는다. 피연산자가 하나인 `ln <원본>`은 현재 폴더에 원본의
2322
+ * 이름으로 링크를 만들므로 `cwd/basename`도 넣는다. 이 명령이 아니면 빈 목록, 위치를 정할 수 없으면 ""(어디든)를 넣는다.
2323
+ */
2324
+ function relinkedPaths(
2325
+ tokens: ShellToken[],
2326
+ invocation: Invocation,
2327
+ cwd: string | null | undefined,
2328
+ variables: ReadonlyMap<string, string>,
2329
+ ): string[] {
2330
+ if (!RELINKING_COMMANDS[invocation.name]) return [];
2331
+ const gnu = invocation.name !== "rsync";
2332
+ const longTakes = (option: string, name: string) => option.length >= 4 && name.startsWith(option);
2333
+ const operands: string[] = [];
2334
+ const targets: string[] = [];
2335
+ const inlineValues: string[] = [];
2336
+ const args = tokens.slice(invocation.index + 1).map((token) => token.value);
2337
+ let optionsEnded = false;
2338
+ for (let index = 0; index < args.length; index += 1) {
2339
+ const value = args[index]!;
2340
+ if (optionsEnded || value === "-" || !value.startsWith("-")) {
2341
+ operands.push(value);
2342
+ } else if (value === "--") {
2343
+ optionsEnded = true;
2344
+ } else if (value.startsWith("--")) {
2345
+ const equals = value.indexOf("=");
2346
+ const option = equals > 0 ? value.slice(0, equals) : value;
2347
+ const inline = equals > 0 ? value.slice(equals + 1) : undefined;
2348
+ if (gnu && longTakes(option, "--target-directory")) {
2349
+ const directory = inline ?? args[(index += 1)];
2350
+ if (directory === undefined) return [""];
2351
+ targets.push(directory);
2352
+ } else if (gnu && longTakes(option, "--suffix")) {
2353
+ if (inline === undefined) index += 1;
2354
+ } else if (inline !== undefined) {
2355
+ // `--backup=none` 같은 다른 옵션의 값: 경로일 수 있어 넣지만 명시한 목적지는 아니다(R4-OAI-1).
2356
+ inlineValues.push(inline);
2357
+ }
2358
+ } else if (gnu) {
2359
+ // 짧은 옵션 묶음: S·t 뒤의 글자는 그 값이고, 끝에 오면 다음 인자가 값이다.
2360
+ const cluster = value.slice(1);
2361
+ const at = cluster.search(/[St]/);
2362
+ if (at >= 0) {
2363
+ const glued = cluster.slice(at + 1);
2364
+ const taken = glued || args[(index += 1)];
2365
+ if (taken === undefined) return [""];
2366
+ if (cluster[at] === "t") targets.push(taken);
2367
+ }
2368
+ }
2369
+ }
2370
+ if (operands.length + targets.length === 0) return [""];
2371
+ const paths: string[] = [];
2372
+ for (const value of [...operands, ...targets, ...inlineValues]) {
2373
+ const expanded = expandPath(value, variables);
2374
+ if (expanded === undefined) return [""];
2375
+ paths.push(resolveFrom(cwd ?? undefined, expanded) ?? "");
2376
+ }
2377
+ if (invocation.name === "ln" && targets.length === 0 && operands.length === 1) {
2378
+ const name = basename(expandPath(operands[0]!, variables) ?? "");
2379
+ paths.push(name ? (resolveFrom(cwd ?? undefined, name) ?? "") : "");
2380
+ }
2381
+ return paths;
2382
+ }
2383
+
2384
+ /** `export`·`readonly`·`declare`·`local`·`typeset`의 `NAME=…` 인자도 이후 세그먼트가 보는 대입이다. */
2385
+ const ASSIGNING_BUILTINS: StringLookup = { export: true, readonly: true, declare: true, local: true, typeset: true };
2386
+
2127
2387
  function matchBlockedCommandInternal(
2128
2388
  command: string,
2129
2389
  depth: number,
2130
- context: GuardContext | undefined,
2390
+ context: SegmentContext | undefined,
2131
2391
  windowsShell: boolean,
2392
+ effects: CommandEffects,
2132
2393
  ): string | undefined {
2133
2394
  const tokenized = tokenizeShell(command);
2134
2395
  const segments = tokenized.segments;
2135
- const descend = (script: string, scriptContext: GuardContext | undefined, shell: boolean): string | undefined =>
2136
- depth < MAX_NESTING ? matchBlockedCommandInternal(script, depth + 1, scriptContext, shell) : undefined;
2396
+ // 하위 셸(`bash -c '…'`)은 export하지 않은 변수를 보지 못하므로 확정한 변수 값을 넘기지 않는다(모르는 위치로 보고 막는다).
2397
+ // 바꾼 위치(effects)와 GIT_DIR·GIT_WORK_TREE 덮어쓰기는 하위 셸에도 그대로 이어진다.
2398
+ const descend = (script: string, scriptContext: SegmentContext | undefined, shell: boolean): string | undefined =>
2399
+ depth < MAX_NESTING
2400
+ ? matchWithUnescape(script, depth + 1, scriptContext && { ...scriptContext, variables: undefined }, shell, effects)
2401
+ : undefined;
2137
2402
  for (const script of tokenized.loose) {
2138
2403
  const reason = descend(script, context, windowsShell);
2139
2404
  if (reason) return reason;
2140
2405
  }
2141
2406
  // `cd <리터럴 경로>` 뒤 `&&`로만 이어진 호출은 그 경로에서 돈다. `;`·`||`·`|`·`&`·줄바꿈으로 이어지면 cd가 실패해도
2142
2407
  // 다음 호출이 돌 수 있어 위치를 모르는 것(null)으로 보고 finalizer 소유 git을 막는다. 괄호 subshell의 cd는 닫히면
2143
- // 사라진다. GIT_DIR·GIT_WORK_TREE를 쓰는 명령은 위치가 저장소를 정하지 않으므로 cd를 따라가지 않는다.
2144
- const followCd = !/\bGIT_(?:DIR|WORK_TREE)\b/.test(command);
2408
+ // 사라진다. GIT_DIR·GIT_WORK_TREE를 쓰는 명령(바깥 명령이 쓴 경우 포함)은 위치가 저장소를 정하지 않으므로 cd를 따라가지 않는다.
2409
+ const locationOverridden = Boolean(context?.locationOverridden) || /\bGIT_(?:DIR|WORK_TREE)\b/.test(command);
2410
+ const followCd = !locationOverridden;
2145
2411
  const cwds: (string | null | undefined)[] = [context?.cwd];
2146
2412
  const moved: boolean[] = [false];
2413
+ // 경로로 확정한 변수(`T=$(mktemp -d)`, `P="$T/x"`, `D=/tmp/x`). subshell 안 대입은 닫히면 사라진다(cwds와 같은 규칙).
2414
+ const scopes: Map<string, string>[] = [new Map(context?.variables)];
2415
+ // `a && T=…`처럼 앞 명령이 성공해야 도는 대입. 같은 `&&` 사슬 안에서는 대입이 건너뛰어지면 뒤도 건너뛰지만, 사슬이
2416
+ // `;`·`||`·줄바꿈으로 끊기면 대입 여부를 모르므로 그 변수를 모르는 값으로 돌린다(cwd의 moved와 같은 규칙).
2417
+ const pending: Set<string>[] = [new Set()];
2418
+ const temporaryRoot = context?.temporaryRoot ?? "/tmp";
2147
2419
 
2148
2420
  for (let index = 0; index < segments.length; index += 1) {
2149
2421
  const segment = segments[index];
2150
2422
  for (let level = cwds.length; level <= segment.depth; level += 1) {
2151
2423
  cwds[level] = cwds[level - 1];
2152
2424
  moved[level] = moved[level - 1];
2153
- }
2154
- cwds.length = moved.length = segment.depth + 1;
2155
- if (index > 0 && segment.separatorBefore !== "&&" && moved[segment.depth]) cwds[segment.depth] = null;
2425
+ scopes[level] = new Map(scopes[level - 1]);
2426
+ pending[level] = new Set(pending[level - 1]);
2427
+ }
2428
+ cwds.length = moved.length = scopes.length = pending.length = segment.depth + 1;
2429
+ const scope = scopes[segment.depth]!;
2430
+ const conditional = pending[segment.depth]!;
2431
+ const separator = index > 0 ? segment.separatorBefore : undefined;
2432
+ if (separator !== undefined && separator !== "&&") {
2433
+ if (moved[segment.depth]) cwds[segment.depth] = null;
2434
+ for (const name of conditional) scope.delete(name);
2435
+ conditional.clear();
2436
+ }
2437
+ // `a || b`의 b는 a가 성공하면 건너뛰고, 파이프·백그라운드의 원소는 subshell에서 돌아 뒤 세그먼트의 위치·변수를 바꾸지 못한다.
2438
+ const following = segments[index + 1]?.separatorBefore;
2439
+ const unreliable =
2440
+ separator === "||" || separator === "|" || separator === "&" || following === "|" || following === "&";
2156
2441
 
2157
2442
  const invocation = resolveInvocation(segment.tokens);
2158
2443
  const segmentCwd = cwds[segment.depth];
2159
- const gitContext = segmentCwd === null ? undefined : context && { ...context, cwd: segmentCwd };
2160
- // 하위 스크립트는 이 세그먼트가 도는 위치에서 실행된다. 이 세그먼트의 `cd`는 그 뒤에 적용한다.
2444
+ const gitContext: SegmentContext | undefined =
2445
+ segmentCwd === null
2446
+ ? undefined
2447
+ : context && { ...context, cwd: segmentCwd, variables: scope, effects, locationOverridden };
2448
+ const assignments = !invocation
2449
+ ? segment.tokens.map((token) => token.value)
2450
+ : ASSIGNING_BUILTINS[invocation.name]
2451
+ ? segment.tokens.slice(invocation.index + 1).map((token) => token.value)
2452
+ : [];
2453
+ for (const value of assignments) {
2454
+ if (!isEnvironmentAssignment(value)) continue;
2455
+ const name = value.slice(0, value.indexOf("="));
2456
+ const path = unreliable ? undefined : assignedPath(value.slice(name.length + 1), scope, segmentCwd, temporaryRoot);
2457
+ if (path === undefined) {
2458
+ scope.delete(name);
2459
+ conditional.delete(name);
2460
+ } else {
2461
+ scope.set(name, path);
2462
+ if (separator === "&&") conditional.add(name);
2463
+ else conditional.delete(name);
2464
+ }
2465
+ }
2161
2466
  const nestedWindowsShell =
2162
2467
  windowsShell ||
2163
2468
  Boolean(
@@ -2177,20 +2482,29 @@ function matchBlockedCommandInternal(
2177
2482
  .map((token) => token.value)
2178
2483
  .filter((value) => value !== "-L" && value !== "-P" && value !== "--");
2179
2484
  const from = cwds[segment.depth];
2180
- const target = targets[0];
2485
+ const target = targets[0] === undefined ? undefined : expandPath(targets[0], scope);
2181
2486
  const literal =
2182
- followCd && invocation.name === "cd" && targets.length === 1 && target !== "-" && !hasShellExpansion(target);
2183
- cwds[segment.depth] = !literal
2184
- ? null
2185
- : from === null
2186
- ? isAbsolute(target) ? resolve(target) : null
2187
- : resolve(from ?? ".", target);
2487
+ followCd &&
2488
+ !unreliable &&
2489
+ invocation.name === "cd" &&
2490
+ targets.length === 1 &&
2491
+ targets[0] !== "-" &&
2492
+ target !== undefined;
2493
+ cwds[segment.depth] =
2494
+ !literal || target === undefined
2495
+ ? null
2496
+ : from === null
2497
+ ? isAbsolute(target) ? resolve(target) : null
2498
+ : resolve(from ?? ".", target);
2188
2499
  moved[segment.depth] = true;
2189
2500
  continue;
2190
2501
  }
2191
2502
 
2192
2503
  const gitReason = matchGit(segment.tokens, invocation, gitContext);
2193
2504
  if (gitReason) return gitReason;
2505
+ const worktree = addedWorktreePath(segment.tokens, invocation, gitContext);
2506
+ if (worktree !== undefined) effects.addedWorktrees.push(worktree);
2507
+ effects.relinked.push(...relinkedPaths(segment.tokens, invocation, segmentCwd, scope));
2194
2508
  const linuxGitReason = matchLinuxGitOnWindowsDrive(segment.tokens, invocation, context, segmentCwd, windowsShell);
2195
2509
  if (linuxGitReason) return linuxGitReason;
2196
2510
 
@@ -2222,18 +2536,52 @@ function matchBlockedCommandInternal(
2222
2536
  return undefined;
2223
2537
  }
2224
2538
 
2539
+ /**
2540
+ * 역슬래시를 POSIX처럼 벗긴다. 따옴표 밖의 `\x`만 벗기고(`g\it` → `git`), 작은따옴표·큰따옴표 안, 주석, heredoc 본문은 그대로
2541
+ * 둔다: 큰따옴표 안 `\"`를 벗기면 따옴표가 일찍 닫혀 grep 패턴의 `|`가 파이프로 읽힌다(2026-10-23 grep 오탐). 큰따옴표 안의 글과
2542
+ * heredoc 본문이 하위 셸 스크립트로 쓰이면 그 스크립트를 판정할 때 다시 벗긴다(matchWithUnescape). `\$`·`\``는 치환이 일어나지
2543
+ * 않게 막은 것이고, heredoc 구분자 낱말(`<<\EOF`, `<<E\OF`, `<<'E'OF`)의 `\`·따옴표는 본문을 확장 없이 두라는 표시라 벗기지 않는다.
2544
+ */
2225
2545
  function unescapePosix(command: string): string {
2226
2546
  let result = "";
2547
+ let quote: "'" | '"' | undefined;
2548
+ let pending: Heredoc[] = [];
2227
2549
  for (let index = 0; index < command.length; index += 1) {
2228
- const character = command[index];
2550
+ const character = command[index]!;
2551
+ if (quote) {
2552
+ result += character;
2553
+ if (character === quote) quote = undefined;
2554
+ else if (quote === '"' && character === "\\" && index + 1 < command.length) result += command[(index += 1)];
2555
+ continue;
2556
+ }
2557
+ if (character === "\n" && pending.length > 0) {
2558
+ const end = readHeredocBodies(command, index + 1, pending);
2559
+ result += command.slice(index, end);
2560
+ index = end - 1;
2561
+ pending = [];
2562
+ continue;
2563
+ }
2564
+ if (character === "'" || character === '"') {
2565
+ quote = character;
2566
+ result += character;
2567
+ continue;
2568
+ }
2569
+ if (character === "#" && (index === 0 || /[\s;&|()]/.test(command[index - 1]!))) {
2570
+ const newline = command.indexOf("\n", index);
2571
+ const end = newline < 0 ? command.length : newline;
2572
+ result += command.slice(index, end);
2573
+ index = end - 1;
2574
+ continue;
2575
+ }
2229
2576
  if (character === "<" && command[index + 1] === "<" && command[index + 2] !== "<" && command[index - 1] !== "<") {
2230
- const wordStart = heredocWordStart(command, index + 2).index;
2231
- const wordEnd = scanHeredocWord(command, wordStart).end;
2577
+ const read = readHeredocDelimiter(command, index + 2);
2578
+ const wordEnd = read?.end ?? heredocWordStart(command, index + 2).index;
2579
+ if (read) pending.push(read.heredoc);
2232
2580
  result += command.slice(index, wordEnd);
2233
2581
  index = wordEnd - 1;
2234
2582
  continue;
2235
2583
  }
2236
- if (character === "\\" && index + 1 < command.length && !/[\r\n$`]/.test(command[index + 1])) {
2584
+ if (character === "\\" && index + 1 < command.length && !/[\r\n$`]/.test(command[index + 1]!)) {
2237
2585
  result += command[index + 1];
2238
2586
  index += 1;
2239
2587
  continue;
@@ -2243,16 +2591,31 @@ function unescapePosix(command: string): string {
2243
2591
  return result;
2244
2592
  }
2245
2593
 
2246
- export function matchBlockedCommand(
2594
+ /** 그대로 한 번, 역슬래시를 벗겨 한 번 판정한다. 하위 스크립트도 같은 두 판정을 거친다. */
2595
+ function matchWithUnescape(
2247
2596
  command: string,
2248
- context?: GuardContext,
2597
+ depth: number,
2598
+ context: SegmentContext | undefined,
2599
+ windowsShell: boolean,
2600
+ effects: CommandEffects,
2249
2601
  ): string | undefined {
2250
- const directReason = matchBlockedCommandInternal(command, 0, context, false);
2602
+ const directReason = matchBlockedCommandInternal(command, depth, context, windowsShell, effects);
2251
2603
  if (directReason) return directReason;
2252
-
2253
- // 역슬래시를 POSIX처럼 벗긴 2차 판정. `\$`·`\``는 치환이 일어나지 않게 막은 것이고, heredoc 구분자 낱말(`<<\EOF`,
2254
- // `<<E\OF`, `<<'E'OF`)의 `\`·따옴표는 본문을 확장 없이 그대로 두라는 표시라 둘 다 벗기지 않는다.
2255
2604
  const posixUnescaped = unescapePosix(command);
2256
2605
  if (posixUnescaped === command) return undefined;
2257
- return matchBlockedCommandInternal(posixUnescaped, 0, context, false);
2606
+ // 첫 판정이 모은 바뀐 위치가 남아 있어 둘째 판정은 그만큼 보수적이다.
2607
+ return matchBlockedCommandInternal(posixUnescaped, depth, context, windowsShell, effects);
2608
+ }
2609
+
2610
+ export function matchBlockedCommand(
2611
+ command: string,
2612
+ context?: GuardContext,
2613
+ ): string | undefined {
2614
+ // 역슬래시·따옴표로 낱말을 쪼갠 것(`.g\it`, `.g'i't`)도 셸이 붙이므로 뺀 글로도 본다.
2615
+ const plain = command.replace(/[\\'"]/g, "");
2616
+ return matchWithUnescape(command, 0, context, false, {
2617
+ addedWorktrees: [],
2618
+ relinked: [],
2619
+ repositoryRedirect: REPOSITORY_REDIRECT.test(command) || REPOSITORY_REDIRECT.test(plain),
2620
+ });
2258
2621
  }