@cortex-agent/server 2026.6.18-2 → 2026.6.22
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/defaults/CORTEX.md +5 -0
- package/defaults/hooks/ask-user-question-hook.mjs +6 -1
- package/defaults/hooks/exit-plan-mode-hook.mjs +6 -1
- package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +7 -0
- package/defaults/prompts/systemPrompts/coder.md +6 -1
- package/defaults/prompts/systemPrompts/direct.md +5 -0
- package/defaults/prompts/systemPrompts/web-opus-4-6.md +6 -1
- package/defaults/prompts/systemPrompts/web-sonnet-4-6.md +6 -1
- package/defaults/prompts/systemPrompts/web.md +6 -1
- package/defaults/prompts/systemPrompts/worker.md +6 -1
- package/dist/agent-adapter/claude/adapter.d.ts +110 -1
- package/dist/agent-adapter/claude/adapter.js +117 -0
- package/dist/agent-adapter/claude/bg-task-tracker.d.ts +37 -0
- package/dist/agent-adapter/claude/bg-task-tracker.js +78 -0
- package/dist/agent-adapter/normalize/event-types.d.ts +4 -0
- package/dist/agent-adapter/pi/event-parser.d.ts +3 -1
- package/dist/agent-adapter/pi/event-parser.js +12 -2
- package/dist/agent-adapter/types.d.ts +19 -0
- package/dist/core/auth.d.ts +36 -0
- package/dist/core/auth.js +85 -0
- package/dist/core/locales/en.d.ts +6 -0
- package/dist/core/locales/slices/status.d.ts +6 -0
- package/dist/core/locales/slices/status.js +16 -0
- package/dist/core/types/agent-types.d.ts +5 -0
- package/dist/core/types/thread-types.d.ts +12 -1
- package/dist/core/version.d.ts +3 -0
- package/dist/core/version.js +4 -1
- package/dist/domain/agents/facade.js +12 -0
- package/dist/domain/costs/rate-limit-throttle.d.ts +1 -1
- package/dist/domain/costs/rate-limit-throttle.js +23 -2
- package/dist/domain/costs/resume-registry.d.ts +30 -0
- package/dist/domain/costs/resume-registry.js +68 -0
- package/dist/domain/mcp/core-server.js +5 -0
- package/dist/domain/mcp/tools/manager-qa.d.ts +2 -0
- package/dist/domain/mcp/tools/manager-qa.js +72 -0
- package/dist/domain/mcp/tools/task-ops.js +4 -2
- package/dist/domain/mcp/tools/thread-ops.js +2 -1
- package/dist/domain/mcp/tui-server.js +2 -1
- package/dist/domain/remote/client-bootstrap.js +14 -2
- package/dist/domain/remote/client-manager.d.ts +1 -1
- package/dist/domain/remote/client-manager.js +31 -5
- package/dist/domain/remote/cortex-client-config.d.ts +32 -0
- package/dist/domain/remote/cortex-client-config.js +49 -0
- package/dist/domain/remote/cortex-client.js +11 -7
- package/dist/domain/scheduling/jobs/scheduled-task.js +17 -1
- package/dist/domain/scheduling/jobs/task-dispatch.js +21 -0
- package/dist/domain/tasks/dispatcher.js +8 -0
- package/dist/domain/tasks/system/cortex-run.js +4 -2
- package/dist/domain/threads/runner.d.ts +8 -1
- package/dist/domain/threads/runner.js +81 -11
- package/dist/domain/threads/state-machine.d.ts +5 -0
- package/dist/domain/threads/state-machine.js +16 -0
- package/dist/entry/app.js +19 -4
- package/dist/entry/init.js +6 -0
- package/dist/hooks/ask-user-question-hook.mjs +6 -1
- package/dist/hooks/exit-plan-mode-hook.mjs +6 -1
- package/dist/orchestration/agent-runner.js +28 -3
- package/dist/orchestration/bg-continuation.d.ts +26 -0
- package/dist/orchestration/bg-continuation.js +34 -0
- package/dist/orchestration/conversation-runner.d.ts +3 -0
- package/dist/orchestration/conversation-runner.js +1 -1
- package/dist/orchestration/interactions/interaction-handlers.js +13 -2
- package/dist/orchestration/lifecycle.d.ts +3 -1
- package/dist/orchestration/lifecycle.js +72 -2
- package/dist/orchestration/manager-qa.d.ts +55 -0
- package/dist/orchestration/manager-qa.js +218 -0
- package/dist/orchestration/resume-dispatcher.d.ts +22 -0
- package/dist/orchestration/resume-dispatcher.js +129 -0
- package/dist/orchestration/routing/webhook.d.ts +1 -1
- package/dist/orchestration/routing/webhook.js +75 -14
- package/dist/orchestration/status-helpers.d.ts +3 -0
- package/dist/orchestration/status-helpers.js +16 -0
- package/dist/orchestration/thread-callback.d.ts +13 -1
- package/dist/orchestration/thread-callback.js +18 -1
- package/dist/orchestration/turn-notify.d.ts +26 -0
- package/dist/orchestration/turn-notify.js +66 -0
- package/dist/store/schedule-repo.d.ts +6 -0
- package/dist/store/schedule-repo.js +11 -1
- package/dist/store/thread-repo.js +14 -0
- package/dist/store/version-migrations.d.ts +14 -4
- package/dist/store/version-migrations.js +67 -9
- package/package.json +1 -1
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// input: orch/bg-continuation(isInteractiveChannel), store/outbound-queue(durablePost,getOutboundQueue), core/status-format(buildSessionTag), core/icons, core/i18n
|
|
2
|
+
// output: isTurnNotifyEnabled / getTurnNotifyThresholdS / maybeNotifyTurnComplete
|
|
3
|
+
// pos: orch layer — push a NEW message (Slack + Feishu) when a long-running user turn finishes
|
|
4
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
+
import { createLogger } from '../core/log.js';
|
|
6
|
+
import { Icons } from '../core/icons.js';
|
|
7
|
+
import { t } from '../core/i18n.js';
|
|
8
|
+
import { buildSessionTag } from '../core/status-format.js';
|
|
9
|
+
import { getOutboundQueue, durablePost } from '../store/outbound-queue.js';
|
|
10
|
+
import { isInteractiveChannel } from './bg-continuation.js';
|
|
11
|
+
const log = createLogger('turn-notify');
|
|
12
|
+
const DEFAULT_THRESHOLD_S = 60;
|
|
13
|
+
/** Feature gate: turn-completion notification is ON by default. Opt out by setting
|
|
14
|
+
* CORTEX_TURN_NOTIFY to a falsy value (0 / false / off / no). */
|
|
15
|
+
export function isTurnNotifyEnabled() {
|
|
16
|
+
const v = process.env.CORTEX_TURN_NOTIFY;
|
|
17
|
+
if (v === undefined)
|
|
18
|
+
return true;
|
|
19
|
+
return !['0', 'false', 'off', 'no'].includes(v.trim().toLowerCase());
|
|
20
|
+
}
|
|
21
|
+
/** Minimum turn duration (seconds) before a completion notification is pushed.
|
|
22
|
+
* Configurable via CORTEX_TURN_NOTIFY_THRESHOLD_S; defaults to 60s. A non-positive
|
|
23
|
+
* or unparseable value falls back to the default. */
|
|
24
|
+
export function getTurnNotifyThresholdS() {
|
|
25
|
+
const raw = process.env.CORTEX_TURN_NOTIFY_THRESHOLD_S;
|
|
26
|
+
if (raw === undefined)
|
|
27
|
+
return DEFAULT_THRESHOLD_S;
|
|
28
|
+
const n = Number(raw.trim());
|
|
29
|
+
if (!Number.isFinite(n) || n <= 0)
|
|
30
|
+
return DEFAULT_THRESHOLD_S;
|
|
31
|
+
return n;
|
|
32
|
+
}
|
|
33
|
+
/** Push a NEW message to the conversation's channel when a long-running, user-initiated
|
|
34
|
+
* turn finishes — so the user gets an actual push notification (editing the status
|
|
35
|
+
* message to "✓ Done" does not notify on Slack or Feishu). Works for both Slack and
|
|
36
|
+
* Feishu through the PlatformAdapter abstraction (Composite fans out to both).
|
|
37
|
+
*
|
|
38
|
+
* Gated by: feature flag, interactive-channel scope, and a duration threshold.
|
|
39
|
+
* Never throws — a failed notification must not affect the main turn. */
|
|
40
|
+
export async function maybeNotifyTurnComplete(params) {
|
|
41
|
+
const { adapter, channel, threadAnchorId, sessionName, sessionId, elapsedS, elapsedStr, status, metricsSuffix } = params;
|
|
42
|
+
try {
|
|
43
|
+
if (!isTurnNotifyEnabled())
|
|
44
|
+
return;
|
|
45
|
+
if (!isInteractiveChannel(channel))
|
|
46
|
+
return;
|
|
47
|
+
if (elapsedS < getTurnNotifyThresholdS())
|
|
48
|
+
return;
|
|
49
|
+
const sessionTag = buildSessionTag(sessionName, sessionId);
|
|
50
|
+
const text = status === 'completed'
|
|
51
|
+
? `${Icons.ok} ${t('notify.turnComplete')} | ${sessionTag}(${elapsedStr}${metricsSuffix ?? ''})`
|
|
52
|
+
: `${Icons.error} ${t('notify.turnFailed')} | ${sessionTag}(${elapsedStr})`;
|
|
53
|
+
const dest = { type: 'interactive-reply', conduit: channel, sessionId: sessionId ?? '' };
|
|
54
|
+
const opts = threadAnchorId ? { threadId: threadAnchorId } : undefined;
|
|
55
|
+
const queue = getOutboundQueue();
|
|
56
|
+
if (queue) {
|
|
57
|
+
await durablePost(queue, adapter, dest, { text }, opts);
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
await adapter.postMessage(dest, { text }, opts);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
catch (err) {
|
|
64
|
+
log.warn('turn-complete notification failed:', err?.message ?? err);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { ResumeEntry } from '../domain/costs/resume-registry.js';
|
|
1
2
|
export declare const SCHEDULES_FILE: string;
|
|
2
3
|
export declare const CHANNEL_REGISTRY_FILE: string;
|
|
3
4
|
/** Where a fired scheduled-task should land. Resolved by the cortex_schedule_add MCP tool
|
|
@@ -54,6 +55,9 @@ export interface SchedulesData {
|
|
|
54
55
|
activatedAt: number;
|
|
55
56
|
modes?: string[];
|
|
56
57
|
} | null;
|
|
58
|
+
/** Sessions/threads interrupted by a rate limit, awaiting auto-resume when the
|
|
59
|
+
* window resets. Owned by domain/costs/resume-registry.ts. */
|
|
60
|
+
resumeQueue?: ResumeEntry[] | null;
|
|
57
61
|
}
|
|
58
62
|
/** Convenience: reverse-lookup projectId from a Slack channel via channel-registry.json. */
|
|
59
63
|
export declare function channelToProjectId(channel: string): string | null;
|
|
@@ -76,6 +80,8 @@ export declare class ScheduleRepo {
|
|
|
76
80
|
activatedAt: number;
|
|
77
81
|
modes?: string[];
|
|
78
82
|
} | null>;
|
|
83
|
+
setResumeQueue(entries: ResumeEntry[] | null): Promise<void>;
|
|
84
|
+
getResumeQueue(): Promise<ResumeEntry[]>;
|
|
79
85
|
/** Generic mutate passthrough for composite operations. */
|
|
80
86
|
mutate<R>(fn: (data: SchedulesData) => {
|
|
81
87
|
next: SchedulesData;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// input: schedules.json + channel-registry.json + JsonRepository
|
|
2
|
-
// output: ScheduleRepo (read / addTask / removeTask / updateTask / rateLimitThrottle) + migration helpers
|
|
2
|
+
// output: ScheduleRepo (read / addTask / removeTask / updateTask / rateLimitThrottle / resumeQueue) + migration helpers
|
|
3
3
|
// pos: Schedule persistence layer. Based on JsonRepository abstraction (Pattern A), AsyncMutex serializes reads/writes of schedules.json.
|
|
4
4
|
// Migration from channel→projectId reads channel-registry.json synchronously for reverse lookup.
|
|
5
5
|
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
@@ -117,6 +117,16 @@ export class ScheduleRepo {
|
|
|
117
117
|
const data = await this._repo.read();
|
|
118
118
|
return data.rateLimitThrottle || null;
|
|
119
119
|
}
|
|
120
|
+
async setResumeQueue(entries) {
|
|
121
|
+
await this._repo.mutate((data) => {
|
|
122
|
+
data.resumeQueue = entries;
|
|
123
|
+
return { next: data, result: undefined };
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
async getResumeQueue() {
|
|
127
|
+
const data = await this._repo.read();
|
|
128
|
+
return data.resumeQueue ?? [];
|
|
129
|
+
}
|
|
120
130
|
/** Generic mutate passthrough for composite operations. */
|
|
121
131
|
async mutate(fn) {
|
|
122
132
|
return this._repo.mutate(fn);
|
|
@@ -155,6 +155,10 @@ class ThreadRepo {
|
|
|
155
155
|
|| record.metadata?.waitingOnTasks?.length);
|
|
156
156
|
if (isSuspendedParent)
|
|
157
157
|
continue;
|
|
158
|
+
// Rate-limit-paused threads survive restarts: the throttle re-arms its resume timer (or
|
|
159
|
+
// fires immediately if the window already passed) and resume-dispatcher re-enters them.
|
|
160
|
+
if (record.status === 'rate_limited')
|
|
161
|
+
continue;
|
|
158
162
|
if (record.status === 'running' || record.status === 'waiting') {
|
|
159
163
|
record.status = 'failed';
|
|
160
164
|
record.error = 'Interrupted by server restart';
|
|
@@ -196,6 +200,16 @@ class ThreadRepo {
|
|
|
196
200
|
record.updatedAt = new Date().toISOString();
|
|
197
201
|
staleWaiting++;
|
|
198
202
|
}
|
|
203
|
+
// Limbo safety net: a rate-limit-paused thread that never got resumed (auto-resume
|
|
204
|
+
// disabled, or the window-reset resume was dropped) is failed once past maxAge so it
|
|
205
|
+
// does not linger forever.
|
|
206
|
+
if (record.status === 'rate_limited' && record.updatedAt < cutoff) {
|
|
207
|
+
record.status = 'failed';
|
|
208
|
+
record.error = 'rate-limit-paused thread never resumed';
|
|
209
|
+
record.endedAt = new Date().toISOString();
|
|
210
|
+
record.updatedAt = new Date().toISOString();
|
|
211
|
+
staleWaiting++;
|
|
212
|
+
}
|
|
199
213
|
}
|
|
200
214
|
if (staleWaiting > 0)
|
|
201
215
|
log.info(`Failed ${staleWaiting} stale waiting threads (leak safety net)`);
|
|
@@ -5,12 +5,22 @@ export interface Migration {
|
|
|
5
5
|
/** CalVer when this migration was introduced. Compared against the per-file
|
|
6
6
|
* version tracked in versions.json to decide whether to run. */
|
|
7
7
|
version: string;
|
|
8
|
-
/**
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
|
|
8
|
+
/** Target file format. 'json' (default) parses/serializes JSON; 'text' passes
|
|
9
|
+
* the raw file contents (string) through unchanged. Determines how the runner
|
|
10
|
+
* reads, diffs, and writes the file. */
|
|
11
|
+
format?: 'json' | 'text';
|
|
12
|
+
/** Idempotent migration function. For 'json' migrations, receives the parsed JSON
|
|
13
|
+
* of the target file and optionally the parsed JSON of the corresponding defaults
|
|
14
|
+
* file. For 'text' migrations, receives the raw file string and optionally the raw
|
|
15
|
+
* defaults string. Must return the migrated data (object for json, string for text)
|
|
16
|
+
* — the runner compares before/after to decide whether to write. */
|
|
12
17
|
migrate(data: unknown, defaults?: unknown): unknown;
|
|
13
18
|
}
|
|
19
|
+
/** Replace any existing `<!-- cortex:docs ... -->` … `<!-- /cortex:docs -->` region with
|
|
20
|
+
* `block`, or append `block` (separated by a blank line) when absent. Idempotent: feeding
|
|
21
|
+
* the output back in is a no-op. Matches any block version on the start marker so an old
|
|
22
|
+
* block is upgraded in place rather than duplicated. */
|
|
23
|
+
export declare function upsertMarkerBlock(content: string, block: string): string;
|
|
14
24
|
export interface MigrationOptions {
|
|
15
25
|
/** Override DATA_DIR (user config location). Defaults to the real CORTEX_HOME. */
|
|
16
26
|
dataDir?: string;
|
|
@@ -2,12 +2,14 @@
|
|
|
2
2
|
// output: runMigrations() — applies pending file migrations before config loading
|
|
3
3
|
// pos: Version-tracked file migration runner. Tracks per-file applied migration versions
|
|
4
4
|
// in DATA_DIR/data/versions.json; on startup compares against CORTEX_VERSION and
|
|
5
|
-
// runs pending migrations in version order.
|
|
5
|
+
// runs pending migrations in version order. Supports JSON (parse/serialize) and text
|
|
6
|
+
// (raw string, e.g. markdown system prompts) migrations. Idempotent and crash-safe
|
|
7
|
+
// via atomicWrite.
|
|
6
8
|
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
7
9
|
import * as path from 'node:path';
|
|
8
10
|
import * as fs from 'node:fs/promises';
|
|
9
11
|
import * as os from 'node:os';
|
|
10
|
-
import { CORTEX_VERSION } from '../core/version.js';
|
|
12
|
+
import { CORTEX_VERSION, CORTEX_DOCS_URL } from '../core/version.js';
|
|
11
13
|
import { DATA_DIR, DEFAULTS_DIR } from '../core/paths.js';
|
|
12
14
|
import { atomicWrite } from '../core/atomic-write.js';
|
|
13
15
|
import { createLogger } from '../core/log.js';
|
|
@@ -31,6 +33,33 @@ export function compareCalVer(a, b) {
|
|
|
31
33
|
return aMonth - bMonth;
|
|
32
34
|
return aDay - bDay;
|
|
33
35
|
}
|
|
36
|
+
// ── Marker-block helpers (text migrations) ─────────────────────
|
|
37
|
+
// Text migrations edit human-owned markdown (system prompts, CORTEX.md) without
|
|
38
|
+
// clobbering user customizations: a versioned, marker-delimited block is upserted
|
|
39
|
+
// (replaced in place if present, appended otherwise). Bumping the block version token
|
|
40
|
+
// makes a future migration replace an older block cleanly.
|
|
41
|
+
const DOCS_BLOCK_VERSION = 'v1';
|
|
42
|
+
const DOCS_MARKER_START = `<!-- cortex:docs ${DOCS_BLOCK_VERSION} -->`;
|
|
43
|
+
const DOCS_MARKER_END = '<!-- /cortex:docs -->';
|
|
44
|
+
/** The canonical Cortex-docs block inserted into system prompts and CORTEX.md. */
|
|
45
|
+
const DOCS_BLOCK = [
|
|
46
|
+
DOCS_MARKER_START,
|
|
47
|
+
'# Cortex documentation',
|
|
48
|
+
`For how to use Cortex — tasks, threads, scheduling, memory, skills, safety & approvals — consult the docs: ${CORTEX_DOCS_URL}`,
|
|
49
|
+
DOCS_MARKER_END,
|
|
50
|
+
].join('\n');
|
|
51
|
+
/** Replace any existing `<!-- cortex:docs ... -->` … `<!-- /cortex:docs -->` region with
|
|
52
|
+
* `block`, or append `block` (separated by a blank line) when absent. Idempotent: feeding
|
|
53
|
+
* the output back in is a no-op. Matches any block version on the start marker so an old
|
|
54
|
+
* block is upgraded in place rather than duplicated. */
|
|
55
|
+
export function upsertMarkerBlock(content, block) {
|
|
56
|
+
const re = /<!-- cortex:docs[^>]*-->[\s\S]*?<!-- \/cortex:docs -->/;
|
|
57
|
+
if (re.test(content)) {
|
|
58
|
+
return content.replace(re, block);
|
|
59
|
+
}
|
|
60
|
+
const trimmed = content.replace(/\s+$/, '');
|
|
61
|
+
return `${trimmed}\n\n${block}\n`;
|
|
62
|
+
}
|
|
34
63
|
// ── Registry ───────────────────────────────────────────────────
|
|
35
64
|
// Add new migrations here. The runner groups them by filePath and applies
|
|
36
65
|
// pending ones in version-ascending order.
|
|
@@ -166,6 +195,31 @@ const migrations = [
|
|
|
166
195
|
return out;
|
|
167
196
|
},
|
|
168
197
|
},
|
|
198
|
+
// M4: Inject the Cortex usage-docs block into the user's system prompts and CORTEX.md.
|
|
199
|
+
// These are user-owned copies seeded at `cortex init` with force=false, so editing the
|
|
200
|
+
// shipped defaults only reaches new installs — existing installs need this migration to
|
|
201
|
+
// pick up the docs URL. Uses upsertMarkerBlock (text format) so the block is inserted
|
|
202
|
+
// once and user customizations around it are preserved. Idempotent: re-runs are no-ops,
|
|
203
|
+
// and fresh installs (whose seeded files already carry the block from defaults) match the
|
|
204
|
+
// existing-block branch and are left unchanged. New files skip gracefully via ENOENT.
|
|
205
|
+
...[
|
|
206
|
+
'CORTEX.md',
|
|
207
|
+
'prompts/systemPrompts/direct.md',
|
|
208
|
+
'prompts/systemPrompts/web.md',
|
|
209
|
+
'prompts/systemPrompts/web-opus-4-6.md',
|
|
210
|
+
'prompts/systemPrompts/web-sonnet-4-6.md',
|
|
211
|
+
'prompts/systemPrompts/worker.md',
|
|
212
|
+
'prompts/systemPrompts/coder.md',
|
|
213
|
+
].map((filePath) => ({
|
|
214
|
+
filePath,
|
|
215
|
+
version: '2026.6.22',
|
|
216
|
+
format: 'text',
|
|
217
|
+
migrate(data) {
|
|
218
|
+
if (typeof data !== 'string')
|
|
219
|
+
return data;
|
|
220
|
+
return upsertMarkerBlock(data, DOCS_BLOCK);
|
|
221
|
+
},
|
|
222
|
+
})),
|
|
169
223
|
];
|
|
170
224
|
// ── Versions file I/O ──────────────────────────────────────────
|
|
171
225
|
async function loadVersionsFrom(filePath) {
|
|
@@ -201,14 +255,14 @@ async function saveVersionsTo(filePath, versions) {
|
|
|
201
255
|
const DEFAULTS_MAP = {
|
|
202
256
|
'config/thread-templates.json': 'config/thread-templates.json',
|
|
203
257
|
};
|
|
204
|
-
async function loadDefaultsForWith(filePath, defaultsDir) {
|
|
258
|
+
async function loadDefaultsForWith(filePath, defaultsDir, format = 'json') {
|
|
205
259
|
const defaultsRel = DEFAULTS_MAP[filePath];
|
|
206
260
|
if (!defaultsRel)
|
|
207
261
|
return undefined;
|
|
208
262
|
const defaultsPath = path.join(defaultsDir, defaultsRel);
|
|
209
263
|
try {
|
|
210
264
|
const raw = await fs.readFile(defaultsPath, 'utf8');
|
|
211
|
-
return JSON.parse(raw);
|
|
265
|
+
return format === 'text' ? raw : JSON.parse(raw);
|
|
212
266
|
}
|
|
213
267
|
catch (err) {
|
|
214
268
|
const e = err;
|
|
@@ -246,12 +300,15 @@ export async function runMigrations(opts = {}) {
|
|
|
246
300
|
.sort((a, b) => compareCalVer(a.version, b.version));
|
|
247
301
|
if (pending.length === 0)
|
|
248
302
|
continue;
|
|
303
|
+
// A file is either JSON or text — take the format from the pending migrations.
|
|
304
|
+
const format = pending.find(m => m.format === 'text') ? 'text' : 'json';
|
|
305
|
+
const serialize = (d) => (format === 'text' ? String(d) : JSON.stringify(d));
|
|
249
306
|
// Read target file
|
|
250
307
|
const absPath = path.join(dataDir, filePath);
|
|
251
308
|
let data;
|
|
252
309
|
try {
|
|
253
310
|
const raw = await fs.readFile(absPath, 'utf8');
|
|
254
|
-
data = JSON.parse(raw);
|
|
311
|
+
data = format === 'text' ? raw : JSON.parse(raw);
|
|
255
312
|
}
|
|
256
313
|
catch (err) {
|
|
257
314
|
const e = err;
|
|
@@ -266,12 +323,12 @@ export async function runMigrations(opts = {}) {
|
|
|
266
323
|
throw err;
|
|
267
324
|
}
|
|
268
325
|
// Load defaults once for this file (if any)
|
|
269
|
-
const defaultsData = await loadDefaultsForWith(filePath, defaultsDir);
|
|
326
|
+
const defaultsData = await loadDefaultsForWith(filePath, defaultsDir, format);
|
|
270
327
|
// Apply all pending migrations in version order
|
|
271
328
|
let changed = false;
|
|
272
329
|
let anyFailed = false;
|
|
273
330
|
for (const m of pending) {
|
|
274
|
-
const before =
|
|
331
|
+
const before = serialize(data);
|
|
275
332
|
try {
|
|
276
333
|
data = m.migrate(data, defaultsData);
|
|
277
334
|
}
|
|
@@ -281,13 +338,14 @@ export async function runMigrations(opts = {}) {
|
|
|
281
338
|
anyFailed = true;
|
|
282
339
|
break;
|
|
283
340
|
}
|
|
284
|
-
if (
|
|
341
|
+
if (serialize(data) !== before) {
|
|
285
342
|
log.info(`Migration ${m.version} applied to ${filePath}`);
|
|
286
343
|
changed = true;
|
|
287
344
|
}
|
|
288
345
|
}
|
|
289
346
|
if (changed) {
|
|
290
|
-
|
|
347
|
+
const out = format === 'text' ? String(data) : JSON.stringify(data, null, 2) + '\n';
|
|
348
|
+
await atomicWrite(absPath, out);
|
|
291
349
|
}
|
|
292
350
|
// Only bump the tracked version if ALL pending migrations succeeded.
|
|
293
351
|
// If any failed: we did not write the file (changed=false), so the data on
|
package/package.json
CHANGED