Files
openmotion/tracking/core.ts
霜草 7d91cab729 feat: add north-star tracking evidence (#424)
* feat: add north-star tracking evidence

* fix(distribution): ship the tracking task ledger in packaged applications

phase1.ts and server.ts import tracking/task-ledger.ts, but the packaged
application file list never gained the new module, so npm artifacts failed
to load with ERR_MODULE_NOT_FOUND and the distribution lane failed.

Add the module to the positive distribution list so both profiles keep a
loadable application.

Generated-By: looper 0.16.2 (runner=fixer, agent=pi)

* fix(tracking): attribute worker evidence and ledger every accepted export

Queue snapshots, heartbeats and technical-export checks now pass the worker
entrypoint instead of inheriting the MCP tracker default. Host run failures and
cancellations read the recorded work-round mode, and a failure only reports a
failed run state after it actually closed the round.

Every accepted export is now ledgered inside the shared export entry, so the
Studio and legacy routes produce the same evidence as the MCP adapter, and an
unreadable ledger is recorded as a diagnostic instead of failing an export that
already started rendering. Repeating an identical terminal result keeps the
recorded terminal time, and quality-check version ids follow the public
version-id contract instead of requiring a v4 UUID.

Generated-By: looper 0.16.2 (runner=fixer, agent=pi)

* fix: correct instrumentation evidence semantics

* fix: preserve work round failure evidence

* fix: close interrupted exports with one terminal outcome

Preview delivery now needs the confirmed current version and the originating
round's fixed version, and preview evidence is emitted only after recordDisplay
passes its version guard, so a rejected display no longer claims an observation
and a delivery for the same run.

Technical export checks report cancelled or unfinished jobs as unreviewed
instead of error; only a completed job without a verification report stays an
error.

The export ledger entry for an interrupted export is now closed once with
outcome unknown, and the worker tick that owns that transition emits the
matching task_terminal evidence. A second tick or a status read sees the closed
record and claim nothing. The tracking README describes that reconciliation
path.

Generated-By: looper 0.16.2 (runner=fixer, agent=pi)

* fix: keep interrupted-export reconciliation out of live renders

The worker tick reconciled before taking the working-set guard, so a later tick
could close a job this process was still rendering, the local render was left
running, and the owning worker then stated a second task_terminal for the same
task. Reconciliation now runs only for a tick that does not own the render, it
aborts any local controller of a job it closes, and the claiming worker states
its terminal evidence through one helper that skips a job the reconciler already
closed as unknown.

Generated-By: looper 0.16.2 (runner=fixer, agent=pi)

* fix: state terminal evidence from the caller that reconciles an export

Coalesce interrupted-export reconciliation into one owner so every path that
closes a task also reports it: the read path now records the same
task_terminal evidence as the worker tick, keeps the ledger terminal time and
never restates the outcome on a later read. Stores carry the service tracker,
including project-scoped stores and the MCP read paths.

Generated-By: looper 0.16.2 (runner=fixer, agent=pi)

* fix: preserve provider preview schema

---------

Co-authored-by: qindong <qindong@qindongs-MBP.lan>
Co-authored-by: 罗高 <luogao@users.noreply.github.com>
Co-authored-by: qindong <qindong@qindongs-MacBook-Pro.local>
2026-11-16 19:09:57 +08:00

125 lines
8.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { validHostContext } from './host.ts';
import type { HostContext } from './host.ts';
export type Rule = 'uuid' | 'code' | 'slug' | 'text' | 'timestamp' | 'boolean' | 'integer' | readonly string[] | { readonly min: number; readonly max: number };
export type Registry = Record<string, { fields: Record<string, Rule>; required: readonly string[] }>;
export type Fields = Record<string, string | number | boolean>;
type RuleValue<R> = R extends readonly string[] ? R[number] : R extends 'boolean' ? boolean : R extends 'integer' | { readonly min: number; readonly max: number } ? number : string;
export type EventFields<S extends Registry[string]> =
{ [K in S['required'][number]]: K extends keyof S['fields'] ? RuleValue<S['fields'][K]> : never } &
{ [K in Exclude<keyof S['fields'], S['required'][number]>]?: RuleValue<S['fields'][K]> };
export type Entry = 'mcp' | 'studio' | 'webmcp' | 'installer' | 'worker';
export type PendingEvent = {
event: string; event_id: string; occurred_at: string; entrypoint: Entry;
device_timezone: string | null; utc_offset_minutes: number; properties: Fields;
host_context?: HostContext;
};
export type Receipt = 'accepted' | 'retry' | 'drop';
export const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
const code = /^[A-Za-z0-9_.-]{1,128}$/;
// A catalogue resource id: letters, digits and single hyphens between them, at most 64 characters.
// No dots, slashes, spaces or underscores, so a path, URL, file name or title cannot pass.
export const slug = /^(?=.{1,64}$)[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$/;
// The only free-text rule: a settled search-box value, trimmed, 1–100 characters, no control characters.
// Register it on a field only when the product decision to collect that text is explicit.
export const text = (value: string) => value.length >= 1 && value.length <= 100 && value === value.trim() && !/[\u0000-\u001f\u007f]/.test(value);
export function validField(rule: Rule, value: unknown): value is string | number | boolean {
if (Array.isArray(rule)) return typeof value === 'string' && rule.includes(value);
if (typeof rule === 'object' && 'min' in rule) return typeof value === 'number' && Number.isFinite(value) && value >= rule.min && value <= rule.max;
if (rule === 'boolean') return typeof value === 'boolean';
if (rule === 'integer') return Number.isSafeInteger(value) && Number(value) >= 0 && Number(value) <= 86_400_000;
if (rule === 'text') return typeof value === 'string' && text(value);
if (rule === 'timestamp') return typeof value === 'string' && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(value) && Number.isFinite(Date.parse(value));
return typeof value === 'string' && (rule === 'uuid' ? uuid : rule === 'slug' ? slug : code).test(value);
}
export function deviceContext() {
return { device_timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || null,
utc_offset_minutes: -new Date().getTimezoneOffset() };
}
export function validProperties(registry: Registry, event: string, raw: unknown): raw is Fields {
if (!Object.hasOwn(registry, event) || !raw || typeof raw !== 'object' || Array.isArray(raw)) return false;
const spec = registry[event], values = raw as Fields;
if (spec.required.some(key => !Object.hasOwn(values, key))) return false;
return Object.entries(values).every(([key, value]) => {
if (!Object.hasOwn(spec.fields, key)) return false;
return validField(spec.fields[key], value);
});
}
export function validPending(registry: Registry, value: unknown): value is PendingEvent {
if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
const e = value as PendingEvent;
if (Object.keys(e).some(k => !['event','event_id','occurred_at','entrypoint','device_timezone','utc_offset_minutes','properties','host_context'].includes(k))) return false;
if (e.host_context !== undefined && !validHostContext(e.host_context)) return false;
if (typeof e.occurred_at !== 'string' || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(e.occurred_at)) return false;
const time = Date.parse(e.occurred_at), age = Date.now() - time;
if (!uuid.test(e.event_id) || !Number.isFinite(time) || age < -300_000 || age > 86_400_000) return false;
if (!['mcp','studio','webmcp','installer','worker'].includes(e.entrypoint)) return false;
if (!Number.isInteger(e.utc_offset_minutes) || Math.abs(e.utc_offset_minutes) > 840) return false;
if (e.device_timezone !== null) {
if (typeof e.device_timezone !== 'string' || e.device_timezone.length > 64) return false;
try { new Intl.DateTimeFormat('en', { timeZone: e.device_timezone }); } catch { return false; }
}
return validProperties(registry, e.event, e.properties) && JSON.stringify(e).length <= 4096;
}
export function createTracker<const R extends Registry>(options: {
registry: R; entrypoint: Entry; enabled: boolean;
send: (events: readonly PendingEvent[], signal: AbortSignal) => Promise<Receipt>;
maxQueue?: number; flushIntervalMs?: number; isEnabled?: () => boolean;
}) {
let enabled = options.enabled, queue: PendingEvent[] = [], timer: ReturnType<typeof setTimeout> | undefined;
let inFlight: Promise<Receipt | 'disabled' | 'empty'> | undefined, controller: AbortController | undefined;
const seen = new Set<string>(), maxQueue = options.maxQueue ?? 64;
let failures = 0;
function discard() { queue = []; seen.clear(); if (timer) clearTimeout(timer); timer = undefined; controller?.abort(); }
function active() {
let allowed = enabled;
try { allowed = allowed && (options.isEnabled?.() ?? true); } catch { allowed = false; }
if (!allowed) discard();
return allowed;
}
function schedule() {
if (!active() || timer || options.flushIntervalMs === 0) return;
timer = setTimeout(() => { timer = undefined; void flush(); }, Math.min(60_000, (options.flushIntervalMs ?? 1000) * 2 ** failures));
(timer as unknown as { unref?: () => void }).unref?.();
}
function ingest(raw: unknown) {
if (!active()) return 'disabled';
if (!validPending(options.registry, raw)) return 'invalid';
if (seen.has(raw.event_id)) return 'duplicate';
if (queue.length >= maxQueue) return 'full';
queue.push(structuredClone(raw)); seen.add(raw.event_id);
// shortcut: process-local queue and dedup; add durable storage only if crash recovery is required.
if (seen.size > 2048) seen.delete(seen.values().next().value!);
schedule(); return 'queued';
}
function track<E extends keyof R & string>(event: E, properties: EventFields<R[E]>, eventId: string = crypto.randomUUID(), entrypoint: Entry = options.entrypoint, host?: HostContext) {
if (!active()) return 'disabled';
try { return ingest({ event, properties, event_id: eventId, occurred_at: new Date().toISOString(),
entrypoint, ...deviceContext(), ...(host ? { host_context: host } : {}) }); } catch { return 'invalid'; }
}
function setEnabled(next: boolean) {
enabled = next;
if (!next) discard();
}
function flush(): Promise<Receipt | 'disabled' | 'empty'> {
if (!active()) return Promise.resolve('disabled');
if (inFlight) return inFlight;
if (!queue.length) return Promise.resolve('empty');
if (timer) clearTimeout(timer); timer = undefined;
queue = queue.filter(event => Date.now() - Date.parse(event.occurred_at) <= 86_400_000);
if (!queue.length) return Promise.resolve('empty');
const snapshot = queue.slice(0, 16), request = new AbortController(); controller = request;
inFlight = (async () => {
let receipt: Receipt;
try { receipt = await options.send(snapshot, request.signal); } catch { receipt = 'retry'; }
if (!active()) return 'disabled' as const;
failures = receipt === 'retry' ? Math.min(6, failures + 1) : 0;
if (receipt !== 'retry') { const ids = new Set(snapshot.map(e => e.event_id)); queue = queue.filter(e => !ids.has(e.event_id)); }
return receipt;
})().finally(() => { inFlight = undefined; controller = undefined; if (queue.length) schedule(); });
return inFlight;
}
return { track, ingest, flush, setEnabled, enabled: active, pending: () => queue.length,
close: () => { setEnabled(false); } };
}