@sentropic/artifacts 0.2.17 → 0.2.18
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/CHANGELOG.md +18 -0
- package/dist/adapters/github-forge.d.ts +4 -0
- package/dist/adapters/github-forge.js +88 -0
- package/dist/adapters/github-git-port.d.ts +5 -0
- package/dist/adapters/github-git-port.js +102 -0
- package/dist/adapters/github-http.d.ts +5 -0
- package/dist/adapters/github-http.js +57 -0
- package/dist/adapters/github-receive-pack.d.ts +4 -0
- package/dist/adapters/github-receive-pack.js +49 -0
- package/dist/adapters/postgres-git-bindings.d.ts +7 -0
- package/dist/adapters/postgres-git-bindings.js +110 -0
- package/dist/adapters/postgres-live.d.ts +4 -0
- package/dist/adapters/postgres-live.js +97 -0
- package/dist/adapters/postgres.d.ts +1 -0
- package/dist/adapters/postgres.js +1 -0
- package/dist/git-tool-definitions.d.ts +606 -0
- package/dist/git-tool-definitions.js +14 -0
- package/dist/http.d.ts +6 -0
- package/dist/http.js +20 -2
- package/dist/index.d.ts +13 -0
- package/dist/index.js +12 -0
- package/dist/mcp-core.d.ts +3 -3
- package/dist/mcp-core.js +15 -2
- package/dist/profile/contracts.d.ts +1 -1
- package/dist/profile/contracts.js +4 -0
- package/dist/profile/index.js +8 -1
- package/dist/profile/schemas.js +19 -0
- package/dist/profile/validation.js +5 -1
- package/dist/server/build-contract.d.ts +64 -0
- package/dist/server/build-contract.js +58 -0
- package/dist/server/build-dependencies.d.ts +3 -0
- package/dist/server/build-dependencies.js +122 -0
- package/dist/server/consent-grant.d.ts +91 -0
- package/dist/server/consent-grant.js +89 -0
- package/dist/server/consent-screen.d.ts +21 -0
- package/dist/server/consent-screen.js +52 -0
- package/dist/server/failures.d.ts +3 -2
- package/dist/server/failures.js +30 -0
- package/dist/server/git-bindings.d.ts +8 -0
- package/dist/server/git-bindings.js +113 -0
- package/dist/server/git-contracts.d.ts +98 -0
- package/dist/server/git-contracts.js +1 -0
- package/dist/server/git-port-policy.d.ts +9 -0
- package/dist/server/git-port-policy.js +76 -0
- package/dist/server/git-port-read.d.ts +3 -0
- package/dist/server/git-port-read.js +95 -0
- package/dist/server/git-port-session.d.ts +38 -0
- package/dist/server/git-port-session.js +59 -0
- package/dist/server/git-port-tree.d.ts +8 -0
- package/dist/server/git-port-tree.js +92 -0
- package/dist/server/git-port-write.d.ts +6 -0
- package/dist/server/git-port-write.js +102 -0
- package/dist/server/git-port.d.ts +147 -0
- package/dist/server/git-port.js +8 -0
- package/dist/server/git-projection.d.ts +16 -0
- package/dist/server/git-projection.js +20 -0
- package/dist/server/git-registry.d.ts +37 -0
- package/dist/server/git-registry.js +39 -0
- package/dist/server/live-body.d.ts +3 -0
- package/dist/server/live-body.js +28 -0
- package/dist/server/live-commit-outcome.d.ts +6 -0
- package/dist/server/live-commit-outcome.js +10 -0
- package/dist/server/live-commit.d.ts +11 -0
- package/dist/server/live-commit.js +133 -0
- package/dist/server/live-contracts.d.ts +62 -0
- package/dist/server/live-contracts.js +8 -0
- package/dist/server/live-crypto.d.ts +14 -0
- package/dist/server/live-crypto.js +50 -0
- package/dist/server/live-drafts.d.ts +61 -0
- package/dist/server/live-drafts.js +119 -0
- package/dist/server/live-errors.d.ts +23 -0
- package/dist/server/live-errors.js +9 -0
- package/dist/server/live-mutations.d.ts +18 -0
- package/dist/server/live-mutations.js +83 -0
- package/dist/server/live-read.d.ts +15 -0
- package/dist/server/live-read.js +95 -0
- package/dist/server/live-service.d.ts +3 -0
- package/dist/server/live-service.js +181 -0
- package/dist/server/live-store.d.ts +111 -0
- package/dist/server/live-store.js +80 -0
- package/dist/server/live-tree.d.ts +22 -0
- package/dist/server/live-tree.js +148 -0
- package/dist/server/live-worker.d.ts +10 -0
- package/dist/server/live-worker.js +55 -0
- package/migrations/0010_git_bindings.sql +82 -0
- package/migrations/0011_live_drafts.sql +42 -0
- package/package.json +13 -1
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { ArtifactOperationError } from './failures.js';
|
|
3
|
+
import { persistLiveOverlay } from './live-drafts.js';
|
|
4
|
+
import { applyLiveMutation, liveTreeSha } from './live-tree.js';
|
|
5
|
+
import { liveResponse } from './live-contracts.js';
|
|
6
|
+
export const liveBusy = (reason) => {
|
|
7
|
+
throw new ArtifactOperationError('git_live_conflict', { publicDetails: { reason } });
|
|
8
|
+
};
|
|
9
|
+
export async function mutateLive(input) {
|
|
10
|
+
const { deps, tx, authority, operation, args, base, overlay, currentHeadSha, now } = input;
|
|
11
|
+
let record = tx.record;
|
|
12
|
+
if (args.expectedLiveRevision !== record.revision)
|
|
13
|
+
throw new ArtifactOperationError('git_live_revision_moved');
|
|
14
|
+
const phase = record.runtime?.phase ?? 'DORMANT';
|
|
15
|
+
let action = null;
|
|
16
|
+
if (operation === 'live_control' && args.action === 'stop') {
|
|
17
|
+
if (args.liveSessionId !== record.runtime?.liveSessionId)
|
|
18
|
+
liveBusy('stale_session');
|
|
19
|
+
record.runtime.phase = 'QUIESCING';
|
|
20
|
+
record.runtime.routeEpoch++;
|
|
21
|
+
action = 'stop';
|
|
22
|
+
}
|
|
23
|
+
else {
|
|
24
|
+
if (record.pendingCommit)
|
|
25
|
+
liveBusy('commit_indeterminate');
|
|
26
|
+
if (!['DORMANT', 'LIVE', 'REVIVING'].includes(phase))
|
|
27
|
+
liveBusy('invalid_phase');
|
|
28
|
+
if (operation !== 'live_reset' && record.baseHeadSha !== currentHeadSha && record.changedPaths) {
|
|
29
|
+
throw new ArtifactOperationError('git_live_draft_conflict');
|
|
30
|
+
}
|
|
31
|
+
if (operation === 'live_write') {
|
|
32
|
+
const next = await applyLiveMutation(deps.git, authority.target, base, record.baseHeadSha, overlay, args);
|
|
33
|
+
if (JSON.stringify(next) === JSON.stringify(overlay))
|
|
34
|
+
throw new ArtifactOperationError('git_live_no_changes');
|
|
35
|
+
const touched = new Set([...(args.files ?? []).map((f) => f.path), ...(args.edits ?? []).map((f) => f.path)]);
|
|
36
|
+
const resultingBytes = next.filter(e => touched.has(e.path)).reduce((n, e) => n + Buffer.byteLength(e.text ?? ''), 0);
|
|
37
|
+
if (resultingBytes > 2 * 1024 * 1024 || next.length > Math.min(255, deps.commitPathsMax ?? 255) ||
|
|
38
|
+
next.reduce((n, e) => n + Buffer.byteLength(e.text ?? ''), 0) > Math.min(8 * 1024 * 1024, deps.commitBytesMax ?? 8 * 1024 * 1024)) {
|
|
39
|
+
throw new ArtifactOperationError('limit_exceeded');
|
|
40
|
+
}
|
|
41
|
+
record = await persistLiveOverlay(tx, deps.keys, { identity: record, expectedRevision: record.revision,
|
|
42
|
+
baseHeadSha: record.baseHeadSha, baseTreeSha: record.baseTreeSha,
|
|
43
|
+
liveTreeSha: liveTreeSha(base, next, authority.target), overlay: next }, now);
|
|
44
|
+
action = 'project';
|
|
45
|
+
}
|
|
46
|
+
else if (operation === 'live_reset') {
|
|
47
|
+
for (const entry of overlay) {
|
|
48
|
+
// Validation happened before any GitPort call; no unadmitted saved path is projected.
|
|
49
|
+
if (!entry.path)
|
|
50
|
+
throw new ArtifactOperationError('git_path_refused');
|
|
51
|
+
}
|
|
52
|
+
Object.assign(record, { revision: randomUUID(), baseHeadSha: currentHeadSha, baseTreeSha: base.treeSha,
|
|
53
|
+
liveTreeSha: base.treeSha, objectRef: null, keyVersion: null, digest: null,
|
|
54
|
+
expiresAt: null, changedPaths: 0, draftBytes: 0, tombstone: 'reset' });
|
|
55
|
+
if (phase !== 'DORMANT')
|
|
56
|
+
action = 'project';
|
|
57
|
+
}
|
|
58
|
+
else {
|
|
59
|
+
if (phase !== 'DORMANT' && !(phase === 'REVIVING' && record.runtime?.origin === 'implicit'))
|
|
60
|
+
liveBusy('active_session');
|
|
61
|
+
action = 'project';
|
|
62
|
+
}
|
|
63
|
+
if (action === 'project') {
|
|
64
|
+
if (!record.runtime || phase === 'DORMANT')
|
|
65
|
+
record.runtime = { liveSessionId: randomUUID(), phase: 'REVIVING',
|
|
66
|
+
leaseEpoch: (record.runtime?.leaseEpoch ?? 0) + 1, routeEpoch: (record.runtime?.routeEpoch ?? 0) + 1,
|
|
67
|
+
appliedRevision: null, lastAccessAt: new Date(now).toISOString(), pendingWake: false,
|
|
68
|
+
origin: operation === 'live_control' ? 'explicit' : 'implicit', rowVersion: 1,
|
|
69
|
+
ownerId: authority.ownerId, podUid: null, sourceRevision: record.revision,
|
|
70
|
+
baseHeadSha: record.baseHeadSha, liveTreeSha: record.liveTreeSha,
|
|
71
|
+
idleDeadline: new Date(now + 600000).toISOString(), maximumLifetimeAt: new Date(now + 3600000).toISOString(),
|
|
72
|
+
activeAttemptId: null, stateDetail: null };
|
|
73
|
+
Object.assign(record.runtime, { sourceRevision: record.revision, baseHeadSha: record.baseHeadSha,
|
|
74
|
+
liveTreeSha: record.liveTreeSha, rowVersion: record.runtime.rowVersion + 1 });
|
|
75
|
+
if (operation === 'live_control')
|
|
76
|
+
record.runtime.renewOnReady = true;
|
|
77
|
+
record.runtime.lastAccessAt = new Date(now).toISOString();
|
|
78
|
+
record.runtime.idleDeadline = new Date(now + 600000).toISOString();
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return { action, result: { ...liveResponse(record, currentHeadSha, now), state: record.runtime?.phase ?? 'DORMANT',
|
|
82
|
+
replayed: false, workerPending: record.runtime?.appliedRevision !== record.revision } };
|
|
83
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { GitPort } from './git-port.js';
|
|
2
|
+
import type { LiveAuthority, LiveInvocation } from './live-contracts.js';
|
|
3
|
+
import type { LiveDraftRecord, LiveOverlayEntry } from './live-store.js';
|
|
4
|
+
import type { LiveBaseTree } from './live-tree.js';
|
|
5
|
+
export declare function readLivePage(input: {
|
|
6
|
+
git: GitPort;
|
|
7
|
+
authority: LiveAuthority;
|
|
8
|
+
record: LiveDraftRecord;
|
|
9
|
+
overlay: LiveOverlayEntry[];
|
|
10
|
+
base: LiveBaseTree;
|
|
11
|
+
args: Record<string, any>;
|
|
12
|
+
invocation: LiveInvocation;
|
|
13
|
+
kind: 'read' | 'diff';
|
|
14
|
+
now: number;
|
|
15
|
+
}): Promise<Record<string, unknown>>;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { ArtifactOperationError } from './failures.js';
|
|
3
|
+
import { gitPath } from './git-port-policy.js';
|
|
4
|
+
import { liveDigest } from './live-crypto.js';
|
|
5
|
+
export async function readLivePage(input) {
|
|
6
|
+
const { git, authority, record, overlay, base, args, invocation, kind, now } = input;
|
|
7
|
+
let snapshot = { actorId: invocation.actorId, revision: record.revision,
|
|
8
|
+
baseHeadSha: record.baseHeadSha, offset: 0, kind, expiresAt: now + 15 * 60000,
|
|
9
|
+
...(args.paths ? { paths: args.paths } : {}) };
|
|
10
|
+
if (args.cursor) {
|
|
11
|
+
const saved = record.snapshots?.[args.cursor];
|
|
12
|
+
if (!saved || saved.expiresAt <= now || saved.actorId !== invocation.actorId || saved.kind !== kind ||
|
|
13
|
+
saved.revision !== record.revision || saved.baseHeadSha !== record.baseHeadSha)
|
|
14
|
+
throw new ArtifactOperationError('git_live_snapshot_expired');
|
|
15
|
+
if (args.paths && JSON.stringify(args.paths) !== JSON.stringify(saved.paths))
|
|
16
|
+
throw new ArtifactOperationError('invalid_request');
|
|
17
|
+
snapshot = saved;
|
|
18
|
+
}
|
|
19
|
+
if (args.expectedLiveRevision && args.expectedLiveRevision !== record.revision)
|
|
20
|
+
throw new ArtifactOperationError('git_live_revision_moved');
|
|
21
|
+
const prefix = authority.target.subPath ? authority.target.subPath + '/' : '';
|
|
22
|
+
const baseEntries = new Map(base.entries.filter(e => e.path.startsWith(prefix)).map(e => [e.path.slice(prefix.length), e]));
|
|
23
|
+
const changes = new Map(overlay.map(e => [e.path, e]));
|
|
24
|
+
const candidates = kind === 'diff' ? overlay.map(e => e.path) : snapshot.paths ??
|
|
25
|
+
[...new Set([...baseEntries.keys(), ...changes.keys()])].sort();
|
|
26
|
+
const paths = candidates.filter(path => {
|
|
27
|
+
if (kind === 'read' && changes.get(path)?.text === null)
|
|
28
|
+
return false;
|
|
29
|
+
try {
|
|
30
|
+
gitPath(authority.repository, authority.target, path, false);
|
|
31
|
+
return true;
|
|
32
|
+
}
|
|
33
|
+
catch (cause) {
|
|
34
|
+
if (snapshot.paths)
|
|
35
|
+
throw cause;
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
const files = [];
|
|
40
|
+
const diff = [];
|
|
41
|
+
const recipe = [];
|
|
42
|
+
const deletes = [];
|
|
43
|
+
let bytes = 0;
|
|
44
|
+
let offset = snapshot.offset;
|
|
45
|
+
while (offset < paths.length && files.length + diff.length < 32) {
|
|
46
|
+
const path = paths[offset];
|
|
47
|
+
const change = changes.get(path);
|
|
48
|
+
const entry = baseEntries.get(path);
|
|
49
|
+
let text = change?.text;
|
|
50
|
+
let omitted;
|
|
51
|
+
if (text === undefined && entry) {
|
|
52
|
+
if (entry.type !== 'blob' || !['100644', '100755'].includes(entry.mode))
|
|
53
|
+
omitted = 'path_alias';
|
|
54
|
+
else if ((entry.size ?? 0) > 1024 * 1024)
|
|
55
|
+
omitted = 'too_large';
|
|
56
|
+
else {
|
|
57
|
+
const file = (await git.read(authority.target, { commitSha: record.baseHeadSha, paths: [path] })).files[0];
|
|
58
|
+
if (file && 'text' in file)
|
|
59
|
+
text = file.text;
|
|
60
|
+
else
|
|
61
|
+
omitted = file && 'omitted' in file ? file.omitted : 'binary';
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (text === undefined && !entry)
|
|
65
|
+
throw new ArtifactOperationError('not_found');
|
|
66
|
+
const size = text === null || text === undefined ? 0 : Buffer.byteLength(text);
|
|
67
|
+
if (bytes + size > 2 * 1024 * 1024)
|
|
68
|
+
break;
|
|
69
|
+
bytes += size;
|
|
70
|
+
offset++;
|
|
71
|
+
if (kind === 'read')
|
|
72
|
+
files.push({ path, ...(omitted ? { omitted } :
|
|
73
|
+
{ text, mode: change?.mode ?? entry?.mode, encoding: 'utf-8' }) });
|
|
74
|
+
else {
|
|
75
|
+
diff.push({ path, action: text === null ? 'delete' : entry ? 'replace' : 'create',
|
|
76
|
+
oldDigest: entry?.sha ?? null, newDigest: text === null ? null : liveDigest(text),
|
|
77
|
+
mode: change.mode, ...(text === null ? {} : { text }) });
|
|
78
|
+
if (text === null)
|
|
79
|
+
deletes.push(path);
|
|
80
|
+
else
|
|
81
|
+
recipe.push({ path, text: text });
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
let nextCursor = null;
|
|
85
|
+
if (offset < paths.length) {
|
|
86
|
+
nextCursor = randomUUID();
|
|
87
|
+
const retained = Object.entries(record.snapshots ?? {}).filter(([, value]) => value.expiresAt > now).slice(-31);
|
|
88
|
+
record.snapshots = Object.fromEntries([...retained, [nextCursor, { ...snapshot, offset }]]);
|
|
89
|
+
}
|
|
90
|
+
if (kind === 'read' && record.runtime) {
|
|
91
|
+
record.runtime.lastAccessAt = new Date(now).toISOString();
|
|
92
|
+
record.runtime.idleDeadline = new Date(now + 600000).toISOString();
|
|
93
|
+
}
|
|
94
|
+
return kind === 'read' ? { files, nextCursor } : { diff, files: recipe, deletes, nextCursor };
|
|
95
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { GIT_TOOL_DEFINITIONS } from '../git-tool-definitions.js';
|
|
3
|
+
import { matchesSchema } from '../profile/validation.js';
|
|
4
|
+
import { orderedDigest } from '../profile/json.js';
|
|
5
|
+
import { ArtifactOperationError } from './failures.js';
|
|
6
|
+
import { isGitSha, gitPath } from './git-port-policy.js';
|
|
7
|
+
import { cleanLiveRecord, expireLiveDraft, readLiveOverlay } from './live-drafts.js';
|
|
8
|
+
import { validateLiveMutation } from './live-tree.js';
|
|
9
|
+
import { readLivePage } from './live-read.js';
|
|
10
|
+
import { liveBusy, mutateLive } from './live-mutations.js';
|
|
11
|
+
import { executeLiveCommit } from './live-commit.js';
|
|
12
|
+
import { settleLiveWorker } from './live-worker.js';
|
|
13
|
+
import { liveResponse } from './live-contracts.js';
|
|
14
|
+
export function createLiveService(deps) {
|
|
15
|
+
const now = deps.now ?? Date.now;
|
|
16
|
+
return { async execute(operation, raw, invocation) {
|
|
17
|
+
const args = structuredClone(raw);
|
|
18
|
+
if (!['live_write', 'live_read', 'live_reset', 'live_status', 'live_control', 'git_commit'].includes(operation) ||
|
|
19
|
+
!matchesSchema(args, GIT_TOOL_DEFINITIONS[`artifacts_${operation}`].inputSchema)) {
|
|
20
|
+
throw new ArtifactOperationError('invalid_request');
|
|
21
|
+
}
|
|
22
|
+
const writer = !['live_read', 'live_status'].includes(operation);
|
|
23
|
+
const stop = operation === 'live_control' && args.action === 'stop';
|
|
24
|
+
let authority = await deps.authorize(invocation, args.artifactId);
|
|
25
|
+
const { binding } = authority;
|
|
26
|
+
if (authority.target.storageScopeId !== binding.storageScopeId || authority.target.repoId !== binding.repoId ||
|
|
27
|
+
authority.target.branch !== binding.branch || authority.target.subPath !== binding.subPath ||
|
|
28
|
+
authority.target.principalId !== invocation.actorId)
|
|
29
|
+
throw new ArtifactOperationError('access_denied');
|
|
30
|
+
if (binding.storageScopeId !== invocation.storageScopeId || binding.artifactId !== args.artifactId ||
|
|
31
|
+
(!authority.canReadCode && !stop) || (authority.ownerId !== invocation.actorId &&
|
|
32
|
+
!(operation === 'live_read' && authority.invited && authority.canReadCode)))
|
|
33
|
+
throw new ArtifactOperationError('access_denied');
|
|
34
|
+
if (writer && (!authority.canWrite || !authority.humanLinked) && !stop)
|
|
35
|
+
throw new ArtifactOperationError('access_denied');
|
|
36
|
+
if (writer && (!args.idempotencyKey.trim() || args.idempotencyKey.length > (deps.idempotencyKeyMaxUnits ?? 256))) {
|
|
37
|
+
throw new ArtifactOperationError('invalid_request');
|
|
38
|
+
}
|
|
39
|
+
if (operation === 'live_control' && (stop ? !args.liveSessionId || args.expectedHeadSha !== undefined ||
|
|
40
|
+
(authority.canReadCode && !args.expectedLiveRevision) : !args.expectedHeadSha || !args.expectedLiveRevision || args.liveSessionId !== undefined)) {
|
|
41
|
+
throw new ArtifactOperationError('invalid_request');
|
|
42
|
+
}
|
|
43
|
+
if (writer && !stop) {
|
|
44
|
+
if (binding.state === 'paused')
|
|
45
|
+
throw new ArtifactOperationError('git_binding_paused');
|
|
46
|
+
if (binding.state === 'diverged')
|
|
47
|
+
throw new ArtifactOperationError('git_diverged');
|
|
48
|
+
if (binding.state === 'detached')
|
|
49
|
+
throw new ArtifactOperationError('git_not_attached');
|
|
50
|
+
if (binding.state !== 'attached')
|
|
51
|
+
liveBusy(binding.pendingJobId ? 'pending_publication' : 'invalid_phase');
|
|
52
|
+
if (binding.channel !== 'personal' || binding.personalPrincipalId !== invocation.actorId || binding.executor !== 'sandbox')
|
|
53
|
+
liveBusy('invalid_phase');
|
|
54
|
+
if ((operation === 'live_write' || operation === 'live_control') && (!authority.qualified || !deps.worker))
|
|
55
|
+
throw new ArtifactOperationError('builder_unavailable');
|
|
56
|
+
}
|
|
57
|
+
if (operation === 'live_write' || operation === 'git_commit')
|
|
58
|
+
validateLiveMutation(authority.repository, authority.target, args, 255, operation === 'git_commit' ? 8 * 1024 * 1024 : 2 * 1024 * 1024);
|
|
59
|
+
if (args.paths) {
|
|
60
|
+
if (new Set(args.paths).size !== args.paths.length || args.paths.length > 255)
|
|
61
|
+
throw new ArtifactOperationError('invalid_request');
|
|
62
|
+
for (const path of args.paths)
|
|
63
|
+
gitPath(authority.repository, authority.target, path, false);
|
|
64
|
+
}
|
|
65
|
+
let identity = { storageScopeId: invocation.storageScopeId, artifactId: binding.artifactId, bindingGeneration: binding.generation };
|
|
66
|
+
if (stop) {
|
|
67
|
+
const sessionIdentity = await deps.store.sessionIdentity(invocation.storageScopeId, binding.artifactId, args.liveSessionId);
|
|
68
|
+
if (!sessionIdentity)
|
|
69
|
+
liveBusy('stale_session');
|
|
70
|
+
identity = sessionIdentity;
|
|
71
|
+
}
|
|
72
|
+
const narrowStop = stop && (!authority.canReadCode || identity.bindingGeneration !== binding.generation);
|
|
73
|
+
const expired = await deps.store.transaction(identity, async (tx) => expireLiveDraft(tx, now()));
|
|
74
|
+
const command = writer ? { actorId: invocation.actorId, key: args.idempotencyKey,
|
|
75
|
+
hash: orderedDigest({ operation, args }), operation } : undefined;
|
|
76
|
+
if (command) {
|
|
77
|
+
const prior = await deps.store.transaction(identity, tx => tx.receipt(command.actorId, command.key));
|
|
78
|
+
if (prior) {
|
|
79
|
+
if (prior.hash !== command.hash)
|
|
80
|
+
throw new ArtifactOperationError('command_conflict');
|
|
81
|
+
const runtime = operation === 'live_control' ? await deps.store.transaction(identity, async (tx) => tx.record?.runtime) : null;
|
|
82
|
+
const liveness = operation !== 'live_control' ? {} : runtime?.liveSessionId === prior.result.liveSessionId ?
|
|
83
|
+
{ state: runtime.phase, runtimeState: runtime.phase, appliedRevision: runtime.appliedRevision } :
|
|
84
|
+
{ state: 'DORMANT', runtimeState: 'DORMANT', appliedRevision: null };
|
|
85
|
+
return narrowStop ? { liveSessionId: prior.result.liveSessionId, state: liveness.state } :
|
|
86
|
+
{ ...prior.result, ...liveness, replayed: true };
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (expired && !stop && operation !== 'live_reset') {
|
|
90
|
+
const tombstone = await deps.store.transaction(identity, async (tx) => ({ draftExpiresAt: tx.record?.expiresAt,
|
|
91
|
+
liveRevision: tx.record?.revision, tombstone: true, bindingGeneration: identity.bindingGeneration }));
|
|
92
|
+
throw new ArtifactOperationError('git_live_draft_expired', { publicDetails: tombstone });
|
|
93
|
+
}
|
|
94
|
+
if (writer && !stop && !expired)
|
|
95
|
+
await deps.store.transaction(identity, async (tx) => {
|
|
96
|
+
const overlay = await readLiveOverlay(tx, deps.keys);
|
|
97
|
+
if (overlay.length)
|
|
98
|
+
validateLiveMutation(authority.repository, authority.target, { deletes: overlay.map(e => e.path) });
|
|
99
|
+
});
|
|
100
|
+
if (operation === 'git_commit')
|
|
101
|
+
return executeLiveCommit({ deps, identity, authority, invocation, args, command: command, now: now() });
|
|
102
|
+
const head = stop ? binding.headCommitSha : await deps.git.resolveRef(authority.target, binding.branch);
|
|
103
|
+
if (!stop && !isGitSha(head))
|
|
104
|
+
throw new ArtifactOperationError('invalid_request');
|
|
105
|
+
if (args.expectedHeadSha && (!isGitSha(args.expectedHeadSha) || args.expectedHeadSha.length !== head.length))
|
|
106
|
+
throw new ArtifactOperationError('invalid_request');
|
|
107
|
+
if (args.expectedHeadSha && args.expectedHeadSha !== head)
|
|
108
|
+
throw new ArtifactOperationError('git_head_moved', { publicDetails: { expectedHeadSha: args.expectedHeadSha, actualHeadSha: head } });
|
|
109
|
+
let action = null;
|
|
110
|
+
const result = await deps.store.transaction(identity, async (tx) => {
|
|
111
|
+
const current = await deps.authorize(invocation, args.artifactId);
|
|
112
|
+
if (!stop && current.binding.generation !== identity.bindingGeneration || current.ownerId !== invocation.actorId &&
|
|
113
|
+
!(operation === 'live_read' && current.invited && current.canReadCode) ||
|
|
114
|
+
(!stop && !current.canReadCode))
|
|
115
|
+
throw new ArtifactOperationError('access_denied');
|
|
116
|
+
if (writer && !stop && (!current.canWrite || !current.humanLinked || current.binding.state !== 'attached'))
|
|
117
|
+
throw new ArtifactOperationError('access_denied');
|
|
118
|
+
if ((operation === 'live_write' || operation === 'live_control' && !stop) && !current.qualified)
|
|
119
|
+
throw new ArtifactOperationError('builder_unavailable');
|
|
120
|
+
authority = current;
|
|
121
|
+
if (command) {
|
|
122
|
+
const prior = await tx.receipt(command.actorId, command.key);
|
|
123
|
+
if (prior) {
|
|
124
|
+
if (prior.hash !== command.hash)
|
|
125
|
+
throw new ArtifactOperationError('command_conflict');
|
|
126
|
+
return { ...prior.result, replayed: true };
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
const baseSha = tx.record?.changedPaths ? tx.record.baseHeadSha : head;
|
|
130
|
+
if (!deps.git.snapshot && !stop)
|
|
131
|
+
throw new ArtifactOperationError('capability_unselected');
|
|
132
|
+
const base = stop ? { treeSha: tx.record?.baseTreeSha ?? '', entries: [] } : await deps.git.snapshot(authority.target, operation === 'live_reset' ? head : baseSha);
|
|
133
|
+
if (!tx.record)
|
|
134
|
+
tx.record = cleanLiveRecord(identity, head, base.treeSha, now());
|
|
135
|
+
const record = tx.record;
|
|
136
|
+
if (!stop && operation !== 'live_reset' && record.expiresAt && Date.parse(record.expiresAt) <= now())
|
|
137
|
+
throw new ArtifactOperationError('git_live_draft_expired');
|
|
138
|
+
if (!stop && record.latestVerifiedHeadSha !== head) {
|
|
139
|
+
const fastForward = await deps.git.isAncestor(authority.target, record.latestVerifiedHeadSha, head);
|
|
140
|
+
if (!fastForward && writer)
|
|
141
|
+
throw new ArtifactOperationError('git_diverged');
|
|
142
|
+
if (fastForward) {
|
|
143
|
+
record.latestVerifiedHeadSha = head;
|
|
144
|
+
record.progressSeq++;
|
|
145
|
+
record.lastProgressEventId = 'head:' + head;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
if (!stop && record.baseHeadSha !== head && !record.changedPaths) {
|
|
149
|
+
if (!await deps.git.isAncestor(authority.target, record.baseHeadSha, head))
|
|
150
|
+
throw new ArtifactOperationError('git_diverged');
|
|
151
|
+
Object.assign(record, { revision: randomUUID(), baseHeadSha: head, baseTreeSha: base.treeSha, liveTreeSha: base.treeSha,
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
if (operation === 'live_reset' && record.baseHeadSha !== head &&
|
|
155
|
+
!await deps.git.isAncestor(authority.target, record.baseHeadSha, head))
|
|
156
|
+
throw new ArtifactOperationError('git_diverged');
|
|
157
|
+
const overlay = stop ? [] : operation === 'live_reset' && expired ? [] : await readLiveOverlay(tx, deps.keys);
|
|
158
|
+
if (operation === 'live_read' || operation === 'live_status')
|
|
159
|
+
return { ...liveResponse(record, head),
|
|
160
|
+
dirty: record.changedPaths > 0, changedPaths: record.changedPaths, draftBytes: record.draftBytes,
|
|
161
|
+
jobId: binding.pendingJobId, publicationIntent: record.progressSeq > record.publicationBaselineSeq && binding.autoPublish ? 'deferred' : null,
|
|
162
|
+
retentionWarning: record.expiresAt && Date.parse(record.expiresAt) - now() < 86400000 ? 'expires_within_24_hours' : null,
|
|
163
|
+
...(operation === 'live_read' || args.includeDiff || args.cursor ? await readLivePage({ git: deps.git, authority, record,
|
|
164
|
+
overlay, base, args, invocation, kind: operation === 'live_read' ? 'read' : 'diff', now: now() }) : { nextCursor: null }) };
|
|
165
|
+
if (stop && !authority.canReadCode)
|
|
166
|
+
args.expectedLiveRevision = record.revision;
|
|
167
|
+
const mutation = await mutateLive({ deps, tx, authority, operation, args, base, overlay, currentHeadSha: head, now: now() });
|
|
168
|
+
action = mutation.action;
|
|
169
|
+
await tx.complete(command, { ...mutation.result, revision: tx.record.revision });
|
|
170
|
+
return mutation.result;
|
|
171
|
+
});
|
|
172
|
+
if (!result.replayed && action) {
|
|
173
|
+
const settling = settleLiveWorker({ deps, identity, action, result, now: now() });
|
|
174
|
+
if (action === 'stop')
|
|
175
|
+
await settling;
|
|
176
|
+
else
|
|
177
|
+
void settling;
|
|
178
|
+
}
|
|
179
|
+
return narrowStop ? { liveSessionId: result.liveSessionId, state: result.state } : result;
|
|
180
|
+
} };
|
|
181
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
export interface LiveIdentity {
|
|
2
|
+
storageScopeId: string;
|
|
3
|
+
artifactId: string;
|
|
4
|
+
bindingGeneration: number;
|
|
5
|
+
}
|
|
6
|
+
export interface LiveOverlayEntry {
|
|
7
|
+
path: string;
|
|
8
|
+
text: string | null;
|
|
9
|
+
mode: string;
|
|
10
|
+
}
|
|
11
|
+
export interface LiveRuntimeState {
|
|
12
|
+
liveSessionId: string;
|
|
13
|
+
phase: 'DORMANT' | 'REVIVING' | 'LIVE' | 'QUIESCING' | 'BUILD_PROVISIONING' | 'BUILDING' | 'VERIFYING' | 'PUBLISHING' | 'SAVING' | 'DECOMMISSIONING' | 'RECOVERING' | 'FAILED';
|
|
14
|
+
leaseEpoch: number;
|
|
15
|
+
routeEpoch: number;
|
|
16
|
+
rowVersion: number;
|
|
17
|
+
ownerId: string;
|
|
18
|
+
podUid: string | null;
|
|
19
|
+
sourceRevision: string;
|
|
20
|
+
baseHeadSha: string;
|
|
21
|
+
liveTreeSha: string;
|
|
22
|
+
idleDeadline: string;
|
|
23
|
+
maximumLifetimeAt: string;
|
|
24
|
+
activeAttemptId: string | null;
|
|
25
|
+
stateDetail: string | null;
|
|
26
|
+
appliedRevision: string | null;
|
|
27
|
+
lastAccessAt: string;
|
|
28
|
+
pendingWake: boolean;
|
|
29
|
+
origin?: 'implicit' | 'explicit';
|
|
30
|
+
renewOnReady?: boolean;
|
|
31
|
+
}
|
|
32
|
+
export interface LiveCommitIntent {
|
|
33
|
+
actorId: string;
|
|
34
|
+
key: string;
|
|
35
|
+
hash: string;
|
|
36
|
+
invocationId: string;
|
|
37
|
+
createdAt: string;
|
|
38
|
+
message: string;
|
|
39
|
+
expectedHeadSha: string;
|
|
40
|
+
revision: string;
|
|
41
|
+
liveTreeSha: string;
|
|
42
|
+
policyDigest: string;
|
|
43
|
+
}
|
|
44
|
+
export interface LiveDraftRecord extends LiveIdentity {
|
|
45
|
+
revision: string;
|
|
46
|
+
baseHeadSha: string;
|
|
47
|
+
baseTreeSha: string;
|
|
48
|
+
liveTreeSha: string;
|
|
49
|
+
objectRef: string | null;
|
|
50
|
+
keyVersion: string | null;
|
|
51
|
+
digest: string | null;
|
|
52
|
+
expiresAt: string | null;
|
|
53
|
+
changedPaths: number;
|
|
54
|
+
draftBytes: number;
|
|
55
|
+
tombstone: 'reset' | 'expired' | null;
|
|
56
|
+
runtime: LiveRuntimeState | null;
|
|
57
|
+
pendingCommit: LiveCommitIntent | null;
|
|
58
|
+
progressSeq: number;
|
|
59
|
+
latestVerifiedHeadSha: string;
|
|
60
|
+
publicationBaselineSeq: number;
|
|
61
|
+
publicationBaselineHeadSha: string;
|
|
62
|
+
lastSuccessfulReleaseId: string | null;
|
|
63
|
+
initialUnpublishedBranchEligible: boolean;
|
|
64
|
+
rowVersion: number;
|
|
65
|
+
createdAt: string;
|
|
66
|
+
updatedAt: string;
|
|
67
|
+
lastProgressEventId: string | null;
|
|
68
|
+
snapshots?: Record<string, import('./live-contracts.js').LiveSnapshot>;
|
|
69
|
+
}
|
|
70
|
+
export interface LiveEnvelope {
|
|
71
|
+
nonce: string;
|
|
72
|
+
ciphertext: string;
|
|
73
|
+
tag: string;
|
|
74
|
+
}
|
|
75
|
+
export interface LiveCommand {
|
|
76
|
+
actorId: string;
|
|
77
|
+
key: string;
|
|
78
|
+
hash: string;
|
|
79
|
+
operation: string;
|
|
80
|
+
}
|
|
81
|
+
export type LiveResult = Record<string, unknown> & {
|
|
82
|
+
revision: string;
|
|
83
|
+
};
|
|
84
|
+
export interface LiveReceipt {
|
|
85
|
+
hash: string;
|
|
86
|
+
result: LiveResult;
|
|
87
|
+
}
|
|
88
|
+
export interface LiveTransaction {
|
|
89
|
+
record: LiveDraftRecord | undefined;
|
|
90
|
+
getObject(ref: string): Promise<LiveEnvelope | undefined>;
|
|
91
|
+
putObject(ref: string, envelope: LiveEnvelope): Promise<void>;
|
|
92
|
+
collectObjects(): Promise<number>;
|
|
93
|
+
receipt(actorId: string, key: string): Promise<LiveReceipt | undefined>;
|
|
94
|
+
complete(command: LiveCommand, result: LiveResult): Promise<void>;
|
|
95
|
+
reserveCommit(actorId: string, invocationId: string, now: string): Promise<void>;
|
|
96
|
+
/** Adapter-owned SG1 update in the same transaction as draft cleanup. */
|
|
97
|
+
advanceBinding?(input: {
|
|
98
|
+
expectedHeadSha: string;
|
|
99
|
+
commitSha: string;
|
|
100
|
+
invocationId: string;
|
|
101
|
+
actorId: string;
|
|
102
|
+
now: string;
|
|
103
|
+
}): Promise<void>;
|
|
104
|
+
}
|
|
105
|
+
export interface LiveStore {
|
|
106
|
+
transaction<T>(identity: LiveIdentity, action: (tx: LiveTransaction) => Promise<T>): Promise<T>;
|
|
107
|
+
sessionIdentity(scope: string, artifactId: string, liveSessionId: string): Promise<LiveIdentity | undefined>;
|
|
108
|
+
}
|
|
109
|
+
export declare const liveIdentityKey: (identity: LiveIdentity) => string;
|
|
110
|
+
/** Atomic fake; the persisted representation contains encrypted objects and metadata only. */
|
|
111
|
+
export declare function createMemoryLiveStore(): LiveStore;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { createKeyMutex } from './ports.js';
|
|
2
|
+
import { ArtifactOperationError } from './failures.js';
|
|
3
|
+
export const liveIdentityKey = (identity) => JSON.stringify([
|
|
4
|
+
identity.storageScopeId, identity.artifactId, identity.bindingGeneration
|
|
5
|
+
]);
|
|
6
|
+
/** Atomic fake; the persisted representation contains encrypted objects and metadata only. */
|
|
7
|
+
export function createMemoryLiveStore() {
|
|
8
|
+
const records = new Map();
|
|
9
|
+
const objects = new Map();
|
|
10
|
+
const receipts = new Map();
|
|
11
|
+
const quota = [];
|
|
12
|
+
const mutex = createKeyMutex();
|
|
13
|
+
return {
|
|
14
|
+
async sessionIdentity(scope, artifactId, sessionId) {
|
|
15
|
+
const record = [...records.values()].find(row => row.storageScopeId === scope && row.artifactId === artifactId &&
|
|
16
|
+
row.runtime?.liveSessionId === sessionId);
|
|
17
|
+
return record ? { storageScopeId: scope, artifactId, bindingGeneration: record.bindingGeneration } : undefined;
|
|
18
|
+
},
|
|
19
|
+
transaction: (identity, action) => mutex.runSerialized('live-store', async () => {
|
|
20
|
+
const id = liveIdentityKey(identity);
|
|
21
|
+
const pendingObjects = new Map();
|
|
22
|
+
const pendingReceipts = new Map();
|
|
23
|
+
const pendingQuota = [];
|
|
24
|
+
const receiptKey = (actor, key) => JSON.stringify([identity.storageScopeId, actor, key]);
|
|
25
|
+
const tx = {
|
|
26
|
+
record: structuredClone(records.get(id)),
|
|
27
|
+
getObject: async (ref) => structuredClone(pendingObjects.get(id + ref) ?? objects.get(id + ref)),
|
|
28
|
+
async putObject(ref, value) {
|
|
29
|
+
if (objects.has(id + ref) || pendingObjects.has(id + ref))
|
|
30
|
+
throw new ArtifactOperationError('command_conflict');
|
|
31
|
+
pendingObjects.set(id + ref, structuredClone(value));
|
|
32
|
+
},
|
|
33
|
+
async collectObjects() {
|
|
34
|
+
let count = 0;
|
|
35
|
+
for (const key of objects.keys()) {
|
|
36
|
+
if (key.startsWith(id) && key !== id + tx.record?.objectRef) {
|
|
37
|
+
pendingObjects.set(key, undefined);
|
|
38
|
+
count++;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return count;
|
|
42
|
+
},
|
|
43
|
+
receipt: async (actor, key) => structuredClone(receipts.get(receiptKey(actor, key))),
|
|
44
|
+
async complete(command, result) {
|
|
45
|
+
const key = receiptKey(command.actorId, command.key);
|
|
46
|
+
if (receipts.has(key))
|
|
47
|
+
throw new ArtifactOperationError('command_conflict');
|
|
48
|
+
pendingReceipts.set(key, structuredClone({ hash: command.hash, result }));
|
|
49
|
+
},
|
|
50
|
+
async reserveCommit(actor, invocation, now) {
|
|
51
|
+
const scoped = quota.filter(q => q.scope === identity.storageScopeId && q.at > Date.parse(now) - 3600000);
|
|
52
|
+
if (scoped.some(q => q.invocation === invocation && q.actor === actor))
|
|
53
|
+
return;
|
|
54
|
+
const principalFull = scoped.filter(q => q.actor === actor).length >= 30;
|
|
55
|
+
if (principalFull || scoped.filter(q => q.artifact === identity.artifactId).length >= 60)
|
|
56
|
+
throw new ArtifactOperationError('limit_exceeded', { publicDetails: { quota: 'git_write', scope: principalFull ? 'principal' : 'artifact' } });
|
|
57
|
+
pendingQuota.push({ scope: identity.storageScopeId, artifact: identity.artifactId, actor, invocation, at: Date.parse(now) });
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
const original = JSON.stringify(tx.record);
|
|
61
|
+
const result = await action(tx);
|
|
62
|
+
if (tx.record && JSON.stringify(tx.record) !== original) {
|
|
63
|
+
if (liveIdentityKey(tx.record) !== id)
|
|
64
|
+
throw new ArtifactOperationError('access_denied');
|
|
65
|
+
tx.record.rowVersion = (records.get(id)?.rowVersion ?? 0) + 1;
|
|
66
|
+
records.set(id, structuredClone(tx.record));
|
|
67
|
+
}
|
|
68
|
+
for (const [key, object] of pendingObjects) {
|
|
69
|
+
if (object)
|
|
70
|
+
objects.set(key, object);
|
|
71
|
+
else
|
|
72
|
+
objects.delete(key);
|
|
73
|
+
}
|
|
74
|
+
for (const [key, receipt] of pendingReceipts)
|
|
75
|
+
receipts.set(key, receipt);
|
|
76
|
+
quota.push(...pendingQuota);
|
|
77
|
+
return structuredClone(result);
|
|
78
|
+
})
|
|
79
|
+
};
|
|
80
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { GitPort, GitPortRepository, GitPortTarget, GitTreeEntry } from './git-port.js';
|
|
2
|
+
import type { LiveOverlayEntry } from './live-store.js';
|
|
3
|
+
export interface LiveBaseTree {
|
|
4
|
+
treeSha: string;
|
|
5
|
+
entries: GitTreeEntry[];
|
|
6
|
+
}
|
|
7
|
+
export interface LiveMutation {
|
|
8
|
+
edits?: {
|
|
9
|
+
path: string;
|
|
10
|
+
oldStr: string;
|
|
11
|
+
newStr: string;
|
|
12
|
+
}[];
|
|
13
|
+
files?: {
|
|
14
|
+
path: string;
|
|
15
|
+
text: string;
|
|
16
|
+
}[];
|
|
17
|
+
deletes?: string[];
|
|
18
|
+
}
|
|
19
|
+
export declare function validateLiveMutation(repo: GitPortRepository, target: GitPortTarget, input: LiveMutation, maxPaths?: number, maxBytes?: number): void;
|
|
20
|
+
/** Compute actual Git object IDs without creating forge objects, preserving all excluded base entries. */
|
|
21
|
+
export declare function liveTreeSha(base: LiveBaseTree, overlay: LiveOverlayEntry[], target: GitPortTarget): string;
|
|
22
|
+
export declare function applyLiveMutation(git: GitPort, target: GitPortTarget, base: LiveBaseTree, baseHeadSha: string, before: LiveOverlayEntry[], input: LiveMutation): Promise<LiveOverlayEntry[]>;
|