@tienne/gestalt 0.126.0 → 0.128.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CLAUDE.md +1 -0
  2. package/README.ko.md +15 -5
  3. package/README.md +19 -6
  4. package/dist/bin/gestalt.js +28 -3
  5. package/dist/bin/gestalt.js.map +1 -1
  6. package/dist/package.json +1 -1
  7. package/dist/plugin/.codex-plugin/plugin.json +1 -1
  8. package/dist/plugin/scripts/gestalt-cli.mjs +1 -0
  9. package/dist/src/agent-sync/config.d.ts +76 -0
  10. package/dist/src/agent-sync/config.d.ts.map +1 -0
  11. package/dist/src/agent-sync/config.js +55 -0
  12. package/dist/src/agent-sync/config.js.map +1 -0
  13. package/dist/src/agent-sync/doctor.d.ts +48 -0
  14. package/dist/src/agent-sync/doctor.d.ts.map +1 -0
  15. package/dist/src/agent-sync/doctor.js +150 -0
  16. package/dist/src/agent-sync/doctor.js.map +1 -0
  17. package/dist/src/agent-sync/format.d.ts +8 -0
  18. package/dist/src/agent-sync/format.d.ts.map +1 -0
  19. package/dist/src/agent-sync/format.js +81 -0
  20. package/dist/src/agent-sync/format.js.map +1 -0
  21. package/dist/src/agent-sync/fs-ops.d.ts +17 -0
  22. package/dist/src/agent-sync/fs-ops.d.ts.map +1 -0
  23. package/dist/src/agent-sync/fs-ops.js +79 -0
  24. package/dist/src/agent-sync/fs-ops.js.map +1 -0
  25. package/dist/src/agent-sync/inspect.d.ts +53 -0
  26. package/dist/src/agent-sync/inspect.d.ts.map +1 -0
  27. package/dist/src/agent-sync/inspect.js +106 -0
  28. package/dist/src/agent-sync/inspect.js.map +1 -0
  29. package/dist/src/agent-sync/orca.d.ts +33 -0
  30. package/dist/src/agent-sync/orca.d.ts.map +1 -0
  31. package/dist/src/agent-sync/orca.js +110 -0
  32. package/dist/src/agent-sync/orca.js.map +1 -0
  33. package/dist/src/agent-sync/paths.d.ts +20 -0
  34. package/dist/src/agent-sync/paths.d.ts.map +1 -0
  35. package/dist/src/agent-sync/paths.js +31 -0
  36. package/dist/src/agent-sync/paths.js.map +1 -0
  37. package/dist/src/agent-sync/revert.d.ts +41 -0
  38. package/dist/src/agent-sync/revert.d.ts.map +1 -0
  39. package/dist/src/agent-sync/revert.js +318 -0
  40. package/dist/src/agent-sync/revert.js.map +1 -0
  41. package/dist/src/agent-sync/run-store.d.ts +690 -0
  42. package/dist/src/agent-sync/run-store.d.ts.map +1 -0
  43. package/dist/src/agent-sync/run-store.js +241 -0
  44. package/dist/src/agent-sync/run-store.js.map +1 -0
  45. package/dist/src/agent-sync/sync.d.ts +79 -0
  46. package/dist/src/agent-sync/sync.d.ts.map +1 -0
  47. package/dist/src/agent-sync/sync.js +294 -0
  48. package/dist/src/agent-sync/sync.js.map +1 -0
  49. package/dist/src/agent-sync/targets.d.ts +35 -0
  50. package/dist/src/agent-sync/targets.d.ts.map +1 -0
  51. package/dist/src/agent-sync/targets.js +112 -0
  52. package/dist/src/agent-sync/targets.js.map +1 -0
  53. package/dist/src/cli/commands/agent-sync.d.ts +22 -0
  54. package/dist/src/cli/commands/agent-sync.d.ts.map +1 -0
  55. package/dist/src/cli/commands/agent-sync.js +85 -0
  56. package/dist/src/cli/commands/agent-sync.js.map +1 -0
  57. package/dist/src/cli/commands/update.d.ts +1 -0
  58. package/dist/src/cli/commands/update.d.ts.map +1 -1
  59. package/dist/src/cli/commands/update.js +19 -2
  60. package/dist/src/cli/commands/update.js.map +1 -1
  61. package/dist/src/cli/follow-plugin.d.ts +58 -0
  62. package/dist/src/cli/follow-plugin.d.ts.map +1 -0
  63. package/dist/src/cli/follow-plugin.js +250 -0
  64. package/dist/src/cli/follow-plugin.js.map +1 -0
  65. package/dist/src/cli/index.d.ts.map +1 -1
  66. package/dist/src/cli/index.js +20 -0
  67. package/dist/src/cli/index.js.map +1 -1
  68. package/package.json +1 -1
  69. package/plugin/.codex-plugin/plugin.json +1 -1
  70. package/plugin/.mcp.json +5 -2
  71. package/plugin/mcp.json +5 -2
  72. package/plugin/scripts/gestalt-cli.mjs +1 -0
@@ -0,0 +1,241 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
3
+ import { basename, join, relative } from 'node:path';
4
+ import { z } from 'zod';
5
+ import { gestaltPath } from '../core/home.js';
6
+ import { copyPath, movePath, removePath } from './fs-ops.js';
7
+ import { isInside } from './paths.js';
8
+ const RUN_DIR_PATTERN = /^\d{4}-\d{2}-\d{2}-[0-9a-f]{8}$/;
9
+ const stashAction = z.object({ op: z.literal('stash'), path: z.string(), backup: z.string() });
10
+ const moveAction = z.object({ op: z.literal('move'), from: z.string(), to: z.string() });
11
+ /** 되돌리기가 남기는 기록. 그 자리에 sync 뒤로 생긴 것을 치워둔 곳 */
12
+ const backupAction = z.object({ op: z.literal('backup'), path: z.string(), backup: z.string() });
13
+ const movingAction = z.discriminatedUnion('op', [stashAction, moveAction, backupAction]);
14
+ /**
15
+ * 실행 하나가 한 일. 되돌리기는 sync 실행의 이 목록을 거꾸로 읽는다.
16
+ * `backup`은 실행 폴더 안의 절대 경로다. `pending`은 옮기기 시작했지만 끝났다고 적기 전에 멈춘 동작이다.
17
+ */
18
+ const runAction = z.discriminatedUnion('op', [
19
+ z.object({ op: z.literal('mkdir'), path: z.string() }),
20
+ z.object({ op: z.literal('create_file'), path: z.string() }),
21
+ z.object({ op: z.literal('write_file'), path: z.string(), backup: z.string() }),
22
+ z.object({ op: z.literal('create_link'), path: z.string(), target: z.string() }),
23
+ moveAction,
24
+ stashAction,
25
+ backupAction,
26
+ z.object({ op: z.literal('pending'), action: movingAction }),
27
+ z.object({ op: z.literal('restore'), path: z.string() }),
28
+ z.object({ op: z.literal('remove'), path: z.string() }),
29
+ ]);
30
+ const runRecordSchema = z
31
+ .object({
32
+ version: z.literal(1),
33
+ runId: z.string().regex(/^[0-9a-f]{8}$/),
34
+ kind: z.enum(['sync', 'doctor', 'revert']),
35
+ createdAt: z.string().refine((v) => !Number.isNaN(Date.parse(v)), '날짜가 아니에요'),
36
+ /** 실행 폴더 이름. `<YYYY-MM-DD>-<runId>` */
37
+ dirName: z.string().regex(RUN_DIR_PATTERN),
38
+ actions: z.array(runAction),
39
+ /** 사람이 읽을 한 줄 요약. 출력에 보여준 것과 같다 */
40
+ changes: z.array(z.string()),
41
+ revertOf: z.string().optional(),
42
+ revertedAt: z.string().optional(),
43
+ revertedBy: z.string().optional(),
44
+ /** 되돌리기가 어디까지 했는지. 이 인덱스부터 끝까지의 동작은 되돌렸다 */
45
+ revertProgress: z.number().int().nonnegative().optional(),
46
+ })
47
+ .refine((r) => r.dirName.endsWith(`-${r.runId}`), {
48
+ message: 'dirName이 runId로 끝나지 않아요',
49
+ path: ['dirName'],
50
+ });
51
+ export const RUN_FILE = 'run.json';
52
+ export const RETENTION_MONTHS = 6;
53
+ export function backupsRoot() {
54
+ return gestaltPath('backups');
55
+ }
56
+ function localDate(d) {
57
+ const pad = (n) => String(n).padStart(2, '0');
58
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
59
+ }
60
+ /** 원래 경로 구조 그대로. 홈 아래는 `home/`, 그 밖은 `root/` 아래에 둔다 */
61
+ export function backupPathIn(dir, home, path) {
62
+ if (path !== home && isInside(home, path))
63
+ return join(dir, 'home', relative(home, path));
64
+ return join(dir, 'root', path.replace(/^[/\\]+/, '').replace(/:/g, ''));
65
+ }
66
+ /**
67
+ * 실행 폴더는 백업이 처음 들어오기 전에 0700으로 만든다. 옮기기가 부모 폴더를 먼저 만들면 umask 권한으로 생긴다.
68
+ * 이미 있던 폴더는 사용자가 정한 권한일 수 있어 건드리지 않는다.
69
+ */
70
+ function ensureRunDir(dir) {
71
+ if (existsSync(dir))
72
+ return;
73
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
74
+ chmodSync(dir, 0o700);
75
+ }
76
+ /** 임시 파일에 다 쓴 뒤 rename한다. 쓰다가 죽어도 run.json은 직전 내용 그대로 남는다 */
77
+ function writeRunFile(dir, record) {
78
+ const file = join(dir, RUN_FILE);
79
+ const tmp = `${file}.tmp`;
80
+ rmSync(tmp, { force: true });
81
+ writeFileSync(tmp, `${JSON.stringify(record, null, 2)}\n`, { mode: 0o600 });
82
+ renameSync(tmp, file);
83
+ }
84
+ /**
85
+ * 실행 하나의 백업 폴더와 기록 파일. 폴더는 처음 쓸 일이 생길 때 만든다.
86
+ * 바꾼 게 없는 실행은 흔적을 안 남긴다.
87
+ */
88
+ export class RunWriter {
89
+ home;
90
+ record;
91
+ dir;
92
+ constructor(kind, home, now = new Date(), revertOf) {
93
+ this.home = home;
94
+ const runId = randomBytes(4).toString('hex');
95
+ const dirName = `${localDate(now)}-${runId}`;
96
+ this.dir = join(backupsRoot(), dirName);
97
+ this.record = {
98
+ version: 1,
99
+ runId,
100
+ kind,
101
+ createdAt: now.toISOString(),
102
+ dirName,
103
+ actions: [],
104
+ changes: [],
105
+ ...(revertOf ? { revertOf } : {}),
106
+ };
107
+ }
108
+ get recordFile() {
109
+ return join(this.dir, RUN_FILE);
110
+ }
111
+ get touched() {
112
+ return this.record.actions.length > 0;
113
+ }
114
+ backupPathFor(path) {
115
+ return backupPathIn(this.dir, this.home, path);
116
+ }
117
+ /**
118
+ * 옮기기 전에 `pending`으로 먼저 적고 옮긴 뒤 완료로 바꾼다.
119
+ * 그 사이에 멈춰도 어디로 옮기려 했는지 기록에 남아 되돌리기가 찾아갈 수 있다.
120
+ */
121
+ recordMove(action, move) {
122
+ const at = this.record.actions.length;
123
+ this.log({ op: 'pending', action });
124
+ move();
125
+ this.record.actions[at] = action;
126
+ this.save();
127
+ }
128
+ /** 지금 자리에 있는 것을 백업 폴더로 옮긴다 */
129
+ moveToBackup(op, path) {
130
+ const backup = this.backupPathFor(path);
131
+ this.recordMove({ op, path, backup }, () => movePath(path, backup));
132
+ return backup;
133
+ }
134
+ copyToBackup(path) {
135
+ ensureRunDir(this.dir);
136
+ const backup = this.backupPathFor(path);
137
+ copyPath(path, backup);
138
+ return backup;
139
+ }
140
+ log(action) {
141
+ this.record.actions.push(action);
142
+ this.save();
143
+ }
144
+ /**
145
+ * 동작을 적을 때마다 저장한다. 프로세스가 죽어도 마지막으로 저장한 데까지는 run.json에 남는다.
146
+ * 옮기는 동작은 옮기기 전에 적으므로 저장한 기록이 실제보다 뒤처지지 않는다.
147
+ */
148
+ save() {
149
+ ensureRunDir(this.dir);
150
+ writeRunFile(this.dir, this.record);
151
+ }
152
+ }
153
+ /** 기록 파일이 없으면 null. 있는데 못 읽거나 형식이 틀리면 깨진 기록으로 돌려준다 */
154
+ export function readRun(dir) {
155
+ const file = join(dir, RUN_FILE);
156
+ if (!existsSync(file))
157
+ return null;
158
+ const dirName = basename(dir);
159
+ let raw;
160
+ try {
161
+ raw = JSON.parse(readFileSync(file, 'utf-8'));
162
+ }
163
+ catch (e) {
164
+ return { ok: false, dirName, reason: `JSON으로 읽지 못했어요: ${e.message}` };
165
+ }
166
+ const parsed = runRecordSchema.safeParse(raw);
167
+ if (!parsed.success) {
168
+ const detail = parsed.error.issues
169
+ .map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`)
170
+ .join('; ');
171
+ return { ok: false, dirName, reason: `형식이 맞지 않아요: ${detail}` };
172
+ }
173
+ if (parsed.data.dirName !== dirName) {
174
+ return {
175
+ ok: false,
176
+ dirName,
177
+ reason: `기록의 dirName ${parsed.data.dirName}이 폴더 이름과 달라요`,
178
+ };
179
+ }
180
+ return { ok: true, record: parsed.data };
181
+ }
182
+ export function writeRun(record) {
183
+ writeRunFile(runDir(record), record);
184
+ }
185
+ export function listRunsNewestFirst() {
186
+ const root = backupsRoot();
187
+ const listing = { runs: [], corrupt: [] };
188
+ if (!existsSync(root))
189
+ return listing;
190
+ for (const name of readdirSync(root)) {
191
+ if (!RUN_DIR_PATTERN.test(name))
192
+ continue;
193
+ const stored = readRun(join(root, name));
194
+ if (!stored)
195
+ continue;
196
+ if (stored.ok)
197
+ listing.runs.push(stored.record);
198
+ else
199
+ listing.corrupt.push({ dirName: stored.dirName, reason: stored.reason });
200
+ }
201
+ listing.runs.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
202
+ listing.corrupt.sort((a, b) => b.dirName.localeCompare(a.dirName));
203
+ return listing;
204
+ }
205
+ export function runDir(record) {
206
+ return join(backupsRoot(), record.dirName);
207
+ }
208
+ export function retentionCutoff(now) {
209
+ const cutoff = new Date(now);
210
+ cutoff.setMonth(cutoff.getMonth() - RETENTION_MONTHS);
211
+ return cutoff;
212
+ }
213
+ /**
214
+ * 보관 기간이 지난 실행 폴더를 지운다. sync와 `doctor --fix`는 시작할 때, 되돌리기는 끝난 뒤에 부른다.
215
+ * 아직 되돌리지 않은 가장 최근 sync 실행은 기간이 지나도 남긴다. 그게 없어지면 되돌릴 길이 없다.
216
+ * 읽지 못한 기록도 남긴다. 사람이 열어 볼 수 있게 두고 doctor와 되돌리기가 경고한다.
217
+ * 기록 파일이 없으면 폴더 이름의 날짜로 판단한다.
218
+ */
219
+ export function pruneRuns(now = new Date()) {
220
+ const root = backupsRoot();
221
+ if (!existsSync(root))
222
+ return [];
223
+ const cutoff = retentionCutoff(now).getTime();
224
+ const keep = listRunsNewestFirst().runs.find((r) => r.kind === 'sync' && !r.revertedAt)?.dirName;
225
+ const removed = [];
226
+ for (const name of readdirSync(root)) {
227
+ if (!RUN_DIR_PATTERN.test(name) || name === keep)
228
+ continue;
229
+ const dir = join(root, name);
230
+ const stored = readRun(dir);
231
+ if (stored && !stored.ok)
232
+ continue;
233
+ const created = Date.parse(stored?.record.createdAt ?? `${name.slice(0, 10)}T00:00:00`);
234
+ if (Number.isNaN(created) || created >= cutoff)
235
+ continue;
236
+ removePath(dir);
237
+ removed.push(name);
238
+ }
239
+ return removed;
240
+ }
241
+ //# sourceMappingURL=run-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-store.js","sourceRoot":"","sources":["../../../src/agent-sync/run-store.ts"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M,CAAC,EAAE;YAAE,SAAS;QACnC,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,MAAM,CAAC,SAAS,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,WAAW,CAAC,CAAC;QACxF,IAAI,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,OAAO,IAAI,MAAM;YAAE,SAAS;QACzD,UAAU,CAAC,GAAG,CAAC,CAAC;QAChB,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACrB,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC"}
@@ -0,0 +1,79 @@
1
+ import type { AgentSyncConfig } from './config.js';
2
+ import { type InspectedSlot } from './inspect.js';
3
+ import { type SourcePaths } from './paths.js';
4
+ import { RunWriter } from './run-store.js';
5
+ import type { Target } from './targets.js';
6
+ /** 계획 한 줄. dry-run은 `summary`만 보여주고 실제 실행은 `apply`를 부른다 */
7
+ export interface PlanStep {
8
+ summary: string;
9
+ apply(run: RunWriter): void;
10
+ }
11
+ export interface Plan {
12
+ steps: PlanStep[];
13
+ hints: string[];
14
+ }
15
+ export interface PlanContext {
16
+ home: string;
17
+ src: SourcePaths;
18
+ t: (path: string) => string;
19
+ }
20
+ export declare function planContext(home: string): PlanContext;
21
+ export declare function ensureDir(run: RunWriter, path: string): void;
22
+ /**
23
+ * 자리에 뭔가 있으면 백업으로 치우고 링크를 건다.
24
+ * 치울 것은 옮기기 전에 기록하고 새로 만든 것은 만든 뒤 바로 기록한다. 중간에 멈춰도 치운 것은 되돌릴 수 있다.
25
+ */
26
+ export declare function placeLink(run: RunWriter, path: string, target: string): void;
27
+ export declare function placeFile(run: RunWriter, path: string, content: string): void;
28
+ /** 있는 파일 내용을 바꾼다. 원래 내용은 백업에 복사해 두고 나서 쓴다 */
29
+ export declare function rewriteFile(run: RunWriter, path: string, content: string): void;
30
+ export interface SplitRules {
31
+ shared: string;
32
+ kept: string[];
33
+ }
34
+ /**
35
+ * CLAUDE.md를 공용 규칙과 Claude 쪽에 남길 줄로 나눈다.
36
+ * 코드 블록 밖의 `@` 가져오기 줄과 `claudeOnly`에 걸리는 줄이 Claude 쪽에 남고 나머지는 전부 공용이다.
37
+ */
38
+ export declare function splitClaudeRules(content: string, claudeOnly: string[]): SplitRules;
39
+ export declare function claudeRulesWithImport(kept: string[]): string;
40
+ export declare function withImportLine(content: string, line: string): string;
41
+ export interface SlotFixOptions {
42
+ /** sync는 실제 skills 폴더의 항목을 `~/.agents/skills`로 옮긴다. doctor는 폴더째 백업만 한다 */
43
+ mergeSkills: boolean;
44
+ /** 옮길 때 이름이 겹치는지 보려고 `~/.agents/skills`에 있게 될 이름을 모은다 */
45
+ sourceNames: Set<string>;
46
+ /** 내용이 이미 `~/.agents`로 가는 자리. 링크가 여기를 가리켰으면 '옮기지 않았다'고 알리지 않는다 */
47
+ handledPaths: string[];
48
+ }
49
+ /** 자리 하나를 고치는 단계. sync와 doctor --fix가 같이 쓴다 */
50
+ export declare function fixSlotSteps(slot: InspectedSlot, ctx: PlanContext, opts: SlotFixOptions): Plan;
51
+ export interface SyncInput {
52
+ home: string;
53
+ targets: Target[];
54
+ config: AgentSyncConfig;
55
+ }
56
+ /** 시스템 홈의 규칙 파일. 이 내용은 `~/.agents/AGENTS.md`에 들어가 있거나 그 파일을 가져오므로 링크가 여기를 가리켰어도 잃는 게 없다 */
57
+ export declare function systemHomeRules(targets: Target[]): string[];
58
+ export declare function planSync(input: SyncInput): Plan;
59
+ export interface ApplyResult {
60
+ changes: string[];
61
+ hints: string[];
62
+ pruned: string[];
63
+ run?: {
64
+ runId: string;
65
+ dir: string;
66
+ recordFile: string;
67
+ };
68
+ }
69
+ /**
70
+ * 계획을 실행한다. 단계가 에러를 던지면 실패한 단계를 changes에 더해 저장하고 기록 자리를 붙여 다시 던진다.
71
+ * 거기까지 한 동작은 이미 run.json에 있어 되돌리기가 읽는다.
72
+ */
73
+ export declare function applyPlan(plan: Plan, run: RunWriter): void;
74
+ export interface RunSyncOptions extends SyncInput {
75
+ dryRun: boolean;
76
+ now?: Date;
77
+ }
78
+ export declare function runSync(opts: RunSyncOptions): ApplyResult;
79
+ //# sourceMappingURL=sync.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sync.d.ts","sourceRoot":"","sources":["../../../src/agent-sync/sync.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAEnD,OAAO,EAAkB,KAAK,aAAa,EAAE,MAAM,cAAc,CAAC;AAClE,OAAO,EAA4C,KAAK,WAAW,EAAE,MAAM,YAAY,CAAC;AACxF,OAAO,EAAa,SAAS,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAE3C,2DAA2D;AAC3D,MAAM,WAAW,QAAQ;IACvB,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,GAAG,EAAE,SAAS,GAAG,IAAI,CAAC;CAC7B;AAED,MAAM,WAAW,IAAI;IACnB,KAAK,EAAE,QAAQ,EAAE,CAAC;IAClB,KAAK,EAAE,MAAM,EAAE,CAAC;CACjB;AAED,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,WAAW,CAAC;IACjB,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,CAAC;CAC7B;AAED,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW,CAErD;AAED,wBAAgB,SAAS,CAAC,GAAG,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAK5D;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,CAI5E;AAED,wBAAgB,SAAS,CAAC,GAAG,EAAE,SAAS,EAAE,IAAI,E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AAC;IAChB,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,GAAG,CAAC,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,GAAG,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE,CAAC;CAC1D;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,SAAS,GAAG,IAAI,CAe1D;AAED,MAAM,WAAW,cAAe,SAAQ,SAAS;IAC/C,MAAM,EAAE,OAAO,CAAC;IAChB,GAAG,CAAC,EAAE,IAAI,CAAC;CACZ;AAED,wBAAgB,OAAO,CAAC,IAAI,EAAE,cAAc,GAAG,WAAW,CAczD"}
@@ -0,0 +1,294 @@
1
+ import { mkdirSync, readdirSync, readFileSync, readlinkSync, realpathSync, symlinkSync, unlinkSync, writeFileSync, } from 'node:fs';
2
+ import { dirname, isAbsolute, join } from 'node:path';
3
+ import { lstatOrNull, linkTargetOf, movePath, pathExists, samePath } from './fs-ops.js';
4
+ import { inspectTargets } from './inspect.js';
5
+ import { SOURCE_IMPORT_LINE, sourcePaths, tildify } from './paths.js';
6
+ import { pruneRuns, RunWriter } from './run-store.js';
7
+ export function planContext(home) {
8
+ return { home, src: sourcePaths(home), t: (p) => tildify(p, home) };
9
+ }
10
+ export function ensureDir(run, path) {
11
+ if (lstatOrNull(path))
12
+ return;
13
+ ensureDir(run, dirname(path));
14
+ mkdirSync(path);
15
+ run.log({ op: 'mkdir', path });
16
+ }
17
+ /**
18
+ * 자리에 뭔가 있으면 백업으로 치우고 링크를 건다.
19
+ * 치울 것은 옮기기 전에 기록하고 새로 만든 것은 만든 뒤 바로 기록한다. 중간에 멈춰도 치운 것은 되돌릴 수 있다.
20
+ */
21
+ export function placeLink(run, path, target) {
22
+ if (lstatOrNull(path))
23
+ run.moveToBackup('stash', path);
24
+ symlinkSync(target, path);
25
+ run.log({ op: 'create_link', path, target });
26
+ }
27
+ export function placeFile(run, path, content) {
28
+ if (lstatOrNull(path))
29
+ run.moveToBackup('stash', path);
30
+ writeFileSync(path, content, { flag: 'wx' });
31
+ run.log({ op: 'create_file', path });
32
+ }
33
+ /** 있는 파일 내용을 바꾼다. 원래 내용은 백업에 복사해 두고 나서 쓴다 */
34
+ export function rewriteFile(run, path, content) {
35
+ const backup = run.copyToBackup(path);
36
+ run.log({ op: 'write_file', path, backup });
37
+ writeFileSync(path, content);
38
+ }
39
+ /** 상대 링크는 옮기면 엉뚱한 곳을 가리키니 옮긴 뒤 절대 경로로 다시 건다 */
40
+ function moveEntry(run, from, to) {
41
+ const st = lstatOrNull(from);
42
+ const relLink = st?.isSymbolicLink() && !isAbsolute(readlinkSync(from)) ? linkTargetOf(from) : null;
43
+ run.recordMove({ op: 'move', from, to }, () => movePath(from, to));
44
+ if (relLink) {
45
+ unlinkSync(to);
46
+ symlinkSync(relLink, to);
47
+ }
48
+ }
49
+ const FENCE = /^\s*(```|~~~)/;
50
+ /**
51
+ * CLAUDE.md를 공용 규칙과 Claude 쪽에 남길 줄로 나눈다.
52
+ * 코드 블록 밖의 `@` 가져오기 줄과 `claudeOnly`에 걸리는 줄이 Claude 쪽에 남고 나머지는 전부 공용이다.
53
+ */
54
+ export function splitClaudeRules(content, claudeOnly) {
55
+ const shared = [];
56
+ const kept = [];
57
+ let inFence = false;
58
+ for (const line of content.split('\n')) {
59
+ if (FENCE.test(line)) {
60
+ inFence = !inFence;
61
+ shared.push(line);
62
+ continue;
63
+ }
64
+ const trimmed = line.trim();
65
+ if (!inFence && trimmed === SOURCE_IMPORT_LINE)
66
+ continue;
67
+ if (!inFence && (trimmed.startsWith('@') || claudeOnly.some((s) => line.includes(s)))) {
68
+ kept.push(line);
69
+ continue;
70
+ }
71
+ shared.push(line);
72
+ }
73
+ const body = shared.join('\n').trim();
74
+ return { shared: body ? `${body}\n` : '', kept };
75
+ }
76
+ export function claudeRulesWithImport(kept) {
77
+ return `${[SOURCE_IMPORT_LINE, ...(kept.length > 0 ? ['', ...kept] : [])].join('\n')}\n`;
78
+ }
79
+ export function withImportLine(content, line) {
80
+ return content.trim() ? `${line}\n\n${content}` : `${line}\n`;
81
+ }
82
+ /** 자리 하나를 고치는 단계. sync와 doctor --fix가 같이 쓴다 */
83
+ export function fixSlotSteps(slot, ctx, opts) {
84
+ const { t } = ctx;
85
+ const label = slot.target.label;
86
+ const st = slot.status;
87
+ const steps = [];
88
+ const hints = [];
89
+ if (st.state === 'ok')
90
+ return { steps, hints };
91
+ if (slot.mode === 'import') {
92
+ if (st.state === 'missing') {
93
+ steps.push({
94
+ summary: `${label}: ${t(slot.path)}를 만들고 ${slot.importLine} 줄을 넣음`,
95
+ apply: (run) => placeFile(run, slot.path, `${slot.importLine}\n`),
96
+ });
97
+ }
98
+ else if (st.state === 'missing_import') {
99
+ steps.push({
100
+ summary: `${label}: ${t(slot.path)} 맨 위에 ${slot.importLine} 줄을 넣음`,
101
+ apply: (run) => rewriteFile(run, slot.path, withImportLine(readFileSync(slot.path, 'utf-8'), slot.importLine)),
102
+ });
103
+ }
104
+ else if (st.state === 'wrong_target' && lstatOrNull(realpathSync(slot.path))?.isFile()) {
105
+ // 링크가 가리키는 파일은 다른 호스트 것일 수 있어 건드리지 않는다. 내용을 가져와 이 자리에 새 파일로 둔다
106
+ const realFile = realpathSync(slot.path);
107
+ steps.push({
108
+ summary: `${label}: ${t(slot.path)} 링크를 백업하고 ${t(realFile)} 내용 위에 ${slot.importLine} 줄을 얹은 파일로 바꿈`,
109
+ apply: (run) => placeFile(run, slot.path, withImportLine(readFileSync(realFile, 'utf-8'), slot.importLine)),
110
+ });
111
+ }
112
+ else {
113
+ steps.push({
114
+ summary: `${label}: ${t(slot.path)}를 백업하고 ${slot.importLine} 줄만 든 파일로 바꿈`,
115
+ apply: (run) => placeFile(run, slot.path, `${slot.importLine}\n`),
116
+ });
117
+ }
118
+ return { steps, hints };
119
+ }
120
+ const to = t(slot.linkTo);
121
+ if (st.state === 'missing') {
122
+ steps.push({
123
+ summary: `${label}: ${t(slot.path)} → ${to} 링크를 만듦`,
124
+ apply: (run) => placeLink(run, slot.path, slot.linkTo),
125
+ });
126
+ return { steps, hints };
127
+ }
128
+ if (st.state === 'replaced_by_file' && st.isDir && slot.name === 'skills' && opts.mergeSkills) {
129
+ const entries = readdirSync(slot.path).sort();
130
+ const moves = [];
131
+ const stashes = [];
132
+ for (const name of entries) {
133
+ if (opts.sourceNames.has(name))
134
+ stashes.push(name);
135
+ else {
136
+ moves.push(name);
137
+ opts.sourceNames.add(name);
138
+ }
139
+ }
140
+ if (moves.length > 0) {
141
+ steps.push({
142
+ summary: `${label}: ${t(slot.path)}의 항목 ${moves.length}개를 ${to}로 옮김 (${moves.join(', ')})`,
143
+ apply: (run) => {
144
+ for (const name of moves)
145
+ moveEntry(run, join(slot.path, name), join(slot.linkTo, name));
146
+ },
147
+ });
148
+ }
149
+ if (stashes.length > 0) {
150
+ // 겹친 항목은 그 자리에 두고 아래 링크 걸기에서 폴더째 백업한다. 따로 치우면 같은 백업 자리를 두 번 쓴다
151
+ hints.push(`${label}: ${t(slot.path)}에는 ${to}에 이미 있는 ${stashes.join(', ')}가 남아 있어 ${to} 쪽을 남겼어요. 이쪽 것은 백업 폴더에만 있으니 필요하면 꺼내 ${to}에 직접 합쳐 주세요`);
152
+ }
153
+ steps.push({
154
+ summary: stashes.length > 0
155
+ ? `${label}: ${t(slot.path)}에는 ${to}에 이미 있는 ${stashes.length}개(${stashes.join(', ')})만 남아 있어 백업하고 ${to} 링크로 바꿈`
156
+ : `${label}: 빈 ${t(slot.path)}를 ${to} 링크로 바꿈`,
157
+ apply: (run) => placeLink(run, slot.path, slot.linkTo),
158
+ });
159
+ return { steps, hints };
160
+ }
161
+ if (st.state === 'replaced_by_file' && st.isDir && slot.name === 'skills') {
162
+ const extra = readdirSync(slot.path).filter((n) => !pathExists(join(slot.linkTo, n)));
163
+ if (extra.length > 0) {
164
+ hints.push(`${label}: ${to}에 없는 ${extra.join(', ')}는 백업 폴더에만 있어요. 필요하면 ${to}로 옮겨 주세요`);
165
+ }
166
+ }
167
+ if (st.state === 'wrong_target' && !opts.handledPaths.some((p) => samePath(p, st.linkTarget))) {
168
+ hints.push(`${label}: ${t(slot.path)}가 가리키던 ${t(st.linkTarget)} 내용은 옮기지 않았어요`);
169
+ }
170
+ if (st.state === 'replaced_by_file' && !st.isDir && slot.name === 'rules') {
171
+ hints.push(`${label}: 원래 ${t(slot.path)} 내용은 백업 폴더에만 있어요. 공용으로 쓸 줄이 있으면 ${to}에 옮겨 주세요`);
172
+ }
173
+ const what = st.state === 'broken_link'
174
+ ? '끊긴 링크'
175
+ : st.state === 'wrong_target'
176
+ ? '다른 곳을 가리키는 링크'
177
+ : st.state === 'replaced_by_file' && st.isDir
178
+ ? '실제 폴더'
179
+ : '실제 파일';
180
+ steps.push({
181
+ summary: `${label}: ${what}인 ${t(slot.path)}를 백업하고 ${to} 링크로 바꿈`,
182
+ apply: (run) => placeLink(run, slot.path, slot.linkTo),
183
+ });
184
+ return { steps, hints };
185
+ }
186
+ function sourceRulesPlan(input, ctx, systemClaude) {
187
+ const { src, t } = ctx;
188
+ const steps = [];
189
+ const hints = [];
190
+ const needRoot = !lstatOrNull(src.root);
191
+ const mkRoot = needRoot
192
+ ? [{ summary: `${t(src.root)} 폴더를 만듦`, apply: (run) => ensureDir(run, src.root) }]
193
+ : [];
194
+ if (lstatOrNull(src.rulesFile))
195
+ return { steps, hints, claudeHandled: false };
196
+ const claudeFile = systemClaude ? join(systemClaude.home, 'CLAUDE.md') : null;
197
+ const realFile = claudeFile && pathExists(claudeFile) ? realpathSync(claudeFile) : null;
198
+ if (!claudeFile || !realFile || !lstatOrNull(realFile)?.isFile()) {
199
+ steps.push(...mkRoot, {
200
+ summary: `옮길 CLAUDE.md가 없어 빈 ${t(src.rulesFile)}를 만듦`,
201
+ apply: (run) => placeFile(run, src.rulesFile, ''),
202
+ });
203
+ return { steps, hints, claudeHandled: false };
204
+ }
205
+ const split = splitClaudeRules(readFileSync(realFile, 'utf-8'), input.config.rules.claudeOnly);
206
+ const sharedLines = split.shared ? split.shared.trimEnd().split('\n').length : 0;
207
+ const isLink = lstatOrNull(claudeFile)?.isSymbolicLink() ?? false;
208
+ const keptWhat = split.kept.length > 0
209
+ ? `${SOURCE_IMPORT_LINE} 줄과 Claude 전용 줄 ${split.kept.length}개`
210
+ : `${SOURCE_IMPORT_LINE} 줄`;
211
+ const where = isLink ? `${t(claudeFile)}가 가리키는 ${t(realFile)}` : t(claudeFile);
212
+ steps.push(...mkRoot, {
213
+ summary: `${where}의 공용 규칙 ${sharedLines}줄로 ${t(src.rulesFile)}를 만듦`,
214
+ apply: (run) => placeFile(run, src.rulesFile, split.shared),
215
+ }, {
216
+ // 링크면 가리키는 파일은 그대로 두고 링크 자리에 새 파일을 둔다. 그 파일을 다른 호스트가 같이 볼 수 있다
217
+ summary: isLink
218
+ ? `${systemClaude.label}: ${t(claudeFile)} 링크를 백업하고 ${keptWhat}만 든 파일로 바꿈`
219
+ : `${systemClaude.label}: ${t(claudeFile)}를 ${keptWhat}로 바꿈`,
220
+ apply: (run) => isLink
221
+ ? placeFile(run, claudeFile, claudeRulesWithImport(split.kept))
222
+ : rewriteFile(run, claudeFile, claudeRulesWithImport(split.kept)),
223
+ });
224
+ if (split.kept.length > 0) {
225
+ hints.push(`Claude 쪽에 남긴 줄: ${split.kept.map((l) => l.trim()).join(' / ')}`);
226
+ }
227
+ return { steps, hints, claudeHandled: true };
228
+ }
229
+ /** 시스템 홈의 규칙 파일. 이 내용은 `~/.agents/AGENTS.md`에 들어가 있거나 그 파일을 가져오므로 링크가 여기를 가리켰어도 잃는 게 없다 */
230
+ export function systemHomeRules(targets) {
231
+ return targets
232
+ .filter((x) => x.scope === 'system')
233
+ .map((x) => join(x.home, x.kind === 'claude' ? 'CLAUDE.md' : 'AGENTS.md'));
234
+ }
235
+ export function planSync(input) {
236
+ const ctx = planContext(input.home);
237
+ const { src, t } = ctx;
238
+ const systemClaude = input.targets.find((x) => x.kind === 'claude' && x.scope === 'system');
239
+ const rules = sourceRulesPlan(input, ctx, systemClaude);
240
+ const steps = [...rules.steps];
241
+ const hints = [...rules.hints];
242
+ if (!lstatOrNull(src.skillsDir)) {
243
+ steps.push({
244
+ summary: `${t(src.skillsDir)} 폴더를 만듦`,
245
+ apply: (run) => ensureDir(run, src.skillsDir),
246
+ });
247
+ }
248
+ const handledPaths = systemHomeRules(input.targets);
249
+ const sourceNames = new Set(lstatOrNull(src.skillsDir)?.isDirectory() ? readdirSync(src.skillsDir) : []);
250
+ for (const slot of inspectTargets(input.targets, src)) {
251
+ // `~/.agents/AGENTS.md`를 처음 만들 때 시스템 CLAUDE.md는 위에서 같이 고쳤다
252
+ if (rules.claudeHandled && slot.target === systemClaude && slot.name === 'rules')
253
+ continue;
254
+ const fix = fixSlotSteps(slot, ctx, { mergeSkills: true, sourceNames, handledPaths });
255
+ steps.push(...fix.steps);
256
+ hints.push(...fix.hints);
257
+ }
258
+ return { steps, hints };
259
+ }
260
+ /**
261
+ * 계획을 실행한다. 단계가 에러를 던지면 실패한 단계를 changes에 더해 저장하고 기록 자리를 붙여 다시 던진다.
262
+ * 거기까지 한 동작은 이미 run.json에 있어 되돌리기가 읽는다.
263
+ */
264
+ export function applyPlan(plan, run) {
265
+ for (const step of plan.steps) {
266
+ try {
267
+ step.apply(run);
268
+ }
269
+ catch (e) {
270
+ run.record.changes.push(`(실패) ${step.summary}`);
271
+ run.save();
272
+ throw new Error(`${step.summary} 중에 멈췄어요: ${e.message}\n여기까지 한 일은 ${run.recordFile}에 있어요`, { cause: e });
273
+ }
274
+ run.record.changes.push(step.summary);
275
+ run.save();
276
+ }
277
+ }
278
+ export function runSync(opts) {
279
+ const plan = planSync(opts);
280
+ const changes = plan.steps.map((s) => s.summary);
281
+ if (opts.dryRun || plan.steps.length === 0)
282
+ return { changes, hints: plan.hints, pruned: [] };
283
+ const now = opts.now ?? new Date();
284
+ const pruned = pruneRuns(now);
285
+ const run = new RunWriter('sync', opts.home, now);
286
+ applyPlan(plan, run);
287
+ return {
288
+ changes,
289
+ hints: plan.hints,
290
+ pruned,
291
+ run: { runId: run.record.runId, dir: run.dir, recordFile: run.recordFile },
292
+ };
293
+ }
294
+ //# sourceMappingURL=sync.js.map