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
4 changes: 2 additions & 2 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -605,8 +605,8 @@ contextual(
.option('--trigger', 'run the host sync service now (SSH to the configured remote)')
.option('--fold', 'with --trigger: run sync + the LLM fold (the timer unit) so derived artifacts update too; a minute or two')
.option('--force', 're-run even if the host synced (or, with --fold, folded) within 5 minutes'),
).action((opts) => {
const r = refresh(root, opts)
).action(async (opts) => {
const r = await refresh(root, opts)
console.log(`host: ${r.host}${r.fold ? ' [sync + fold]' : ''}${r.outcome ? ` (${r.outcome})` : ''}${r.note ? ` — ${r.note}` : ''}`)
console.log(`synced: ${r.before.lastSync ?? 'never'} → ${r.after.lastSync ?? 'never'}; extracted: ${r.before.lastExtract ?? 'never'} → ${r.after.lastExtract ?? 'never'}`)
})
Expand Down
2 changes: 1 addition & 1 deletion src/commands/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ export function createServer(ctx: ResolvedContext, rememberOpts: { cwd: string;
},
async ({ trigger, force, fold }) => {
lastPull = Date.now()
const r = refresh(rememberOpts.cwd, { ...rememberOpts.opts, trigger, force, fold })
const r = await refresh(rememberOpts.cwd, { ...rememberOpts.opts, trigger, force, fold })
return text(r)
},
)
Expand Down
41 changes: 23 additions & 18 deletions src/commands/refresh.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { execFileSync } from 'node:child_process'
import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
import { isAbsolute } from 'node:path'
import { git, readGlobalConfig, resolveContext, type ResolvedContext, type ResolveOptions } from '../context.js'
import { recallData, type Recalled } from '../recall.js'
Expand All @@ -22,13 +23,13 @@ export interface RefreshResult {

export interface RefreshDeps {
/** Run a command on the host over SSH; throws on non-zero exit. */
ssh: (target: string, command: string, timeoutMs: number) => string
ssh: (target: string, command: string, timeoutMs: number) => string | Promise<string>
/**
* Run a command here, when this machine IS the host (the remote is a local
* directory and the sync unit is installed) — how the hosted MCP server
* triggers a sync. Defaults to a local shell; undefined disables the path.
*/
local?: (command: string, timeoutMs: number) => string
local?: (command: string, timeoutMs: number) => string | Promise<string>
now?: () => number
}

Expand Down Expand Up @@ -86,11 +87,11 @@ const IN_FLIGHT = new Set(['activating', 'active', 'deactivating'])
* forced. The run's outcome comes back in the result — only failing to
* reach the host throws.
*/
export function refresh(
export async function refresh(
cwd: string,
opts: ResolveOptions & { trigger?: boolean; force?: boolean; fold?: boolean },
deps: RefreshDeps = { ssh: sshExec, local: localExec },
): RefreshResult {
): Promise<RefreshResult> {
const ctx = resolveContext(cwd, { ...opts, pull: opts.pull ?? true })
const before = freshness(ctx)
let host: RefreshResult['host'] = 'not-requested'
Expand All @@ -101,7 +102,7 @@ export function refresh(
const remote = ctx.mode === 'cache' ? readGlobalConfig().remote : undefined
const target = sshTargetFromRemote(remote)
// On the host itself the remote is a directory: run the same unit commands here.
const onHost = !target && remote !== undefined && isAbsolute(remote) && deps.local !== undefined && hasSyncUnit(deps.local)
const onHost = !target && remote !== undefined && isAbsolute(remote) && deps.local !== undefined && (await hasSyncUnit(deps.local))
const run = target ? (cmd: string, t: number) => deps.ssh(target, cmd, t) : onHost ? deps.local! : undefined
if (!run) {
host = 'unavailable'
Expand All @@ -110,19 +111,19 @@ export function refresh(
const fold = opts.fold === true
const cmd = hostCommands(fold)
const what = fold ? 'sync + fold' : 'sync'
const state = run(cmd.state, STATUS_TIMEOUT_MS).trim()
const state = (await run(cmd.state, STATUS_TIMEOUT_MS)).trim()
const now = deps.now?.() ?? Date.now()
const last = fold ? before.lastExtract : before.lastSync
const lastMs = last ? new Date(last).getTime() : 0
if (IN_FLIGHT.has(state)) {
host = 'waited'
;({ outcome, note } = unitOutcome(run(cmd.wait, HOST_TIMEOUT_MS), `a ${what} was already running; waited for it`))
;({ outcome, note } = unitOutcome(await run(cmd.wait, HOST_TIMEOUT_MS), `a ${what} was already running; waited for it`))
} else if (!opts.force && now - lastMs < MIN_INTERVAL_MS) {
host = 'skipped-recent'
note = `host ${fold ? 'folded' : 'synced'} ${Math.round((now - lastMs) / 60_000)} min ago; not re-running (force to override)`
} else {
host = 'ran'
;({ outcome, note } = unitOutcome(run(cmd.start, HOST_TIMEOUT_MS)))
;({ outcome, note } = unitOutcome(await run(cmd.start, HOST_TIMEOUT_MS)))
}
if (outcome && ctx.mode === 'cache') git(ctx.root, 'pull', '--ff-only', '--quiet')
}
Expand Down Expand Up @@ -167,10 +168,10 @@ export function sshTargetFromRemote(remote: string | undefined): string | undefi

/** Is the sync unit installed on this machine? Cached: units do not come and go while a server runs. */
let syncUnitHere: boolean | undefined
function hasSyncUnit(local: NonNullable<RefreshDeps['local']>): boolean {
async function hasSyncUnit(local: NonNullable<RefreshDeps['local']>): Promise<boolean> {
if (syncUnitHere === undefined) {
try {
local('systemctl cat lore-sync.service >/dev/null 2>&1', 10_000)
await local('systemctl cat lore-sync.service >/dev/null 2>&1', 10_000)
syncUnitHere = true
} catch {
syncUnitHere = false
Expand All @@ -179,13 +180,17 @@ function hasSyncUnit(local: NonNullable<RefreshDeps['local']>): boolean {
return syncUnitHere
}

function localExec(command: string, timeoutMs: number): string {
return execFileSync('bash', ['-c', command], { stdio: ['ignore', 'pipe', 'pipe'], timeout: timeoutMs }).toString()
const execAsync = promisify(execFile)

/**
* Waiting for the host's sync can take many minutes. These must not block:
* `lore www` serves the board and every agent's MCP session from one
* process, and a synchronous wait here froze all of them until the run ended.
*/
async function localExec(command: string, timeoutMs: number): Promise<string> {
return (await execAsync('bash', ['-c', command], { timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024 })).stdout
}

function sshExec(target: string, command: string, timeoutMs: number): string {
return execFileSync('ssh', ['-o', 'BatchMode=yes', '-o', 'ConnectTimeout=20', target, command], {
stdio: ['ignore', 'pipe', 'pipe'],
timeout: timeoutMs,
}).toString()
async function sshExec(target: string, command: string, timeoutMs: number): Promise<string> {
return (await execAsync('ssh', ['-o', 'BatchMode=yes', '-o', 'ConnectTimeout=20', target, command], { timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024 })).stdout
}
46 changes: 32 additions & 14 deletions test/selfhosted.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -523,16 +523,16 @@ test('refresh: sshTargetFromRemote parses ssh remotes and rejects paths', () =>
assert.equal(sshTargetFromRemote(undefined), undefined)
})

test('refresh: with a path remote the host trigger is unavailable but the pull still reports freshness', () => {
test('refresh: with a path remote the host trigger is unavailable but the pull still reports freshness', async () => {
seedBare('lore-fresh', { project: 'fresh' }, { 'state.json': JSON.stringify({ cursors: {}, lastSync: '2026-09-09T10:00:00Z' }) })
const calls: string[] = []
const r = refresh(tmpdir(), { context: 'lore-fresh', trigger: true }, { ssh: (t, c) => { calls.push(`${t} ${c}`); return '' } })
const r = await refresh(tmpdir(), { context: 'lore-fresh', trigger: true }, { ssh: (t, c) => { calls.push(`${t} ${c}`); return '' } })
assert.equal(r.host, 'unavailable')
assert.deepEqual(calls, [])
assert.equal(r.after.lastSync, '2026-09-09T10:00:00Z')
})

test('refresh: with an ssh remote it checks the unit state, runs the host service unless the last sync is recent, and reports the outcome', () => {
test('refresh: with an ssh remote it checks the unit state, runs the host service unless the last sync is recent, and reports the outcome', async () => {
seedBare('lore-ssh', { project: 'ssh' }, { 'state.json': JSON.stringify({ cursors: {}, lastSync: '2026-09-09T10:00:00Z' }) })
// clone first so the cache exists, then swap the global remote to an ssh form for the trigger check
resolveContext(tmpdir(), { context: 'lore-ssh' })
Expand All @@ -550,13 +550,13 @@ test('refresh: with an ssh remote it checks the unit state, runs the host servic
throw new Error(`unexpected ssh command: ${c}`)
}
const target = 'exedev@lore-host.example'
const recent = refresh(tmpdir(), { context: 'lore-ssh', trigger: true, pull: false }, { ssh, now: () => Date.parse('2026-09-09T10:03:00Z') })
const recent = await refresh(tmpdir(), { context: 'lore-ssh', trigger: true, pull: false }, { ssh, now: () => Date.parse('2026-09-09T10:03:00Z') })
assert.equal(recent.host, 'skipped-recent')
assert.equal(recent.outcome, undefined)
assert.deepEqual(calls, [`${target} ${STATE_CMD}`], 'idle + recent: only the state probe, no start')

calls.length = 0
const stale = refresh(tmpdir(), { context: 'lore-ssh', trigger: true, pull: false }, { ssh, now: () => Date.parse('2026-09-09T12:00:00Z') })
const stale = await refresh(tmpdir(), { context: 'lore-ssh', trigger: true, pull: false }, { ssh, now: () => Date.parse('2026-09-09T12:00:00Z') })
assert.equal(stale.host, 'ran')
assert.equal(stale.outcome, 'success')
assert.deepEqual(calls, [`${target} ${STATE_CMD}`, `${target} ${START_CMD}`])
Expand All @@ -565,14 +565,14 @@ test('refresh: with an ssh remote it checks the unit state, runs the host servic
assert.match(UNIT_PRELUDE, /lore-sync-now\.service.*\|\| echo lore-sync\.service/, 'prefers the sync-only unit, falls back to the hourly one on an un-upgraded host')

calls.length = 0
const forced = refresh(tmpdir(), { context: 'lore-ssh', trigger: true, force: true, pull: false }, { ssh, now: () => Date.parse('2026-09-09T10:05:00Z') })
const forced = await refresh(tmpdir(), { context: 'lore-ssh', trigger: true, force: true, pull: false }, { ssh, now: () => Date.parse('2026-09-09T10:05:00Z') })
assert.equal(forced.host, 'ran')
assert.deepEqual(calls, [`${target} ${STATE_CMD}`, `${target} ${START_CMD}`])

// A run already in flight is waited out, never re-triggered — even when recent/force would otherwise decide.
calls.length = 0
state = 'activating'
const waited = refresh(tmpdir(), { context: 'lore-ssh', trigger: true, pull: false }, { ssh, now: () => Date.parse('2026-09-09T10:05:00Z') })
const waited = await refresh(tmpdir(), { context: 'lore-ssh', trigger: true, pull: false }, { ssh, now: () => Date.parse('2026-09-09T10:05:00Z') })
assert.equal(waited.host, 'waited')
assert.equal(waited.outcome, 'success')
assert.match(waited.note ?? '', /already running/)
Expand All @@ -583,22 +583,40 @@ test('refresh: with an ssh remote it checks the unit state, runs the host servic
calls.length = 0
state = 'failed'
show = 'Result=exit-code\nExecMainStatus=1\n'
const failed = refresh(tmpdir(), { context: 'lore-ssh', trigger: true, pull: false }, { ssh, now: () => Date.parse('2026-09-09T12:00:00Z') })
const failed = await refresh(tmpdir(), { context: 'lore-ssh', trigger: true, pull: false }, { ssh, now: () => Date.parse('2026-09-09T12:00:00Z') })
assert.equal(failed.host, 'ran')
assert.equal(failed.outcome, 'failed')
assert.match(failed.note ?? '', /exit-code, exit 1/)
assert.equal(calls.length, 2)

calls.length = 0
const noTrigger = refresh(tmpdir(), { context: 'lore-ssh', pull: false }, { ssh })
const noTrigger = await refresh(tmpdir(), { context: 'lore-ssh', pull: false }, { ssh })
assert.equal(noTrigger.host, 'not-requested')
assert.deepEqual(calls, [])
} finally {
writeGlobalConfig(saved)
}
})

test('refresh: --fold targets the timer sync+fold unit and rate-limits on the last fold, not the last sync', () => {
test('refresh: waiting on the host does not block the process — the board and other MCP sessions share it', async () => {
seedBare('lore-wait', { project: 'wait' }, { 'state.json': JSON.stringify({ cursors: {}, lastSync: '2026-09-09T10:00:00Z' }) })
resolveContext(tmpdir(), { context: 'lore-wait' })
const saved = readGlobalConfig()
writeGlobalConfig({ ...saved, remote: 'exedev@lore-host.example:/srv/lore/repos' })
try {
let ticks = 0
const timer = setInterval(() => ticks++, 10)
const ssh = (_t: string, c: string) => (c === STATE_CMD ? 'active\n' : new Promise<string>((done) => setTimeout(() => done('Result=success\nExecMainStatus=0\n'), 200)))
const r = await refresh(tmpdir(), { context: 'lore-wait', trigger: true, pull: false }, { ssh })
clearInterval(timer)
assert.equal(r.host, 'waited')
assert.equal(ticks >= 5, true, `other work ran ${ticks} times during the wait`)
} finally {
writeGlobalConfig(saved)
}
})

test('refresh: --fold targets the timer sync+fold unit and rate-limits on the last fold, not the last sync', async () => {
seedBare('lore-fold', { project: 'fold' }, { 'state.json': JSON.stringify({ cursors: {}, lastSync: '2026-09-09T10:00:00Z', lastExtract: '2026-09-09T09:00:00Z' }) })
resolveContext(tmpdir(), { context: 'lore-fold' })
const saved = readGlobalConfig()
Expand All @@ -618,26 +636,26 @@ test('refresh: --fold targets the timer sync+fold unit and rate-limits on the la
}
// Synced 5 min ago but folded an hour ago: a plain trigger would skip; --fold runs.
const now = () => Date.parse('2026-09-09T10:05:00Z')
const ran = refresh(tmpdir(), { context: 'lore-fold', trigger: true, fold: true, pull: false }, { ssh, now })
const ran = await refresh(tmpdir(), { context: 'lore-fold', trigger: true, fold: true, pull: false }, { ssh, now })
assert.equal(ran.host, 'ran')
assert.equal(ran.fold, true)
assert.equal(ran.outcome, 'success')
assert.deepEqual(calls, [fold.state, fold.start])

calls.length = 0
const recent = refresh(tmpdir(), { context: 'lore-fold', trigger: true, fold: true, pull: false }, { ssh, now: () => Date.parse('2026-09-09T09:03:00Z') })
const recent = await refresh(tmpdir(), { context: 'lore-fold', trigger: true, fold: true, pull: false }, { ssh, now: () => Date.parse('2026-09-09T09:03:00Z') })
assert.equal(recent.host, 'skipped-recent')
assert.match(recent.note ?? '', /folded 3 min ago/)
assert.deepEqual(calls, [fold.state])

calls.length = 0
state = 'activating'
const waited = refresh(tmpdir(), { context: 'lore-fold', trigger: true, fold: true, pull: false }, { ssh, now })
const waited = await refresh(tmpdir(), { context: 'lore-fold', trigger: true, fold: true, pull: false }, { ssh, now })
assert.equal(waited.host, 'waited')
assert.match(waited.note ?? '', /sync \+ fold was already running/)
assert.deepEqual(calls, [fold.state, fold.wait])

const plain = refresh(tmpdir(), { context: 'lore-fold', pull: false }, { ssh })
const plain = await refresh(tmpdir(), { context: 'lore-fold', pull: false }, { ssh })
assert.equal(plain.fold, undefined, 'fold is only reported when it was triggered')
} finally {
writeGlobalConfig(saved)
Expand Down
Loading