Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,9 @@ final class OfficeDriver {
let source = """
tell application id "com.microsoft.Excel"
set output to {}
repeat with wb in workbooks
set openWorkbooks to get every workbook
repeat with workbookRef in openWorkbooks
set wb to contents of workbookRef
set workbookPath to ""
try
set workbookPath to full name of wb as text
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/official-plugin-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ async function readMetadata(path: string): Promise<string> {

function safeRuntimePath(value: string): boolean {
return value.startsWith("runtime/") && !isAbsolute(value)
&& value.split("/").every((part) => /^[A-Za-z0-9_. -]+$/u.test(part) && part !== "." && part !== "..");
&& value.split("/").every((part) => /^[A-Za-z0-9_@. -]+$/u.test(part) && part !== "." && part !== "..");
}

async function listRuntimeFiles(root: string, directory: string, depth = 0): Promise<string[]> {
Expand Down
29 changes: 27 additions & 2 deletions packages/core/src/storage/sqlite/delegation-migration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,8 +226,7 @@ export function applyDelegationMigration(input: DelegationMigrationInput): boole
if (input.hasMigration(DELEGATION_MIGRATION_VERSION) !== recorded) {
throw new Error("Delegation migration marker state mismatch.");
}
const missing = inspectDefinitions(database, recorded);
if (recorded && missing.length === 0) {
if (recorded && inspectDefinitions(database, true).length === 0) {
assertPostconditions(database);
return false;
}
Expand All @@ -237,6 +236,7 @@ export function applyDelegationMigration(input: DelegationMigrationInput): boole
database.exec("BEGIN IMMEDIATE;");
try {
const currentMarker = readMigrationMarker(database);
if (!currentMarker) replaceEmptyDevelopmentDelegationTables(database);
const currentMissing = inspectDefinitions(database, currentMarker);
for (const definition of currentMissing) database.exec(definition.sql);
assertPostconditions(database);
Expand All @@ -253,6 +253,31 @@ export function applyDelegationMigration(input: DelegationMigrationInput): boole
}
}

/** The 139 development schema stored budget counters inline and linked steps through delegation_roots. */
function replaceEmptyDevelopmentDelegationTables(database: DatabaseSync): void {
const legacyMarker = database.prepare("SELECT name FROM schema_migrations WHERE version=139").get()?.name;
if (legacyMarker !== "create_delegation_tree") return;
const budgetColumnEnd = stepColumns.indexOf("idempotency_key");
const legacyStepColumns = [...stepColumns.slice(0, budgetColumnEnd),
"consumed_token_count", "consumed_cost_micros", "consumed_wall_time_ms", "budget_settled_at", ...stepColumns.slice(budgetColumnEnd)];
const readColumns = database.prepare("SELECT name FROM pragma_table_info(?) ORDER BY cid");
for (const [table, columns] of [["delegation_steps", legacyStepColumns], ["delegation_messages", messageColumns]] as const) {
const actual = readColumns.all(table);
if (actual.length !== columns.length || actual.some((row, index) => row.name !== columns[index])) return;
}
if (!database.prepare(`SELECT 1 FROM pragma_foreign_key_list('delegation_steps')
WHERE "from"='root_run_id' AND "table"='delegation_roots' AND "to"='root_run_id'`).get()) return;

const exists = database.prepare("SELECT 1 FROM sqlite_schema WHERE type='table' AND name=?");
for (const table of ["delegation_steps", "delegation_messages", "delegation_roots", "delegation_operations", "delegation_message_deliveries"]) {
if (!exists.get(table)) return;
if (database.prepare(`SELECT 1 FROM ${table} LIMIT 1`).get()) {
throw new Error("Delegation migration cannot replace a populated historical development schema.");
}
}
database.exec("DROP TABLE delegation_messages; DROP TABLE delegation_steps;");
}

/** Reject both a conflicting version owner and a reused migration name at another version. */
function readMigrationMarker(database: DatabaseSync): boolean {
const rows = database.prepare("SELECT version, name FROM schema_migrations WHERE version = ? OR name = ?")
Expand Down
50 changes: 25 additions & 25 deletions packages/core/src/storage/sqlite/migrations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,7 @@ const AUTOMATION_MONITOR_SNAPSHOTS_MIGRATION_VERSION = 142;
const AUTOMATION_MONITOR_SNAPSHOTS_MIGRATION_NAME = "create_automation_monitor_snapshots";
const PLUGIN_DISTRIBUTION_FIELDS_MIGRATION_VERSION = 143;
const PLUGIN_DISTRIBUTION_FIELDS_MIGRATION_NAME = "add_plugin_distribution_fields";
const PLUGIN_DISTRIBUTION_FIELDS = ["artifact_id", "platform", "arch", "source_url", "catalog_version", "previous_version"] as const;

export function configureSqliteRunStoreDatabase(database: DatabaseSync): void {
database.exec(`
Expand Down Expand Up @@ -2456,31 +2457,13 @@ export function applySqliteRunStoreMigrations(context: SqliteRunStoreMigrationCo
}
}

const hasPluginDistributionFieldsMigration = context.hasMigration(PLUGIN_DISTRIBUTION_FIELDS_MIGRATION_VERSION);
if (!hasPluginDistributionFieldsMigration || !context.hasTable("managed_plugin_packages")) {
if (context.hasTable("managed_plugin_packages")) {
if (!context.hasColumn("managed_plugin_packages", "artifact_id")) {
database.exec("ALTER TABLE managed_plugin_packages ADD COLUMN artifact_id TEXT;");
}
if (!context.hasColumn("managed_plugin_packages", "platform")) {
database.exec("ALTER TABLE managed_plugin_packages ADD COLUMN platform TEXT;");
}
if (!context.hasColumn("managed_plugin_packages", "arch")) {
database.exec("ALTER TABLE managed_plugin_packages ADD COLUMN arch TEXT;");
}
if (!context.hasColumn("managed_plugin_packages", "source_url")) {
database.exec("ALTER TABLE managed_plugin_packages ADD COLUMN source_url TEXT;");
}
if (!context.hasColumn("managed_plugin_packages", "catalog_version")) {
database.exec("ALTER TABLE managed_plugin_packages ADD COLUMN catalog_version TEXT;");
}
if (!context.hasColumn("managed_plugin_packages", "previous_version")) {
database.exec("ALTER TABLE managed_plugin_packages ADD COLUMN previous_version TEXT;");
}
}
if (!hasPluginDistributionFieldsMigration) {
context.recordMigration(PLUGIN_DISTRIBUTION_FIELDS_MIGRATION_VERSION, PLUGIN_DISTRIBUTION_FIELDS_MIGRATION_NAME);
}
// Historical development profiles can already record compaction recovery at 143.
const packageColumns = new Set(database.prepare("PRAGMA table_info(managed_plugin_packages)").all().map(row => row.name));
for (const field of PLUGIN_DISTRIBUTION_FIELDS) {
if (!packageColumns.has(field)) database.exec(`ALTER TABLE managed_plugin_packages ADD COLUMN ${field} TEXT`);
}
if (!context.hasMigration(PLUGIN_DISTRIBUTION_FIELDS_MIGRATION_VERSION)) {
context.recordMigration(PLUGIN_DISTRIBUTION_FIELDS_MIGRATION_VERSION, PLUGIN_DISTRIBUTION_FIELDS_MIGRATION_NAME);
}

const hasSkillAwareRunMigration = context.hasMigration(SKILL_AWARE_RUN_MIGRATION_VERSION);
Expand Down Expand Up @@ -6145,6 +6128,23 @@ export function applySqliteRunStoreMigrations(context: SqliteRunStoreMigrationCo
hasTable: context.hasTable.bind(context),
recordMigration: context.recordMigration.bind(context),
});
// An archived cron definition with no runs can supply the metadata for its missing owner thread.
database.exec(`
INSERT INTO ling_threads (id, workspace_id, kind, channel_id, title, objective, status, created_at, updated_at, archived_at)
SELECT automation.thread_id, automation.workspace_id, 'automation', automation.channel_id, automation.title,
json_extract(automation.prompt_template_json, '$.promptMarkdown'),
'archived', automation.created_at, automation.updated_at, automation.updated_at
FROM automation_definitions AS automation
WHERE automation.status = 'archived' AND automation.automation_mode = 'cron'
AND automation.target_thread_id IS NULL AND automation.last_run_id IS NULL
AND automation.thread_id <> ''
AND CASE WHEN json_valid(automation.prompt_template_json)
THEN json_type(automation.prompt_template_json, '$.promptMarkdown') = 'text' ELSE 0 END
AND NOT EXISTS (SELECT 1 FROM ling_threads WHERE id = automation.thread_id)
AND NOT EXISTS (SELECT 1 FROM automation_runs WHERE automation_id = automation.id)
AND NOT EXISTS (SELECT 1 FROM automation_definitions AS other WHERE other.thread_id = automation.thread_id AND other.id <> automation.id)
AND NOT EXISTS (SELECT 1 FROM retention_tombstones WHERE entity_type = 'conversation-thread' AND entity_id = automation.thread_id)
`);
ensureHostCommandJournalIndex(database);
ensureLingTurnCursorIndexes(database);
applyHostOperationJournalMigration({
Expand Down
129 changes: 129 additions & 0 deletions packages/core/test/sqlite-legacy-upgrade.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import assert from "node:assert/strict";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { DatabaseSync } from "node:sqlite";
import test, { type TestContext } from "node:test";
import { createSqliteRunStore, DEFAULT_WORKSPACE_ID } from "../dist/index.js";
import { testDatabase } from "./support/sqlite-test-database.ts";

const now = "2026-10-01T00:00:00.000Z";

async function fixture(t: TestContext) {
const cwd = await mkdtemp(join(tmpdir(), "ling-legacy-upgrade-"));
const store = createSqliteRunStore(cwd);
t.after(async () => {
if (testDatabase(store).isOpen) store.close();
await rm(cwd, { recursive: true, force: true });
});
return { cwd, store };
}

test("startup restores a missing archived automation thread from its definition", async t => {
const { cwd, store } = await fixture(t);
const thread = store.createLingThread({ kind: "automation", title: "Archived check", objective: "Check status" }, now);
const definition = store.createAutomationDefinition({
threadId: thread.id, title: thread.title, kind: "custom_prompt", status: "archived", trigger: { type: "manual" },
target: { scope: "workspace", workspaceId: DEFAULT_WORKSPACE_ID, cwd },
promptTemplate: { templateVersion: 1, promptMarkdown: thread.objective, contextSelectors: [] },
executionPolicy: {}, outputPolicy: { destinations: [{ type: "automation_thread" }], artifactFormat: "markdown" },
}, now);
const database = testDatabase(store);
database.exec("PRAGMA foreign_keys=OFF");
database.prepare("DELETE FROM ling_threads WHERE id=?").run(thread.id);
assert.equal(database.prepare("PRAGMA foreign_key_check(automation_definitions)").all().length, 1);
store.close();

for (let attempt = 0; attempt < 2; attempt++) {
const reopened = createSqliteRunStore(cwd);
try {
assert.deepEqual(reopened.getAutomationDefinition(definition.id), definition);
const restored = reopened.getLingThread(thread.id);
assert.equal(restored?.status, "archived");
assert.equal(restored?.archivedAt, now);
assert.equal(restored?.kind, "automation");
assert.equal(restored?.title, thread.title);
assert.equal(restored?.objective, thread.objective);
assert.deepEqual(testDatabase(reopened).prepare("PRAGMA foreign_key_check").all(), []);
} finally { reopened.close(); }
}
});

test("startup repairs missing plugin package fields even when 143 records compaction recovery", async t => {
const { cwd, store } = await fixture(t);
const database = testDatabase(store);
database.exec(`
ALTER TABLE managed_plugin_packages DROP COLUMN artifact_id;
ALTER TABLE managed_plugin_packages DROP COLUMN platform;
ALTER TABLE managed_plugin_packages DROP COLUMN source_url;
ALTER TABLE managed_plugin_packages DROP COLUMN catalog_version;
ALTER TABLE managed_plugin_packages DROP COLUMN previous_version;
UPDATE schema_migrations SET name='create_runtime_compaction_recovery_evidence' WHERE version=143;
`);
database.prepare(`INSERT INTO managed_plugin_packages (plugin_id, source_kind, version, status, cache_ref, arch,
manifest_json, installed_at, updated_at) VALUES ('official:pdf-documents','official-remote','0.1.0','installed',
'official-remote/pdf-documents', 'arm64', '{}', ?, ?)`).run(now, now);
const marker = database.prepare("SELECT * FROM schema_migrations WHERE version=143").get();
assert.equal(marker?.name, "create_runtime_compaction_recovery_evidence");
store.close();

const reopened = createSqliteRunStore(cwd);
try {
const plugin = reopened.getManagedPluginPackage("official:pdf-documents");
assert.equal(plugin?.status, "installed");
assert.equal(plugin?.version, "0.1.0");
assert.equal(plugin?.arch, "arm64");
assert.equal(plugin?.installedAt, now);
assert.deepEqual(testDatabase(reopened).prepare("SELECT * FROM schema_migrations WHERE version=143").get(), marker);
} finally { reopened.close(); }
});

for (const hasHistory of [false, true]) {
test(`startup ${hasHistory ? "preserves populated legacy delegation history on refusal" : "upgrades empty 139 delegation tables and reopens"}`, async t => {
const { cwd, store } = await fixture(t);
const path = store.paths.databasePath;
const database = testDatabase(store);
const table = database.prepare("SELECT sql FROM sqlite_schema WHERE type='table' AND name=?");
const steps = table.get("delegation_steps")?.sql;
const messages = table.get("delegation_messages")?.sql;
assert.ok(typeof steps === "string" && typeof messages === "string");
const legacySteps = steps
.replace("idempotency_key TEXT", `consumed_token_count INTEGER NOT NULL DEFAULT 0,
consumed_cost_micros INTEGER NOT NULL DEFAULT 0, consumed_wall_time_ms INTEGER NOT NULL DEFAULT 0,
budget_settled_at TEXT, idempotency_key TEXT`)
.replace("FOREIGN KEY(root_run_id) REFERENCES run_sessions(id)", "FOREIGN KEY(root_run_id) REFERENCES delegation_roots(root_run_id)");
database.exec(`PRAGMA foreign_keys=OFF;
DROP TABLE delegation_messages;
DROP TABLE delegation_steps;
CREATE TABLE delegation_roots (root_run_id TEXT PRIMARY KEY);
CREATE TABLE delegation_operations (id TEXT PRIMARY KEY, delegation_step_id TEXT REFERENCES delegation_steps(id));
CREATE TABLE delegation_message_deliveries (id TEXT PRIMARY KEY, delegation_message_id TEXT REFERENCES delegation_messages(id));
${legacySteps}; ${messages};
DELETE FROM schema_migrations WHERE version=154;
`);
database.prepare("INSERT INTO schema_migrations VALUES (139, 'create_delegation_tree', ?)").run(now);
if (hasHistory) database.exec("INSERT INTO delegation_roots VALUES ('retained-root')");
store.close();

if (hasHistory) {
assert.throws(() => createSqliteRunStore(cwd), /populated historical development schema/u);
const legacy = new DatabaseSync(path, { readOnly: true });
try {
assert.equal(legacy.prepare("SELECT root_run_id FROM delegation_roots").get()?.root_run_id, "retained-root");
assert.equal(legacy.prepare("SELECT 1 FROM schema_migrations WHERE version=154").get(), undefined);
} finally { legacy.close(); }
return;
}

for (let attempt = 0; attempt < 2; attempt++) {
const reopened = createSqliteRunStore(cwd);
try {
const migrated = testDatabase(reopened);
assert.equal(migrated.prepare("SELECT name FROM schema_migrations WHERE version=139").get()?.name, "create_delegation_tree");
assert.equal(migrated.prepare("SELECT name FROM schema_migrations WHERE version=154").get()?.name, "create_delegation_tree_v1");
assert.equal(migrated.prepare("SELECT 1 FROM delegation_steps LIMIT 1").get(), undefined);
assert.deepEqual(migrated.prepare("PRAGMA foreign_key_check").all(), []);
} finally { reopened.close(); }
}
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -57,18 +57,16 @@ export function resolveDocumentProcessingPluginAvailability(
};
}
if (process.env.LING_DOCUMENT_PROCESSING_MODE === "plugin") {
const getManagedPluginPackage = store?.getManagedPluginPackage;
const packageRecord = getManagedPluginPackage?.(pluginId);
if (getManagedPluginPackage && (!packageRecord || packageRecord.status !== "installed")) {
const packageRecord = store?.getManagedPluginPackage?.(pluginId);
if (store?.getManagedPluginPackage && packageRecord?.status !== "installed") {
return {
enabled: false,
errorCode: "document_processing_plugin_not_installed",
errorMessage: `${label} document processing package is not installed for this workspace.`,
};
}
const getManagedPluginHealthSnapshot = store?.getManagedPluginHealthSnapshot;
const health = getManagedPluginHealthSnapshot?.(pluginId, new Date().toISOString());
if (getManagedPluginHealthSnapshot && health?.status !== "ready") {
const health = store?.getManagedPluginHealthSnapshot?.(pluginId, new Date().toISOString());
if (store?.getManagedPluginHealthSnapshot && health?.status !== "ready") {
const errorCode = health?.status === "failed" || health?.status === "expired"
? documentProcessingHealthErrorCode(health.details)
: "document_processing_plugin_health_unknown";
Expand All @@ -78,7 +76,7 @@ export function resolveDocumentProcessingPluginAvailability(
errorMessage: health?.message ?? `${label} document processing runtime health has not been verified.`,
};
}
if (getManagedPluginHealthSnapshot && packageRecord && usesHostPluginCache(packageRecord.cacheRef)) {
if (store?.getManagedPluginHealthSnapshot && packageRecord && usesHostPluginCache(packageRecord.cacheRef)) {
const selectionError = resolveHostSelectionError(pluginId, packageRecord, health);
if (selectionError) return { enabled: false, ...selectionError };
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -300,15 +300,17 @@ class PluginProcess {

constructor(pluginId: string, executablePath: string, version: string) {
this.pluginId = pluginId;
const command = executablePath.endsWith(".mjs") ? process.execPath : executablePath;
const args = executablePath.endsWith(".mjs") ? [executablePath] : [];
const nodeWorker = executablePath.endsWith(".mjs");
const command = nodeWorker ? process.execPath : executablePath;
const args = nodeWorker ? [executablePath] : [];
const env: NodeJS.ProcessEnv = {};
for (const key of CHILD_ENV_KEYS) {
const value = process.env[key];
if (value !== undefined) env[key] = value;
}
this.child = spawn(command, args, { stdio: ["pipe", "pipe", "pipe"], env: {
...env,
...(nodeWorker && process.versions.electron ? { ELECTRON_RUN_AS_NODE: "1" } : {}),
LING_DOCUMENT_PROCESSING_PLUGIN: "1",
LING_DOCUMENT_PROCESSING_PLUGIN_ID: pluginId,
LING_DOCUMENT_PROCESSING_PLUGIN_VERSION: version,
Expand Down
Loading
Loading