@sema-agent/core 7.68.1 → 7.68.3

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 (35) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/dist/agents/repair-loop.js +1 -1
  3. package/dist/agents/verify.js +1 -1
  4. package/dist/core/engine-capabilities.d.ts +8 -1
  5. package/dist/core/engine-capabilities.js +1 -1
  6. package/dist/core/file-history-store.d.ts +229 -44
  7. package/dist/core/file-history-store.js +288 -93
  8. package/dist/core/runner/contracts.d.ts +1 -1
  9. package/dist/core/runner/file-history-request.d.ts +10 -2
  10. package/dist/core/runner/file-history-request.js +17 -1
  11. package/dist/core/runner/file-history-restore.d.ts +11 -4
  12. package/dist/core/runner/file-history-restore.js +19 -5
  13. package/dist/core/runner/prepare-file-history.js +3 -3
  14. package/dist/core/runner/rewind-files.js +11 -8
  15. package/dist/core/store-contracts/file-history-store-contract.js +210 -13
  16. package/dist/core/task-spec-members.d.ts +31 -18
  17. package/dist/core/task-spec-members.js +11 -8
  18. package/dist/core/task-spec.d.ts +7 -0
  19. package/dist/index.d.ts +2 -0
  20. package/dist/index.js +1 -0
  21. package/dist/orchestration/goal.js +3 -1
  22. package/dist/stores/file/file-history-store.d.ts +5 -3
  23. package/dist/stores/file/file-history-store.js +42 -60
  24. package/package.json +2 -2
  25. package/test/export-surface.snapshot.json +17 -1
  26. package/wire-changes/core-stores-sql@7.68.2.json +39 -0
  27. package/wire-changes/core-stores-sql@7.68.3.json +39 -0
  28. package/wire-changes/core@7.68.2.json +612 -0
  29. package/wire-changes/core@7.68.3.json +125 -0
  30. package/wire-changes/mods-kernel@7.68.2.json +39 -0
  31. package/wire-changes/mods-kernel@7.68.3.json +39 -0
  32. package/wire-changes/primitives@7.68.2.json +39 -0
  33. package/wire-changes/primitives@7.68.3.json +39 -0
  34. package/wire-changes/wiki-gate@7.68.2.json +39 -0
  35. package/wire-changes/wiki-gate@7.68.3.json +39 -0
@@ -2,12 +2,13 @@ import { RETIRED_TASK_SPEC_KEYS, retiredKeyOf, retiredKeyRefusal } from "./retir
2
2
  import { thrownText } from "./thrown-value.js";
3
3
  import { strayMembersOf } from "./own-property-receipt.js";
4
4
  const SESSION = "session";
5
+ const ENTRY = "entry";
5
6
  const SPEC_MEMBER_TABLE = {
6
- taskId: 0, objective: 0, wake: SESSION, principal: 0, isolationScope: 0, actor: 0, runOrigin: 0, interactionPosture: 0, approvalReach: 0, interactiveQuestionFallback: 0,
7
- images: 0, userAttachments: 0, sessionId: SESSION, projectId: 0, workspace: 0, requireExistingSession: SESSION, oneShot: 0, clientContext: 0, resumeAt: SESSION,
8
- resumeAtMode: SESSION, model: 0, modelRole: 0, roles: 0, compactionModel: 0, advisorModel: 0, thinking: 0, systemPrompt: 0,
7
+ taskId: 0, objective: 0, wake: ENTRY, principal: 0, isolationScope: 0, actor: 0, runOrigin: 0, interactionPosture: 0, approvalReach: 0, interactiveQuestionFallback: 0,
8
+ images: 0, userAttachments: 0, sessionId: SESSION, projectId: 0, workspace: 0, requireExistingSession: SESSION, oneShot: 0, clientContext: 0, resumeAt: ENTRY,
9
+ resumeAtMode: ENTRY, model: 0, modelRole: 0, roles: 0, compactionModel: 0, advisorModel: 0, thinking: 0, systemPrompt: 0,
9
10
  promptRole: 0, promptForm: 0, promptBinding: 0, promptLocale: 0, appendSystemPrompt: 0, outputStyle: 0, memory: 0, suggestNextPrompts: 0, fileHistory: 0,
10
- projectMemory: 0, instructionFamily: 0, restoreFiles: SESSION, acceptPartialRestore: SESSION, rewindFilesTo: SESSION, tools: 0, allowTools: 0, excludeTools: 0, excludeAllTools: 0,
11
+ projectMemory: 0, instructionFamily: 0, restoreFiles: ENTRY, acceptPartialRestore: ENTRY, unplacedHistoryRecordedUnder: ENTRY, rewindFilesTo: ENTRY, tools: 0, allowTools: 0, excludeTools: 0, excludeAllTools: 0,
11
12
  deferTools: 0, toolMaterializeStrategy: 0, alwaysLoadTools: 0, restoreGatedTools: 0, deferSelfResolve: 0, promptLean: 0, agents: 0, toolPolicy: 0,
12
13
  basePolicyForResumeEdit: 0, onAsk: 0, onQuestion: 0, lspManager: 0, lspDiagnostics: 0, mods: 0, peerPresence: 0, durableApproval: 0,
13
14
  resourceSuspend: 0, preemptSignal: 0, resilience: 0, finalVerification: 0, maxSuspends: 0, checkpointStore: 0, handsReadOnly: 0, memoryPersistenceCapable: 0,
@@ -19,16 +20,18 @@ const SPEC_MEMBER_TABLE = {
19
20
  language: 0,
20
21
  };
21
22
  export const TASK_SPEC_MEMBERS = Object.keys(SPEC_MEMBER_TABLE);
22
- export const SESSION_BOUND_SPEC_MEMBERS = TASK_SPEC_MEMBERS.filter((name) => Reflect.get(SPEC_MEMBER_TABLE, name) === SESSION);
23
+ export const SESSION_BOUND_SPEC_MEMBERS = TASK_SPEC_MEMBERS.filter((name) => Reflect.get(SPEC_MEMBER_TABLE, name) !== 0);
24
+ export const SESSION_ENTRY_SPEC_MEMBERS = SESSION_BOUND_SPEC_MEMBERS.filter((name) => Reflect.get(SPEC_MEMBER_TABLE, name) === ENTRY);
23
25
  export function withoutSessionBinding(spec) {
24
26
  const own = { ...spec };
25
27
  for (const name of SESSION_BOUND_SPEC_MEMBERS)
26
28
  Reflect.deleteProperty(own, name);
27
29
  return own;
28
30
  }
29
- export function withOpeningObjective(spec, objective) {
30
- const own = { ...spec, objective };
31
- Reflect.deleteProperty(own, "wake");
31
+ export function withOpeningObjective(spec, objective, continues) {
32
+ const own = { ...spec, objective, ...(continues !== undefined ? { sessionId: continues } : {}) };
33
+ for (const name of continues !== undefined ? SESSION_ENTRY_SPEC_MEMBERS : ["wake"])
34
+ Reflect.deleteProperty(own, name);
32
35
  return own;
33
36
  }
34
37
  const MEMBERS = new Set(TASK_SPEC_MEMBERS);
@@ -591,6 +591,13 @@ export interface TaskSpec {
591
591
  * documented recovery either way: re-run the same restore — it is per-file idempotent and converges.
592
592
  */
593
593
  acceptPartialRestore?: boolean;
594
+ /**
595
+ * The directory this session's OLDER file versions were recorded under (an engine before 7.68.2 recorded no place): without
596
+ * it they are refused `place_unrecorded`; with it they are judged as recorded there, by the one place comparison (another
597
+ * directory ⇒ `recorded_elsewhere`). An absolute path, in the run's environment; only on a run that restores files, else
598
+ * `rewind.invalid_spec`. A host states it when it knows where every earlier turn ran. `Runner.rewindFiles` takes it too.
599
+ */
600
+ unplacedHistoryRecordedUnder?: string;
594
601
  /**
595
602
  * design/101 §E19 R8 + design/381 (CC Rewind `code`-only mode) — converge the tracked set (see
596
603
  * {@link restoreFiles} for what that is and is not) to the history boundary of this prior entryId
package/dist/index.d.ts CHANGED
@@ -178,6 +178,8 @@ export { COMPACTION_FAILURE_CAUSES } from "./core/auto-compaction.js";
178
178
  export type { CompactionFailureCause } from "./core/auto-compaction.js";
179
179
  export { trackKeyOf as fileHistoryTrackKeyOf, resolveTrackKey as fileHistoryResolveTrackKey } from "./core/file-history-store.js";
180
180
  export { describeTrackKey as fileHistoryDescribeTrackKey, fileHistoryExportDigest, validateFileHistoryExport } from "./core/file-history-store.js";
181
+ export { resolveTrackedFile as fileHistoryResolveTrackedFile, placeProvenDifferent as fileHistoryPlaceProvenDifferent, trackKeyForEdit as fileHistoryTrackKeyForEdit, trackKeyForAnnul as fileHistoryTrackKeyForAnnul, fileHistoryEntryTravels, fileHistoryParentIdentTravels } from "./core/file-history-store.js";
182
+ export type { FileHistoryRewindFile, FileHistoryRestoreOptions } from "./core/file-history-store.js";
181
183
  export { fileHistoryBlobExchangeOf } from "./core/file-history-store.js";
182
184
  export type { FileHistoryBlobExchange } from "./core/file-history-store.js";
183
185
  export type { FileHistoryStore, FileHistoryResult, FileHistoryTrackResult, FileHistoryError, FileHistoryKeyFamily, FileHistoryTrackKeyDescriptor, FileHistoryRestoreResult, FileHistoryDiffStats, FileHistoryExport, FileHistoryExportResult, FileBackupCapture, FileRestoreTarget, FileRestoreApplyOptions, FileRestoreApplyOutcome, FileHistoryTrackKeyResolution } from "./core/file-history-store.js";
package/dist/index.js CHANGED
@@ -144,6 +144,7 @@ export { FILE_HISTORY_REFUSAL_CLASSES } from "./core/file-history-store.js";
144
144
  export { COMPACTION_FAILURE_CAUSES } from "./core/auto-compaction.js";
145
145
  export { trackKeyOf as fileHistoryTrackKeyOf, resolveTrackKey as fileHistoryResolveTrackKey } from "./core/file-history-store.js";
146
146
  export { describeTrackKey as fileHistoryDescribeTrackKey, fileHistoryExportDigest, validateFileHistoryExport } from "./core/file-history-store.js";
147
+ export { resolveTrackedFile as fileHistoryResolveTrackedFile, placeProvenDifferent as fileHistoryPlaceProvenDifferent, trackKeyForEdit as fileHistoryTrackKeyForEdit, trackKeyForAnnul as fileHistoryTrackKeyForAnnul, fileHistoryEntryTravels, fileHistoryParentIdentTravels } from "./core/file-history-store.js";
147
148
  export { fileHistoryBlobExchangeOf } from "./core/file-history-store.js";
148
149
  export { DEFAULT_FILE_HISTORY_BOUNDARY_KEEP, resolveFileHistoryRetention, fileHistoryBoundariesToKeep } from "./core/file-history-retention.js";
149
150
  export { FileStorageBackend, FileSessionRepo, FileCheckpointStore, CHECKPOINT_LEDGER_EVENT_KINDS, readCheckpointLedger, FileToolResultStore, FileSessionPolicyStore, FileFileHistoryStore, FileWorkflowJournalStore, MAX_JOURNAL_RESULT_BYTES, oversizeJournalResult, resolveDataRoot, sanitizeScope, sanitizePathComponent, atomicWriteFile, writeThenLink, ensureDir, readJsonlRecords, AppendLog, FileStoreLockError, processFingerprint, isProcessLive, } from "./stores/file/index.js";
@@ -3,6 +3,7 @@ import { Type } from "typebox";
3
3
  import { delimitUntrusted } from "../core/untrusted-text.js";
4
4
  import { recipeContinuationLeg } from "../core/input-author.js";
5
5
  import { legTaskIdOf } from "../core/leg-identity.js";
6
+ import { withOpeningObjective } from "../core/task-spec-members.js";
6
7
  import { isDurablePause, pauseFamily } from "../agents/suspend-guard.js";
7
8
  import { OUTPUT_TOOL_NAME, mountRuleFace, toolFace } from "../core/tool-catalog-entries.js";
8
9
  export const DECLARE_DONE_TOOL_NAME = "DeclareDone";
@@ -143,7 +144,8 @@ export async function runGoal(runner, spec, internals) {
143
144
  ? spec.taskSpec.tools
144
145
  : [...(spec.taskSpec.tools ?? []), createDeclareDoneTool(doneRef)];
145
146
  const roundInternals = { ...internals, goalMode: true };
146
- const result = await runner.runTask({ ...spec.taskSpec, sessionId, objective, tools, signal: goalSignal }, iteration === 1 ? roundInternals : recipeContinuationLeg(roundInternals));
147
+ const leg = { ...spec.taskSpec, tools, signal: goalSignal };
148
+ const result = await runner.runTask(lastResult === undefined ? { ...leg, sessionId, objective } : withOpeningObjective(leg, objective, lastResult.sessionId), iteration === 1 ? roundInternals : recipeContinuationLeg(roundInternals));
147
149
  lastResult = result;
148
150
  cumulativeTokens += (result.stats.tokens ?? 0) + (result.stats.nested?.tokens ?? 0);
149
151
  spentCostMicroUsd += (result.stats.costMicroUsd ?? 0) + (result.stats.nested?.costMicroUsd ?? 0);
@@ -1,5 +1,5 @@
1
1
  import type { ExecutionEnv } from "../../internal/harness-types.js";
2
- import { type FileHistoryDiffStats, type FileHistoryExport, type FileHistoryExportResult, type FileHistoryResult, type FileHistoryRestoreResult, type FileHistoryStore, type FileHistoryTrackResult } from "../../core/file-history-store.js";
2
+ import { type FileHistoryDiffStats, type FileHistoryExport, type FileHistoryExportResult, type FileHistoryResult, type FileHistoryRestoreOptions, type FileHistoryRestoreResult, type FileHistoryStore, type FileHistoryTrackResult } from "../../core/file-history-store.js";
3
3
  import { type FileHistoryRetentionPolicy } from "../../core/file-history-retention.js";
4
4
  import { type CorruptReadInfo } from "./corrupt-read-sink.js";
5
5
  /**
@@ -351,9 +351,11 @@ export declare class FileFileHistoryStore implements FileHistoryStore {
351
351
  private listBoundaryIds;
352
352
  snapshot(scope: string, entryId: string, env: ExecutionEnv, root: string, signal?: AbortSignal): Promise<FileHistoryResult>;
353
353
  private snapshotCounted;
354
- restore(scope: string, entryId: string, env: ExecutionEnv, root: string, signal?: AbortSignal): Promise<FileHistoryRestoreResult>;
354
+ restore(scope: string, entryId: string, env: ExecutionEnv, root: string, signal?: AbortSignal, options?: FileHistoryRestoreOptions): Promise<FileHistoryRestoreResult>;
355
355
  canRestore(scope: string, entryId: string): Promise<boolean>;
356
- diffStats(scope: string, entryId: string, env: ExecutionEnv, root: string): Promise<FileHistoryDiffStats | null>;
356
+ /** The restore PLANNED ({@link planFileHistoryRestore}: this store's own `restore` on a view of the env that performs no
357
+ * write), projected — one computation with the restore it previews. `null` when there is no usable boundary (A-2). */
358
+ diffStats(scope: string, entryId: string, env: ExecutionEnv, root: string, options?: FileHistoryRestoreOptions): Promise<FileHistoryDiffStats | null>;
357
359
  reap(scope: string, keepEntryIds: string[]): Promise<number>;
358
360
  deleteBySession(scope: string): Promise<number>;
359
361
  deleteUnreadableSessionHistory(sessionId: string): Promise<number>;
@@ -4,7 +4,7 @@ import { join } from "node:path";
4
4
  import { thrownText } from "../../core/thrown-value.js";
5
5
  import { readUnreadableDeleteId } from "../../core/session.js";
6
6
  import { readFileHistoryScope } from "../../engine/session/repo-utils.js";
7
- import { applyFileRestoreViaEnv, boundaryPublishVerdict, worldStillMatchesMint, annulProofFailure, captureFileBackupViaEnv, modeProvenDifferent, previewFileDelta, describeTrackKey, fileHistoryExportDigest, caughtFault, DAMAGED_RECORD, resolveTrackKey, trackKeyOf, validateFileHistoryExport, } from "../../core/file-history-store.js";
7
+ import { applyFileRestoreViaEnv, boundaryPublishVerdict, worldStillMatchesMint, annulProofFailure, captureFileBackupViaEnv, modeProvenDifferent, placeProvenDifferent, fileHistoryEntryTravels, fileHistoryParentIdentTravels, fileHistoryExportDigest, planFileHistoryRestore, caughtFault, DAMAGED_RECORD, resolveTrackKey, resolveTrackedFile, trackKeyForAnnul, trackKeyForEdit, validateFileHistoryExport, } from "../../core/file-history-store.js";
8
8
  import { fileHistoryBoundariesToKeep, resolveFileHistoryRetention } from "../../core/file-history-retention.js";
9
9
  import { atomicWriteFile, ensureDir, sanitizePathComponent, sanitizeScope, writeThenLink } from "./fs-atomic.js";
10
10
  import { guardCorruptSink } from "./corrupt-read-sink.js";
@@ -54,6 +54,10 @@ function historyPathComponent(raw) {
54
54
  function descriptorOf(rec) {
55
55
  return rec.keyKind !== undefined && rec.keyFamily !== undefined ? { kind: rec.keyKind, family: rec.keyFamily } : undefined;
56
56
  }
57
+ function declaredDescriptorOf(key, rec) {
58
+ const family = rec.keyFamily ?? "posix";
59
+ return { kind: rec.keyKind ?? (isAbsoluteForFamily(family, key) ? "absolute" : "root-relative"), family };
60
+ }
57
61
  const STALE_JOURNAL_MS = 60 * 60 * 1000;
58
62
  function pidIsAlive(pid) {
59
63
  if (!Number.isInteger(pid) || pid <= 0)
@@ -426,10 +430,14 @@ export class FileFileHistoryStore {
426
430
  }
427
431
  async trackEditCounted(scope, absPath, env, root, signal) {
428
432
  try {
429
- const { key, kind, family } = describeTrackKey(root, absPath);
433
+ const corrupt = (fault) => ({ ok: false, error: { code: "track_failed", message: `file history for scope "${scope}" is unreadable — refusing to mint a first-touch record over an unusable graph`, ...fault } });
434
+ const keyed = this.readTrackedState(scope);
435
+ if (keyed.corrupt)
436
+ return corrupt(keyed.fault);
437
+ const { key, kind, family } = await trackKeyForEdit(env, root, absPath, (k) => keyed.tracked.get(k), signal);
430
438
  const before = this.readTrackedState(scope);
431
439
  if (before.corrupt)
432
- return { ok: false, error: { code: "track_failed", message: `file history for scope "${scope}" is unreadable — refusing to mint a first-touch record over an unusable graph`, ...before.fault } };
440
+ return corrupt(before.fault);
433
441
  const existing = before.tracked.get(key);
434
442
  if (existing !== undefined) {
435
443
  if (existing.observedByLaterTouch !== true) {
@@ -480,8 +488,8 @@ export class FileFileHistoryStore {
480
488
  }
481
489
  async annulTrackCounted(scope, absPath, root, verify) {
482
490
  try {
483
- const key = trackKeyOf(root, absPath);
484
491
  const state = this.readTrackedState(scope);
492
+ const key = trackKeyForAnnul(root, absPath, (k) => state.tracked.has(k));
485
493
  if (state.corrupt) {
486
494
  return { ok: false, error: { code: "track_failed", message: `file history for scope "${scope}" is unreadable — the first-touch record (if any) was left in place; repair the graph before retraction can be judged`, ...state.fault } };
487
495
  }
@@ -634,11 +642,17 @@ export class FileFileHistoryStore {
634
642
  nestedSetAdd(this.spentAttempts, scope, entryId);
635
643
  return { ok: false, error: { code: "aborted", message: `boundary capture for entry "${entryId}" aborted` } };
636
644
  }
637
- const resolved = resolveTrackKey(root, key, descriptorOf(rec));
645
+ const resolved = await resolveTrackedFile(env, root, key, rec.versions, descriptorOf(rec), signal);
638
646
  if (!resolved.ok) {
639
647
  nestedSetAdd(this.spentAttempts, scope, entryId);
640
648
  return { ok: false, error: { code: "snapshot_failed", message: resolved.reason } };
641
649
  }
650
+ if ("held" in resolved) {
651
+ const last = rec.versions[rec.versions.length - 1];
652
+ if (last !== undefined)
653
+ staged.set(key, { kind: "unchanged", version: last.version });
654
+ continue;
655
+ }
642
656
  const cap = await captureFileBackupViaEnv(env, resolved.abs, root, signal);
643
657
  if (cap.state === "aborted") {
644
658
  nestedSetAdd(this.spentAttempts, scope, entryId);
@@ -650,13 +664,13 @@ export class FileFileHistoryStore {
650
664
  }
651
665
  const last = rec.versions[rec.versions.length - 1];
652
666
  if (cap.state === "absent") {
653
- if (last !== undefined && last.blobHash === null)
667
+ if (last !== undefined && last.blobHash === null && !placeProvenDifferent(last.parentIdent, cap.parentIdent))
654
668
  staged.set(key, { kind: "unchanged", version: last.version });
655
669
  else
656
670
  staged.set(key, { kind: "changed", blobHash: null, ...(cap.parentIdent !== undefined ? { parentIdent: cap.parentIdent } : {}) });
657
671
  continue;
658
672
  }
659
- if (last !== undefined && last.blobHash === cap.hash && !modeProvenDifferent(last.mode, cap.mode)) {
673
+ if (last !== undefined && last.blobHash === cap.hash && !modeProvenDifferent(last.mode, cap.mode) && !placeProvenDifferent(last.parentIdent, cap.parentIdent)) {
660
674
  staged.set(key, { kind: "unchanged", version: last.version });
661
675
  continue;
662
676
  }
@@ -724,7 +738,7 @@ export class FileFileHistoryStore {
724
738
  safeRm(journal);
725
739
  }
726
740
  }
727
- async restore(scope, entryId, env, root, signal) {
741
+ async restore(scope, entryId, env, root, signal, options) {
728
742
  const ledger = EMPTY_LEDGER();
729
743
  let modeNotPreserved = 0;
730
744
  try {
@@ -794,6 +808,7 @@ export class FileFileHistoryStore {
794
808
  ...(version.mode !== undefined ? { mode: version.mode } : {}),
795
809
  ...(version.parentIdent !== undefined ? { parentIdent: version.parentIdent } : {}),
796
810
  ...(signal !== undefined ? { signal } : {}),
811
+ ...(options?.unplacedHistoryRecordedUnder !== undefined ? { unplacedHistoryRecordedUnder: options.unplacedHistoryRecordedUnder } : {}),
797
812
  });
798
813
  }
799
814
  catch (err) {
@@ -804,7 +819,7 @@ export class FileFileHistoryStore {
804
819
  else if (applied.outcome === "identical")
805
820
  ledger.identicalSkipped.push(key);
806
821
  else if (applied.outcome === "refused")
807
- ledger.refused.push({ path: key, reason: applied.reason, class: applied.class });
822
+ ledger.refused.push({ path: key, reason: applied.reason, class: applied.class, ...(applied.action !== undefined ? { action: applied.action } : {}), ...(applied.recordedUnder !== undefined ? { recordedUnder: applied.recordedUnder } : {}) });
808
823
  else
809
824
  ledger.failed.push({ path: key, reason: applied.reason });
810
825
  if ((applied.outcome === "applied" || applied.outcome === "identical") && applied.modeNotPreserved === true)
@@ -821,49 +836,10 @@ export class FileFileHistoryStore {
821
836
  const bpath = this.tryBoundaryPath(scope, entryId);
822
837
  return bpath !== null && this.readBoundary(bpath) !== null;
823
838
  }
824
- async diffStats(scope, entryId, env, root) {
839
+ async diffStats(scope, entryId, env, root, options) {
825
840
  try {
826
- const bpath = this.tryBoundaryPath(scope, entryId);
827
- const boundary = bpath === null ? null : this.readBoundary(bpath);
828
- if (boundary === null)
829
- return null;
830
- const state = this.readTrackedState(scope);
831
- if (state.corrupt)
832
- return null;
833
- const filesChanged = [];
834
- let insertions = 0;
835
- let deletions = 0;
836
- for (const key of [...state.tracked.keys()].sort()) {
837
- const rec = state.tracked.get(key);
838
- let targetVersion = boundary.get(key);
839
- if (targetVersion === undefined) {
840
- if (!rec.baseAvailable)
841
- continue;
842
- targetVersion = 1;
843
- }
844
- const version = rec.versions.find((v) => v.version === targetVersion);
845
- const resolved = resolveTrackKey(root, key, descriptorOf(rec));
846
- if (version === undefined || !resolved.ok)
847
- continue;
848
- let targetBytes;
849
- if (version.blobHash !== null) {
850
- try {
851
- targetBytes = readFileSync(this.blobPath(version.blobHash));
852
- }
853
- catch {
854
- continue;
855
- }
856
- if (createHash("sha256").update(targetBytes).digest("hex") !== version.blobHash)
857
- continue;
858
- }
859
- const delta = await previewFileDelta(env, resolved.abs, version.blobHash, targetBytes, version.mode);
860
- if (delta === undefined)
861
- continue;
862
- filesChanged.push(key);
863
- insertions += delta.insertions;
864
- deletions += delta.deletions;
865
- }
866
- return { filesChanged, insertions, deletions };
841
+ const plan = await planFileHistoryRestore(this, { scope, entryId, env, root, ...(options !== undefined ? { options } : {}) });
842
+ return plan.restore.outcome === "failed" && plan.restore.files.length === 0 ? null : plan.diffStats;
867
843
  }
868
844
  catch {
869
845
  return null;
@@ -1202,7 +1178,8 @@ export class FileFileHistoryStore {
1202
1178
  safeRm(staging);
1203
1179
  try {
1204
1180
  ensureDir(join(staging, "boundaries"));
1205
- const adoptedRows = [...source];
1181
+ const adoptedRows = [...source].filter(([key, rec]) => fileHistoryEntryTravels(declaredDescriptorOf(key, rec)));
1182
+ const adopted = new Set(adoptedRows.map(([key]) => key));
1206
1183
  const doc = { formatVersion: "file-history/1", scope: toScope, tracked: adoptedRows, digest: trackedDigest(adoptedRows) };
1207
1184
  atomicWriteFile(join(this.base, "tmp"), join(staging, "tracked.json"), JSON.stringify(doc));
1208
1185
  for (const id of sourceBoundaries) {
@@ -1216,7 +1193,8 @@ export class FileFileHistoryStore {
1216
1193
  }
1217
1194
  }
1218
1195
  const sourceCommittedAt = bp === null ? undefined : this.boundaryOrderOf(bp);
1219
- const bdoc = { formatVersion: "file-history/1", files: [...mapping], digest: boundaryDigest([...mapping]), ...(sourceCommittedAt !== undefined ? { committedAt: sourceCommittedAt } : {}) };
1196
+ const files = [...mapping].filter(([key]) => adopted.has(key));
1197
+ const bdoc = { formatVersion: "file-history/1", files, digest: boundaryDigest(files), ...(sourceCommittedAt !== undefined ? { committedAt: sourceCommittedAt } : {}) };
1220
1198
  atomicWriteFile(join(this.base, "tmp"), join(staging, "boundaries", `${historyPathComponent(id)}.json`), JSON.stringify(bdoc));
1221
1199
  }
1222
1200
  const carried = this.carryConsumedIds(fromScope, toScope);
@@ -1253,24 +1231,28 @@ export class FileFileHistoryStore {
1253
1231
  return unexportable(boundaryIds.what, boundaryIds.fault);
1254
1232
  if (tracked.size === 0 && boundaryIds.length === 0)
1255
1233
  return { ok: true, history: null };
1234
+ const travels = [...tracked.entries()].map(([key, rec]) => ({ key, rec, desc: declaredDescriptorOf(key, rec) })).filter((t) => fileHistoryEntryTravels(t.desc));
1235
+ const kept = new Set(travels.map((t) => t.key));
1236
+ const omitted = tracked.size - travels.length;
1256
1237
  const boundaries = [];
1257
1238
  for (const entryId of [...boundaryIds].sort()) {
1258
1239
  const bp = this.tryBoundaryPath(scope, entryId);
1259
1240
  const mapping = bp === null ? null : this.readBoundary(bp);
1260
1241
  if (mapping === null)
1261
1242
  return unexportable(`a boundary ("${entryId}") that stopped being usable while it was exported`, {});
1262
- boundaries.push({ entryId, files: [...mapping.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([relOrAbsPath, version]) => ({ relOrAbsPath, version })) });
1243
+ boundaries.push({ entryId, files: [...mapping.entries()].filter(([key]) => kept.has(key)).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([relOrAbsPath, version]) => ({ relOrAbsPath, version })) });
1263
1244
  }
1264
1245
  const history = {
1265
1246
  formatVersion: "file-history/1",
1266
- tracked: [...tracked.entries()]
1267
- .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
1268
- .map(([key, rec]) => ({
1247
+ ...(omitted > 0 ? { absoluteEntriesOmitted: omitted } : {}),
1248
+ tracked: travels
1249
+ .sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0))
1250
+ .map(({ key, rec, desc }) => ({
1269
1251
  relOrAbsPath: key,
1270
- keyKind: rec.keyKind ?? (isAbsoluteForFamily(rec.keyFamily ?? "posix", key) ? "absolute" : "root-relative"),
1271
- keyFamily: rec.keyFamily ?? "posix",
1252
+ keyKind: desc.kind,
1253
+ keyFamily: desc.family,
1272
1254
  baseAvailable: rec.baseAvailable,
1273
- versions: rec.versions.map((v) => ({ version: v.version, blobHash: v.blobHash, ...(v.mode !== undefined ? { mode: v.mode } : {}), ...(v.parentIdent !== undefined ? { parentIdent: v.parentIdent } : {}), backupTime: v.backupTime })),
1255
+ versions: rec.versions.map((v) => ({ version: v.version, blobHash: v.blobHash, ...(v.mode !== undefined ? { mode: v.mode } : {}), ...(v.parentIdent !== undefined && fileHistoryParentIdentTravels(v.parentIdent) ? { parentIdent: v.parentIdent } : {}), backupTime: v.backupTime })),
1274
1256
  })),
1275
1257
  boundaries,
1276
1258
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sema-agent/core",
3
- "version": "7.68.1",
3
+ "version": "7.68.3",
4
4
  "description": "Stateless, task-oriented AI agent core",
5
5
  "type": "module",
6
6
  "license": "BUSL-1.1",
@@ -132,7 +132,7 @@
132
132
  "dependencies": {
133
133
  "@modelcontextprotocol/client": "2.4.0",
134
134
  "@modelcontextprotocol/core": "2.4.0",
135
- "@sema-agent/primitives": "7.68.1",
135
+ "@sema-agent/primitives": "7.68.3",
136
136
  "typebox": "1.1.39",
137
137
  "undici": "7.30.2"
138
138
  },
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "_comment": "design/87 L3 — frozen public export surface of src/index.ts (name -> kind). DO NOT edit by hand to silence a red test. A removed/changed entry = a BREAKING change: name every removed entry in the CHANGELOG's BREAKING lines (what was removed / who is hurt / what to read instead) and update this fixture in the SAME commit. Regenerate via REGEN in test/export-surface.test.ts.",
3
3
  "_tierComment": "#435 v1 — machine-readable layering of the public surface: stable = demonstrated by README.md / src/examples; internal = an `Internal`-marked name or a runner/engine deep-subtree declaration (the model seam src/engine/llm is excluded — it is the BYOM contract, not an engine internal); advanced = a supported export the front door does not walk you through. THIS IS AN INITIAL HEURISTIC, derived mechanically and expected to be refined ticket by ticket: no human reviewed these 1700+ entries one by one, and nothing here claims otherwise. Known bias: a short or English-word export name (ok, err, Result, Usage) can match ordinary prose in README.md and land `stable` on a coincidence. Every export MUST carry a tier — a new export with no row fails the gate in export-surface.test.ts.",
4
- "count": 3358,
4
+ "count": 3366,
5
5
  "exports": {
6
6
  "A2ATaskState": "type",
7
7
  "A2ATaskStateReversal": "type",
@@ -685,9 +685,11 @@
685
685
  "FileHistoryKeyFamily": "type",
686
686
  "FileHistoryMintProof": "type",
687
687
  "FileHistoryRefusalClass": "type",
688
+ "FileHistoryRestoreOptions": "interface",
688
689
  "FileHistoryRestoreResult": "type",
689
690
  "FileHistoryResult": "type",
690
691
  "FileHistoryRetentionPolicy": "interface",
692
+ "FileHistoryRewindFile": "interface",
691
693
  "FileHistoryScopeParts": "interface",
692
694
  "FileHistoryStore": "interface",
693
695
  "FileHistoryStoreError": "class",
@@ -2678,11 +2680,17 @@
2678
2680
  "fileHistoryBlobExchangeOf": "function",
2679
2681
  "fileHistoryBoundariesToKeep": "function",
2680
2682
  "fileHistoryDescribeTrackKey": "function",
2683
+ "fileHistoryEntryTravels": "function",
2681
2684
  "fileHistoryExportDigest": "function",
2682
2685
  "fileHistoryModeProvenDifferent": "function",
2686
+ "fileHistoryParentIdentTravels": "function",
2687
+ "fileHistoryPlaceProvenDifferent": "function",
2683
2688
  "fileHistoryResolveTrackKey": "function",
2689
+ "fileHistoryResolveTrackedFile": "function",
2684
2690
  "fileHistoryScopeOf": "function",
2685
2691
  "fileHistoryStoreContract": "function",
2692
+ "fileHistoryTrackKeyForAnnul": "function",
2693
+ "fileHistoryTrackKeyForEdit": "function",
2686
2694
  "fileHistoryTrackKeyOf": "function",
2687
2695
  "fileOpAccessOf": "function",
2688
2696
  "fileSessionCaptureRecordStore": "function",
@@ -4045,9 +4053,11 @@
4045
4053
  "FileHistoryKeyFamily": "advanced",
4046
4054
  "FileHistoryMintProof": "advanced",
4047
4055
  "FileHistoryRefusalClass": "advanced",
4056
+ "FileHistoryRestoreOptions": "advanced",
4048
4057
  "FileHistoryRestoreResult": "advanced",
4049
4058
  "FileHistoryResult": "advanced",
4050
4059
  "FileHistoryRetentionPolicy": "advanced",
4060
+ "FileHistoryRewindFile": "advanced",
4051
4061
  "FileHistoryScopeParts": "internal",
4052
4062
  "FileHistoryStore": "advanced",
4053
4063
  "FileHistoryStoreError": "advanced",
@@ -6038,11 +6048,17 @@
6038
6048
  "fileHistoryBlobExchangeOf": "advanced",
6039
6049
  "fileHistoryBoundariesToKeep": "advanced",
6040
6050
  "fileHistoryDescribeTrackKey": "advanced",
6051
+ "fileHistoryEntryTravels": "advanced",
6041
6052
  "fileHistoryExportDigest": "advanced",
6042
6053
  "fileHistoryModeProvenDifferent": "advanced",
6054
+ "fileHistoryParentIdentTravels": "advanced",
6055
+ "fileHistoryPlaceProvenDifferent": "advanced",
6043
6056
  "fileHistoryResolveTrackKey": "advanced",
6057
+ "fileHistoryResolveTrackedFile": "advanced",
6044
6058
  "fileHistoryScopeOf": "internal",
6045
6059
  "fileHistoryStoreContract": "advanced",
6060
+ "fileHistoryTrackKeyForAnnul": "advanced",
6061
+ "fileHistoryTrackKeyForEdit": "advanced",
6046
6062
  "fileHistoryTrackKeyOf": "advanced",
6047
6063
  "fileOpAccessOf": "advanced",
6048
6064
  "fileSessionCaptureRecordStore": "advanced",
@@ -0,0 +1,39 @@
1
+ {
2
+ "repo": "core",
3
+ "package": "@sema-agent/core-stores-sql",
4
+ "version": "7.68.2",
5
+ "from": "d1b75e444fcc96b605fb95122839fdf072afa855",
6
+ "to": "v7.68.2",
7
+ "added": [],
8
+ "removed": [],
9
+ "changed": [],
10
+ "subpaths": [],
11
+ "subpathsUnread": [
12
+ "from",
13
+ "to"
14
+ ],
15
+ "narrowed": [],
16
+ "faces": {
17
+ "open": [],
18
+ "source": null
19
+ },
20
+ "closedSetMembers": [],
21
+ "closedSetsUnreadable": [],
22
+ "typeKeys": [],
23
+ "typeKeysUnreadableArms": [],
24
+ "typeKeysFlattenedCount": 3,
25
+ "signatures": [],
26
+ "versionLiterals": [],
27
+ "declarationMoves": [],
28
+ "mintMoves": [],
29
+ "criteriaObserves": [],
30
+ "consumersHint": {
31
+ "cli": [],
32
+ "server": [],
33
+ "sdk": [],
34
+ "note": "scanned cli@36acd8ff server@027f7b3e4 sdk@6e55f1b — a name listed is MENTIONED there today, which is evidence of consumption, not proof of it"
35
+ },
36
+ "breakingCount": 0,
37
+ "breakingItems": [],
38
+ "toResolvedAt": "cfb33338f80b8ea4507a562d17a11da874d70f1a"
39
+ }
@@ -0,0 +1,39 @@
1
+ {
2
+ "repo": "core",
3
+ "package": "@sema-agent/core-stores-sql",
4
+ "version": "7.68.3",
5
+ "from": "55c147112bd479cd3898e00829c387d78fdb21f7",
6
+ "to": "v7.68.3",
7
+ "added": [],
8
+ "removed": [],
9
+ "changed": [],
10
+ "subpaths": [],
11
+ "subpathsUnread": [
12
+ "from",
13
+ "to"
14
+ ],
15
+ "narrowed": [],
16
+ "faces": {
17
+ "open": [],
18
+ "source": null
19
+ },
20
+ "closedSetMembers": [],
21
+ "closedSetsUnreadable": [],
22
+ "typeKeys": [],
23
+ "typeKeysUnreadableArms": [],
24
+ "typeKeysFlattenedCount": 3,
25
+ "signatures": [],
26
+ "versionLiterals": [],
27
+ "declarationMoves": [],
28
+ "mintMoves": [],
29
+ "criteriaObserves": [],
30
+ "consumersHint": {
31
+ "cli": [],
32
+ "server": [],
33
+ "sdk": [],
34
+ "note": "scanned cli@a51393fd server@027f7b3e4 sdk@6e55f1b — a name listed is MENTIONED there today, which is evidence of consumption, not proof of it"
35
+ },
36
+ "breakingCount": 0,
37
+ "breakingItems": [],
38
+ "toResolvedAt": "d04d328eb407a57a9cc6656453ab8d0422254265"
39
+ }