axstack 0.67.0 → 0.69.0

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 (97) hide show
  1. package/README.md +2 -2
  2. package/docs/host-operations.md +3 -6
  3. package/docs/installation.md +10 -10
  4. package/docs/workflows.md +7 -11
  5. package/package.json +2 -2
  6. package/profiles/presets/claude-only.json +2 -2
  7. package/profiles/presets/codex-only.json +2 -2
  8. package/profiles/presets/mixed.json +2 -2
  9. package/skills/axstack/references/automations.md +18 -33
  10. package/skills/axstack/references/autopilot.md +1 -0
  11. package/skills/axstack/references/capture-receipts.md +22 -0
  12. package/skills/axstack/references/contracts.md +1 -1
  13. package/skills/axstack/references/lifecycle.md +1 -1
  14. package/skills/axstack/references/live-run.md +59 -0
  15. package/skills/axstack/references/local-artifacts.md +1 -1
  16. package/skills/axstack/references/pr-shape.md +13 -16
  17. package/skills/axstack/references/review-manager-prompt.md +38 -42
  18. package/skills/axstack/references/role-roster.md +1 -1
  19. package/skills/axstack/references/run-record.md +7 -5
  20. package/skills/axstack/references/test-audit-weekly.md +1 -2
  21. package/skills/axstack/references/ui-verification.md +5 -3
  22. package/skills/axstack/references/workspace-hygiene.md +3 -0
  23. package/skills/axstack/sandbox/Dockerfile +28 -0
  24. package/skills/axstack/sandbox/host-execution.md +14 -0
  25. package/skills/axstack/sandbox/inventory.json +503 -0
  26. package/skills/axstack/sandbox/launcher-capture.js +63 -0
  27. package/skills/axstack/sandbox/launcher-contract.schema.json +341 -0
  28. package/skills/axstack/sandbox/launcher-contracts.js +35 -0
  29. package/skills/axstack/sandbox/launcher-docker.js +75 -0
  30. package/skills/axstack/sandbox/launcher-host-budget.json +10 -0
  31. package/skills/axstack/sandbox/launcher-host.js +165 -0
  32. package/skills/axstack/sandbox/launcher-host.json +5 -0
  33. package/skills/axstack/sandbox/launcher-image.json +4 -0
  34. package/skills/axstack/sandbox/launcher-interface.md +7 -0
  35. package/skills/axstack/sandbox/launcher-policy.js +135 -0
  36. package/skills/axstack/sandbox/launcher-policy.json +121 -0
  37. package/skills/axstack/sandbox/launcher-runtime.js +157 -0
  38. package/skills/axstack/sandbox/launcher-source.js +72 -0
  39. package/skills/axstack/sandbox/launcher.js +106 -0
  40. package/skills/axstack/sandbox/network-address.js +39 -0
  41. package/skills/axstack/sandbox/network-firewall.js +81 -0
  42. package/skills/axstack/sandbox/network-rules.js +86 -0
  43. package/skills/axstack/sandbox/network-runtime.js +109 -0
  44. package/skills/axstack/sandbox/network.js +49 -0
  45. package/skills/axstack/sandbox/probes-android-platform.xml +17 -0
  46. package/skills/axstack/sandbox/probes-check.js +185 -0
  47. package/skills/axstack/sandbox/probes-exec.js +20 -0
  48. package/skills/axstack/sandbox/probes-image-build.js +129 -0
  49. package/skills/axstack/sandbox/probes-image-pins.json +370 -0
  50. package/skills/axstack/sandbox/probes-link-local.js +25 -0
  51. package/skills/axstack/sandbox/probes-storage.js +33 -0
  52. package/skills/axstack/sandbox/probes-udp.js +44 -0
  53. package/skills/axstack/sandbox/probes.js +239 -0
  54. package/skills/axstack/sandbox/proxy-command.js +6 -0
  55. package/skills/axstack/sandbox/proxy-config.json +9 -0
  56. package/skills/axstack/sandbox/proxy-dns.js +114 -0
  57. package/skills/axstack/sandbox/proxy-policy.js +22 -0
  58. package/skills/axstack/sandbox/proxy.js +119 -0
  59. package/skills/axstack/sandbox/reap.md +7 -0
  60. package/skills/axstack/sandbox/sidecars.json +153 -0
  61. package/skills/axstack/sandbox/storage-checks.js +39 -0
  62. package/skills/axstack/sandbox/storage-cleanup.js +49 -0
  63. package/skills/axstack/sandbox/storage-execution.js +110 -0
  64. package/skills/axstack/sandbox/storage-plan.js +78 -0
  65. package/skills/axstack/sandbox/storage-support.js +91 -0
  66. package/skills/axstack/sandbox/storage.js +75 -0
  67. package/skills/axstack/scripts/archive-evidence.js +2 -2
  68. package/skills/axstack/scripts/capture-identity.js +122 -0
  69. package/skills/axstack/scripts/check-run.js +248 -0
  70. package/skills/axstack/scripts/check-staged-file-tokens.js +6 -3
  71. package/skills/axstack/scripts/command-capture.js +81 -0
  72. package/skills/axstack/scripts/evidence-inspector.js +182 -0
  73. package/skills/axstack/scripts/git-argv.js +6 -0
  74. package/skills/axstack/scripts/image-evidence.js +183 -0
  75. package/skills/axstack/scripts/lane-owner.js +183 -0
  76. package/skills/axstack/scripts/pr-digest.js +17 -1
  77. package/skills/axstack/scripts/pr-fresh.js +139 -0
  78. package/skills/axstack/scripts/pr-shape.js +54 -29
  79. package/skills/axstack/scripts/readiness-run.js +3 -75
  80. package/skills/axstack/scripts/readiness.js +2 -2
  81. package/skills/axstack/scripts/run-init.js +13 -11
  82. package/skills/axstack/scripts/schedule-drift.js +221 -4
  83. package/skills/axstack-audit/references/record.md +1 -1
  84. package/skills/axstack-brainstorm/references/arena.md +5 -5
  85. package/skills/axstack-explain/references/inline-pages.md +8 -4
  86. package/skills/axstack-implement/SKILL.md +6 -5
  87. package/skills/axstack-review/SKILL.md +2 -3
  88. package/skills/axstack-review/references/candidate-brief.md +12 -21
  89. package/skills/axstack-review/references/codebase-brief.md +1 -0
  90. package/skills/axstack-review/references/codebase-mode.md +4 -1
  91. package/skills/axstack-review/references/codebase-report.md +2 -1
  92. package/skills/axstack-review/references/peer-mode.md +11 -12
  93. package/skills/axstack-review/references/review-candidate.md +2 -2
  94. package/skills/axstack-review/references/review-receipt.md +8 -3
  95. package/skills/axstack-verify/SKILL.md +10 -4
  96. package/skills/axstack-watch/references/proven-verification.md +3 -2
  97. package/skills/axstack-watch/references/readiness.md +56 -61
@@ -0,0 +1,153 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "images": [
4
+ {
5
+ "id": "postgres16",
6
+ "image": "docker.io/library/postgres@sha256:a49f7438ba03589f9b1ca062f2da82e899b48ea1dc50d2449fa09a70be83ebca",
7
+ "argv": [
8
+ "sh",
9
+ "-ec",
10
+ "printf 'sandbox:x:61234:61234:sandbox:/tmp:/bin/sh\\n' > /tmp/passwd; printf 'sandbox:x:61234:\\n' > /tmp/group; export NSS_WRAPPER_PASSWD=/tmp/passwd NSS_WRAPPER_GROUP=/tmp/group LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libnss_wrapper.so; initdb -D /var/lib/postgresql/data --username=postgres --auth=trust; exec postgres -D /var/lib/postgresql/data -c listen_addresses='*' -c unix_socket_directories=/tmp"
11
+ ],
12
+ "declaredVolumes": [
13
+ {
14
+ "path": "/var/lib/postgresql/data",
15
+ "bytes": 536870912,
16
+ "uid": 61234,
17
+ "gid": 61234,
18
+ "mode": "0700",
19
+ "noexec": true
20
+ }
21
+ ]
22
+ },
23
+ {
24
+ "id": "postgres17",
25
+ "image": "docker.io/library/postgres@sha256:40865bc877a289da75963d97d72b59633f639fc5af7a4e856bfa3714cae5b536",
26
+ "argv": [
27
+ "sh",
28
+ "-ec",
29
+ "printf 'sandbox:x:61234:61234:sandbox:/tmp:/bin/sh\\n' > /tmp/passwd; printf 'sandbox:x:61234:\\n' > /tmp/group; export NSS_WRAPPER_PASSWD=/tmp/passwd NSS_WRAPPER_GROUP=/tmp/group LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libnss_wrapper.so; initdb -D /var/lib/postgresql/data --username=postgres --auth=trust; exec postgres -D /var/lib/postgresql/data -c listen_addresses='*' -c unix_socket_directories=/tmp"
30
+ ],
31
+ "declaredVolumes": [
32
+ {
33
+ "path": "/var/lib/postgresql/data",
34
+ "bytes": 536870912,
35
+ "uid": 61234,
36
+ "gid": 61234,
37
+ "mode": "0700",
38
+ "noexec": true
39
+ }
40
+ ]
41
+ },
42
+ {
43
+ "id": "redis",
44
+ "image": "docker.io/library/redis@sha256:2e3eb11462c4e3759e6972678dd051d150ff54b1e60714b3c33b701260172a90",
45
+ "argv": [
46
+ "redis-server",
47
+ "--save",
48
+ "60 1",
49
+ "--appendonly",
50
+ "no",
51
+ "--protected-mode",
52
+ "no",
53
+ "--bind",
54
+ "0.0.0.0",
55
+ "--dir",
56
+ "/data"
57
+ ],
58
+ "declaredVolumes": [
59
+ {
60
+ "path": "/data",
61
+ "bytes": 268435456,
62
+ "uid": 61234,
63
+ "gid": 61234,
64
+ "mode": "0700",
65
+ "noexec": true
66
+ }
67
+ ]
68
+ },
69
+ {
70
+ "id": "azurite",
71
+ "image": "mcr.microsoft.com/azure-storage/azurite@sha256:830430c1da1a2d537e08f3e6764dd1f5ae00cf0346bcaf625b968ec3f0971fd5",
72
+ "argv": [
73
+ "azurite",
74
+ "--location",
75
+ "/data",
76
+ "--blobHost",
77
+ "0.0.0.0",
78
+ "--queueHost",
79
+ "0.0.0.0",
80
+ "--tableHost",
81
+ "0.0.0.0",
82
+ "--silent"
83
+ ],
84
+ "declaredVolumes": [
85
+ {
86
+ "path": "/data",
87
+ "bytes": 268435456,
88
+ "uid": 61234,
89
+ "gid": 61234,
90
+ "mode": "0700",
91
+ "noexec": true
92
+ }
93
+ ]
94
+ },
95
+ {
96
+ "id": "prometheus",
97
+ "image": "docker.io/prom/prometheus@sha256:efd719c99d83b060d9daefdcf00360461adf279f45ef5391f8d111892118753e",
98
+ "argv": [
99
+ "--config.file=/etc/prometheus/prometheus.yml",
100
+ "--storage.tsdb.path=/prometheus",
101
+ "--storage.tsdb.retention.size=128MB"
102
+ ],
103
+ "declaredVolumes": [
104
+ {
105
+ "path": "/prometheus",
106
+ "bytes": 268435456,
107
+ "uid": 61234,
108
+ "gid": 61234,
109
+ "mode": "0700",
110
+ "noexec": true
111
+ }
112
+ ]
113
+ },
114
+ {
115
+ "id": "grafana",
116
+ "image": "docker.io/grafana/grafana@sha256:b28bae15e219c998fb0e0424ed724930cc61b1f61fb404d47c862f9a23f9e572",
117
+ "argv": [
118
+ "cfg:default.paths.data=/var/lib/grafana",
119
+ "cfg:default.paths.logs=/tmp",
120
+ "cfg:default.paths.plugins=/var/lib/grafana/plugins"
121
+ ],
122
+ "declaredVolumes": [
123
+ {
124
+ "path": "/var/lib/grafana",
125
+ "bytes": 268435456,
126
+ "uid": 61234,
127
+ "gid": 61234,
128
+ "mode": "0700",
129
+ "noexec": true
130
+ }
131
+ ]
132
+ },
133
+ {
134
+ "id": "otel",
135
+ "image": "docker.io/otel/opentelemetry-collector@sha256:310a800ad69ee430e7c541796852a242c9c7db97aaad4daa5ccf843c525fbdb2",
136
+ "argv": [
137
+ "--config",
138
+ "yaml:receivers:\n otlp:\n protocols:\n grpc:\n endpoint: 0.0.0.0:4317\n http:\n endpoint: 0.0.0.0:4318\nexporters:\n debug: {}\nservice:\n pipelines:\n traces:\n receivers: [otlp]\n exporters: [debug]\n"
139
+ ],
140
+ "declaredVolumes": []
141
+ },
142
+ {
143
+ "id": "nginx",
144
+ "image": "docker.io/library/nginx@sha256:552e7481ca93ffccd046aa658dbbed22caefbc09c66fa7cd247cbb90b8a5c609",
145
+ "argv": [
146
+ "sh",
147
+ "-ec",
148
+ "printf '%s\\n' 'pid /tmp/nginx.pid; error_log /dev/stderr; events {} http { access_log /dev/stdout; client_body_temp_path /tmp/client; proxy_temp_path /tmp/proxy; fastcgi_temp_path /tmp/fastcgi; uwsgi_temp_path /tmp/uwsgi; scgi_temp_path /tmp/scgi; server { listen 8080; location / { return 200 \"sandbox\\n\"; } } }' > /tmp/nginx.conf; exec nginx -c /tmp/nginx.conf -g 'daemon off;'"
149
+ ],
150
+ "declaredVolumes": []
151
+ }
152
+ ]
153
+ }
@@ -0,0 +1,39 @@
1
+ import { planStorage } from './storage-plan.js';
2
+ import { hold, term, commands, planContext, privateDirectory, readRecord } from './storage-support.js';
3
+
4
+ export function checksWithRunner(run) {
5
+ const { checked } = commands(run);
6
+ return async function checkMountedStorage({ owner, plan, policy, containerIds }) {
7
+ const context = planContext(owner, plan);
8
+ const canonical = planStorage({ runId: owner.runId, ownedDir: context.dir, policy });
9
+ if (JSON.stringify(plan.checks) !== JSON.stringify(canonical.checks)) throw Error('Modified storage checks');
10
+ await privateDirectory(context.dir);
11
+ const record = await readRecord(context.record, owner, plan);
12
+ if (!record || record.user !== policy.user || !/^[1-9]\d*:[1-9]\d*$/.test(policy.user) ||
13
+ !Number.isSafeInteger(record.filesystemBytes) || record.filesystemBytes < 1 || record.filesystemBytes > plan.bytes) throw hold('Missing recorded filesystem geometry/user');
14
+ if (!Array.isArray(containerIds) || !containerIds.length || new Set(containerIds).size !== containerIds.length ||
15
+ containerIds.some(id => !/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(id))) throw hold('Mounting-container enumeration missing/invalid');
16
+ const mounted = (await checked(['docker', 'ps', '--quiet', '--filter', `volume=${plan.volumeName}`])).split(/\s+/).filter(Boolean);
17
+ if (!mounted.length) throw hold('No running mounting containers observed');
18
+ // Docker ps returns IDs, so callers bind those exact observations rather
19
+ // than guessing names. Recheck at each fetch/test/probe phase.
20
+ if (mounted.some(id => !containerIds.includes(id))) throw hold('A mounting container was omitted from the capped-filesystem checks');
21
+ const terms = [];
22
+ for (const containerId of containerIds) {
23
+ let container;
24
+ try { [container] = JSON.parse(await checked(['docker', 'inspect', containerId])); } catch { throw hold('Mounting container inspection unknown'); }
25
+ if (container?.Config?.User !== policy.user || !container.Mounts?.some(mount => mount.Type === 'volume' &&
26
+ mount.Name === plan.volumeName && mount.Destination === plan.checks[0].path)) throw hold('Container user or dependency-volume binding differs');
27
+ const results = [];
28
+ for (const step of plan.checks) results.push(await checked(['docker', 'exec', '--user', policy.user, containerId, ...step.argv]));
29
+ const [uid, filesystem, total] = results;
30
+ const [type, options] = (filesystem ?? '').split(/\s+/);
31
+ const [blockSize, blocks] = (total ?? '').split(/\s+/).map(Number);
32
+ if (uid !== policy.user.split(':')[0] || type !== 'ext4' || !['nosuid', 'nodev'].every(option => options?.split(',').includes(option)) ||
33
+ blockSize !== 4096 || !Number.isSafeInteger(blocks) || blocks * blockSize !== record.filesystemBytes) throw hold(`Capped-filesystem check failed in ${containerId}`);
34
+ terms.push(term(`capped-filesystem:${containerId}`, `uid=${uid}; ext4 nosuid,nodev`,
35
+ `total=${record.filesystemBytes}; image cap=${plan.bytes}; inodes=${plan.inodes}`));
36
+ }
37
+ return terms;
38
+ };
39
+ }
@@ -0,0 +1,49 @@
1
+ import { containerList } from './storage-plan.js';
2
+ import { hold, term, commands, planContext, privateDirectory, statOrNull, loops, ownLoops,
3
+ readRecord, inspectVolume, validateVolume, unlinkOwned, unrelatedLoops } from './storage-support.js';
4
+
5
+ export function cleanupWithRunner(run) {
6
+ const { raw, checked } = commands(run);
7
+ return async function cleanupStorage({ owner, plan }) {
8
+ const context = planContext(owner, plan);
9
+ await privateDirectory(context.dir);
10
+ const noContainers = async () => {
11
+ if (await checked(containerList(owner.runId)) ||
12
+ await checked(['docker', 'ps', '--all', '--quiet', '--filter', `volume=${plan.volumeName}`])) {
13
+ throw hold('Storage cleanup waits for every owned/mounting container to be removed');
14
+ }
15
+ };
16
+ await noContainers();
17
+ const record = await readRecord(context.record, owner, plan);
18
+ const image = await statOrNull(plan.imageFile);
19
+ const volume = await inspectVolume(raw, plan);
20
+ const before = await loops(checked);
21
+ if ((image || volume || ownLoops(before, plan).length) && !record) throw hold('Storage ownership record absent; preserve assets');
22
+ if (image && (!image.isFile() || image.uid !== process.getuid() || image.nlink !== 1 || image.mode & 0o077)) throw hold('Unsafe backing image; preserve it');
23
+ if (volume) {
24
+ validateVolume(volume, owner);
25
+ await noContainers();
26
+ // Non-zero removal can mean another reaper won; only readback decides.
27
+ await raw(['docker', 'volume', 'rm', plan.volumeName]);
28
+ if (await inspectVolume(raw, plan)) throw hold('Owned volume remains after removal');
29
+ }
30
+ await noContainers();
31
+ // Re-enumerate after volume removal, never detach the stale device recorded
32
+ // in Docker options: after a reboot it could belong to a snap.
33
+ const attached = await loops(checked);
34
+ for (const loop of ownLoops(attached, plan)) {
35
+ const fresh = ownLoops(await loops(checked), plan);
36
+ if (!fresh.some(candidate => candidate.name === loop.name)) continue;
37
+ await raw(['losetup', '--detach', loop.name]);
38
+ }
39
+ const readback = await loops(checked);
40
+ if (ownLoops(readback, plan).length) throw hold('Owned loop device still attached after detach; backing image retained');
41
+ if (unrelatedLoops(before, plan) !== unrelatedLoops(readback, plan)) throw hold('Unrelated loop-device state changed during cleanup; preserve image');
42
+ // Last observation precedes deletion, including when no device survived reboot.
43
+ await unlinkOwned(plan.imageFile);
44
+ await unlinkOwned(context.record);
45
+ return [term('storage-containers-gone', 'Independent run-label and volume-user checks: no containers'),
46
+ term('storage-volume-gone', plan.volumeName), term('storage-loop-detached', plan.imageFile, 'No loop remains attached to this exact backing file; unbound nodes may remain'),
47
+ term('storage-image-gone', plan.imageFile)];
48
+ };
49
+ }
@@ -0,0 +1,110 @@
1
+ import { checksWithRunner } from './storage-checks.js';
2
+ import { cleanupWithRunner } from './storage-cleanup.js';
3
+ import { planStorage, volumeCreate } from './storage-plan.js';
4
+ import { fs, hold, term, commands, runCommand, planContext, privateDirectory, statOrNull,
5
+ loops, ownLoops, writeRecord, inspectVolume, validateVolume, unrelatedLoops } from './storage-support.js';
6
+
7
+ export function createStorage({ run = runCommand } = {}) {
8
+ const { raw, checked } = commands(run);
9
+ let pending = Promise.resolve();
10
+ const serial = fn => input => {
11
+ const next = pending.then(() => fn(input));
12
+ pending = next.catch(() => {});
13
+ return next;
14
+ };
15
+ return { prepareStorage: serial(prepareStorage), cleanupStorage: serial(cleanupWithRunner(run)), checkMountedStorage: serial(checksWithRunner(run)) };
16
+
17
+ async function prepareStorage({ owner, plan, policy }) {
18
+ const context = planContext(owner, plan);
19
+ const canonical = planStorage({ runId: owner.runId, ownedDir: context.dir, policy });
20
+ if (JSON.stringify(canonical) !== JSON.stringify(plan)) throw Error('Modified storage plan');
21
+ await privateDirectory(context.dir);
22
+ const terms = [];
23
+ for (const binary of ['truncate', 'fallocate', 'mkfs.ext4', 'dumpe2fs', 'losetup', 'lsblk', 'docker', 'modprobe', 'test', 'cat']) {
24
+ await checked(['which', binary]);
25
+ }
26
+ await checked(['test', '-c', '/dev/loop-control']);
27
+ const cmdline = await checked(['cat', '/proc/cmdline']);
28
+ const moduleOptions = await checked(['modprobe', '--showconfig']);
29
+ const maxLoop = await checked(['cat', '/sys/module/loop/parameters/max_loop']);
30
+ if (!/^\d+$/.test(maxLoop) || /(?:^|\s)(?:loop\.)?max_loop=/.test(cmdline) ||
31
+ moduleOptions.split('\n').some(line => /^\s*options\s+loop\s/.test(line) && /\bmax_loop\s*=/.test(line))) {
32
+ throw hold('On-demand loop allocation unknown/limited by max_loop configuration');
33
+ }
34
+ // The sysfs value (e.g. 8) is not itself a module-option declaration.
35
+ terms.push(term('loop-allocatable', '/dev/loop-control present; no max_loop in cmdline or effective modprobe options',
36
+ `sysfs max_loop=${maxLoop}; free-loop observations still required`));
37
+ const before = await loops(checked);
38
+ if (ownLoops(before, plan).length || await statOrNull(plan.imageFile) || await statOrNull(context.record) || await inspectVolume(raw, plan)) {
39
+ throw hold('Leftover owned loop, image, record or volume requires cleanup before admission');
40
+ }
41
+ const candidate = await checked(['losetup', '--find']);
42
+ terms.push(await reserveBeforeAttach(before, candidate, plan));
43
+ const record = { owner, imageFile: plan.imageFile, volumeName: plan.volumeName, bytes: plan.bytes, inodes: plan.inodes };
44
+ // Reserve ownership before creating the image: a SIGKILL cannot leave an
45
+ // unlabelled image between creation and loop/volume registration.
46
+ try { await writeRecord(context.record, record, true); } catch (error) { throw hold(`Cannot reserve image ownership: ${error.message}`); }
47
+ const image = await fs.open(plan.imageFile, 'wx', 0o600);
48
+ await image.close();
49
+ for (const id of ['truncate', 'preallocate', 'format']) await checked(plan.steps.find(step => step.id === id).argv);
50
+ const geometry = await checked(plan.steps.find(step => step.id === 'geometry').argv);
51
+ const fields = Object.fromEntries(geometry.split('\n').map(line => {
52
+ const match = /^([^:]+):\s*(\d+)\s*$/.exec(line);
53
+ return match ? [match[1], Number(match[2])] : [];
54
+ }).filter(entry => entry.length));
55
+ const blockSize = fields['Block size'];
56
+ const overhead = fields['Overhead clusters'];
57
+ const clusterSize = fields['Cluster size'] ?? blockSize;
58
+ const total = fields['Block count'] * blockSize - overhead * clusterSize;
59
+ if (blockSize !== 4096 || clusterSize !== blockSize || fields['Block count'] * blockSize !== plan.bytes ||
60
+ fields['Inode count'] !== plan.inodes || !Number.isSafeInteger(total) || total <= 0 || total > plan.bytes) throw hold('Formatted ext4 geometry is unknown or differs from recorded caps');
61
+ record.filesystemBytes = total;
62
+ record.user = policy.user;
63
+ await writeRecord(context.record, record);
64
+ terms.push(term('filesystem-total', total, `ext4 image cap=${plan.bytes}; inodes=${plan.inodes}; metadata overhead=${overhead * clusterSize}`));
65
+ const loopDevice = await checked(plan.steps.find(step => step.id === 'attach').argv);
66
+ if (!/^\/dev\/loop\d+$/.test(loopDevice)) throw hold('Attach did not return an exact loop device');
67
+ const after = await loops(checked);
68
+ const own = ownLoops(after, plan);
69
+ if (own.length !== 1 || own[0].name !== loopDevice || own[0].autoclear) throw hold('Attached backing file/device/autoclear readback differs');
70
+ if (unrelatedLoops(after, plan) !== unrelatedLoops(before, plan)) throw hold('Unrelated loop-device state changed during attachment');
71
+ const spare = await checked(['losetup', '--find']);
72
+ if (!/^\/dev\/loop\d+$/.test(spare) || after.some(loop => loop.name === spare)) throw hold('One further free/allocatable loop device is required');
73
+ terms.push(term('free-loop-reserve', `${loopDevice} attached; ${spare} free/allocatable; admission lock is caller-held`));
74
+ await checked(volumeCreate(plan.volumeName, loopDevice, owner));
75
+ const volume = await inspectVolume(raw, plan);
76
+ if (!volume) throw hold('Created volume missing on readback');
77
+ validateVolume(volume, owner, loopDevice);
78
+ terms.push(term('storage-prepared', plan.imageFile, loopDevice, plan.volumeName, 'autoclear=false; nosuid,nodev; no host mount'));
79
+ return { loopDevice, terms };
80
+ }
81
+
82
+ async function reserveBeforeAttach(before, candidate, plan) {
83
+ const evidence = [`attachment candidate=${candidate}`, 'No image created or loop attached by this preparation'];
84
+ const uncertain = reason => Object.assign(hold('One further free/allocatable loop device is unproven before attachment'), {
85
+ terms: [{ id: 'free-loop-reserve', status: 'unknown', evidence: [...evidence, reason] }],
86
+ });
87
+ let result;
88
+ try { result = await raw(plan.steps.find(step => step.id === 'reserve-before-attach').argv); }
89
+ catch (error) { throw uncertain(`Loop capacity observation unavailable: ${error.message}`); }
90
+ if (result.exitCode !== 0) throw uncertain(`Loop capacity observation failed: ${result.stderr}`);
91
+ let devices;
92
+ try { devices = JSON.parse(result.stdout).blockdevices; } catch { throw uncertain('Invalid loop capacity JSON'); }
93
+ if (!Array.isArray(devices) || devices.some(device => !device || typeof device.type !== 'string')) throw uncertain('Loop capacity enumeration is incomplete');
94
+ const loopDevices = devices.filter(device => device.type === 'loop');
95
+ if (loopDevices.some(device => !/^\/dev\/loop\d+$/.test(device.path ?? '') ||
96
+ !/^\d+$/.test(String(device.size)) || !Number.isSafeInteger(Number(device.size)))) throw uncertain('Loop capacity fields are incomplete');
97
+ const available = [...new Set(loopDevices.filter(device => Number(device.size) === 0 &&
98
+ !before.some(loop => loop.name === device.path)).map(device => device.path))];
99
+ evidence.push(`observed unbound loop devices=${JSON.stringify(available)}`);
100
+ const spare = available.find(device => device !== candidate);
101
+ if (!available.includes(candidate) || !spare) throw uncertain('Two distinct unbound devices required; configuration alone does not prove an allocatable spare');
102
+ for (const device of [candidate, spare]) {
103
+ let node;
104
+ try { node = await raw(['test', '-b', device]); }
105
+ catch (error) { throw uncertain(`Loop device node observation unavailable: ${device}: ${error.message}`); }
106
+ if (node.exitCode !== 0) throw uncertain(`Observed loop device node unavailable: ${device}: ${node.stderr}`);
107
+ }
108
+ return term('free-loop-reserve-before-attach', ...evidence, `spare=${spare}; admission lock is caller-held`);
109
+ }
110
+ }
@@ -0,0 +1,78 @@
1
+ // Private storage wire construction. Braced values are bound after observations,
2
+ // never expanded by a shell. B binds each check's containerId and mount path.
3
+ const LOOP = '{loopDevice}';
4
+ export const MOUNT_PATH = '/dependencies';
5
+ export const LOOP_LIST = ['losetup', '--list', '--json', '--output', 'NAME,BACK-FILE,AUTOCLEAR'];
6
+ export const LABEL = 'axstack.sandbox';
7
+
8
+ export function storageLabels(owner) {
9
+ return { [LABEL]: 'true', ...Object.fromEntries(Object.entries(owner).map(([key, value]) => [`${LABEL}.${key}`, String(value)])) };
10
+ }
11
+
12
+ export function storageNames(runId, ownedDir) {
13
+ if (typeof runId !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(runId) ||
14
+ typeof ownedDir !== 'string' || !/^\/(?:[a-zA-Z0-9_.-]+\/)*[a-zA-Z0-9_.-]+$/.test(ownedDir) ||
15
+ ownedDir.split('/').some(part => part === '.' || part === '..')) throw Error('Invalid storage run/path');
16
+ return { imageFile: `${ownedDir}/axstack.sandbox-${runId}.img`, volumeName: `axstack-sandbox-${runId}-deps` };
17
+ }
18
+
19
+ export function validateOwner(owner) {
20
+ if (owner?.label !== LABEL || !Number.isSafeInteger(owner.pid) || owner.pid < 1 ||
21
+ !/^\d+$/.test(owner.startTimeTicks ?? '') || !/^[a-zA-Z0-9-]+$/.test(owner.bootId ?? '')) throw Error('Invalid storage owner');
22
+ }
23
+
24
+ /** @param {{runId:string, ownedDir:string, policy:Pick<import('./launcher-contracts.js').LaunchPolicy, 'user'|'dependencyBytes'|'dependencyInodes'>}} input
25
+ * @returns {import('./launcher-contracts.js').StoragePlan} */
26
+ export function planStorage({ runId, ownedDir, policy }) {
27
+ const names = storageNames(runId, ownedDir);
28
+ if (!/^[1-9]\d*:[1-9]\d*$/.test(policy?.user ?? '') ||
29
+ !Number.isSafeInteger(policy.dependencyBytes) || policy.dependencyBytes % 4096 !== 0 ||
30
+ !Number.isSafeInteger(policy.dependencyInodes) || policy.dependencyInodes < 1 ||
31
+ policy.dependencyBytes < policy.dependencyInodes * 256 + 32 * 1024 ** 2) throw Error('Invalid ext4 geometry/user');
32
+ /** @param {string} id @param {'prepare'|'check'|'cleanup'} phase @param {string[]} argv @returns {import('./launcher-contracts.js').Step} */
33
+ const step = (id, phase, argv, container = false) => ({ id, phase, executor: container ? 'container' : 'host',
34
+ containerId: null, argv, path: container ? MOUNT_PATH : names.imageFile });
35
+ const owner = { runId, pid: '{owner.pid}', startTimeTicks: '{owner.startTimeTicks}', bootId: '{owner.bootId}' };
36
+ return { ...names, filesystem: 'ext4', bytes: policy.dependencyBytes, inodes: policy.dependencyInodes,
37
+ mountOptions: ['nosuid', 'nodev'], keepFreeLoops: 1, autoclear: false,
38
+ steps: [
39
+ step('loop-control', 'prepare', ['test', '-c', '/dev/loop-control']),
40
+ step('loop-cmdline', 'prepare', ['cat', '/proc/cmdline']),
41
+ step('loop-module-options', 'prepare', ['modprobe', '--showconfig']),
42
+ step('loop-module-limit', 'prepare', ['cat', '/sys/module/loop/parameters/max_loop']),
43
+ step('loops-before', 'prepare', LOOP_LIST),
44
+ step('free-loop', 'prepare', ['losetup', '--find']),
45
+ step('reserve-before-attach', 'prepare', ['lsblk', '--all', '--json', '--bytes', '--output', 'PATH,TYPE,SIZE']),
46
+ step('truncate', 'prepare', ['truncate', '--size', String(policy.dependencyBytes), names.imageFile]),
47
+ step('preallocate', 'prepare', ['fallocate', '--length', String(policy.dependencyBytes), names.imageFile]),
48
+ step('format', 'prepare', ['mkfs.ext4', '-F', '-b', '4096', '-I', '256', '-N', String(policy.dependencyInodes), '-m', '0',
49
+ '-E', `root_owner=${policy.user},lazy_itable_init=0,lazy_journal_init=0`, names.imageFile]),
50
+ step('geometry', 'prepare', ['dumpe2fs', '-h', names.imageFile]),
51
+ step('attach', 'prepare', ['losetup', '--find', '--show', '--nooverlap', names.imageFile]),
52
+ step('loops-attached', 'prepare', LOOP_LIST),
53
+ step('reserve-loop', 'prepare', ['losetup', '--find']),
54
+ step('volume', 'prepare', volumeCreate(names.volumeName, LOOP, owner)),
55
+ step('volume-readback', 'prepare', ['docker', 'volume', 'inspect', names.volumeName]),
56
+ ],
57
+ checks: [step('non-root', 'check', ['id', '-u'], true),
58
+ step('filesystem', 'check', ['findmnt', '--noheadings', '--raw', '--output', 'FSTYPE,OPTIONS', '--target', MOUNT_PATH], true),
59
+ step('total-size', 'check', ['stat', '-f', '-c', '%S %b', MOUNT_PATH], true)],
60
+ cleanup: [
61
+ step('containers', 'cleanup', containerList(runId)),
62
+ step('volume-inspect', 'cleanup', ['docker', 'volume', 'inspect', names.volumeName]),
63
+ step('volume-remove', 'cleanup', ['docker', 'volume', 'rm', names.volumeName]),
64
+ step('backing-files', 'cleanup', LOOP_LIST),
65
+ step('detach', 'cleanup', ['losetup', '--detach', LOOP]),
66
+ step('detach-readback', 'cleanup', LOOP_LIST),
67
+ step('image-remove', 'cleanup', ['unlink', names.imageFile]),
68
+ ] };
69
+ }
70
+
71
+ export function volumeCreate(name, device, owner) {
72
+ return ['docker', 'volume', 'create', '--driver', 'local',
73
+ ...Object.entries(storageLabels(owner)).flatMap(([key, value]) => ['--label', `${key}=${value}`]),
74
+ '--opt', 'type=ext4', '--opt', 'o=nosuid,nodev', '--opt', `device=${device}`, name];
75
+ }
76
+ export function containerList(runId) {
77
+ return ['docker', 'ps', '--all', '--quiet', '--filter', `label=${LABEL}=true`, '--filter', `label=${LABEL}.runId=${runId}`];
78
+ }
@@ -0,0 +1,91 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import { LOOP_LIST, storageNames, storageLabels, validateOwner } from './storage-plan.js';
3
+ export { fs };
4
+
5
+ export function hold(message) { return Object.assign(Error(message), { sandboxHold: true }); }
6
+ export function term(id, ...evidence) { return { id, status: 'pass', evidence: evidence.map(String) }; }
7
+ export async function runCommand(argv) {
8
+ const child = Bun.spawn(argv, { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe',
9
+ env: { PATH: '/usr/sbin:/usr/bin:/sbin:/bin', LC_ALL: 'C' } });
10
+ const [stdout, stderr, exitCode] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
11
+ return { stdout, stderr, exitCode };
12
+ }
13
+ export function commands(run) {
14
+ const raw = async argv => {
15
+ try { return await run(argv); } catch (error) { throw hold(`Storage command unavailable: ${argv[0]}: ${error.message}`); }
16
+ };
17
+ const checked = async argv => {
18
+ const result = await raw(argv);
19
+ if (result.exitCode !== 0) throw hold(`Storage command failed: ${JSON.stringify(argv)}: ${result.stderr}`);
20
+ return result.stdout.trim();
21
+ };
22
+ return { raw, checked };
23
+ }
24
+ export async function statOrNull(path) {
25
+ try { return await fs.lstat(path); } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
26
+ }
27
+ export function planContext(owner, plan) {
28
+ validateOwner(owner);
29
+ const dir = plan.imageFile.slice(0, plan.imageFile.lastIndexOf('/'));
30
+ const names = storageNames(owner.runId, dir);
31
+ if (plan.imageFile !== names.imageFile || plan.volumeName !== names.volumeName || plan.filesystem !== 'ext4' ||
32
+ plan.autoclear !== false || plan.keepFreeLoops !== 1 || JSON.stringify(plan.mountOptions) !== '["nosuid","nodev"]') throw Error('Storage plan identity mismatch');
33
+ return { dir, record: `${plan.imageFile}.owner.json`, lock: `${dir}/.axstack-storage.lock` };
34
+ }
35
+ export async function privateDirectory(dir) {
36
+ const stat = await fs.lstat(dir);
37
+ if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid() || (stat.mode & 0o077) || await fs.realpath(dir) !== dir) {
38
+ throw hold(`Storage directory must be canonical, private and owned: ${dir}`);
39
+ }
40
+ }
41
+ export async function readRecord(path, owner, plan) {
42
+ const stat = await statOrNull(path);
43
+ if (!stat) return null;
44
+ if (!stat.isFile() || stat.uid !== process.getuid() || stat.nlink !== 1 || stat.mode & 0o077) throw hold('Unsafe storage owner record');
45
+ let record;
46
+ try { record = JSON.parse(await fs.readFile(path, 'utf8')); } catch { throw hold('Unreadable storage owner record'); }
47
+ if (JSON.stringify(record.owner) !== JSON.stringify(owner) || record.imageFile !== plan.imageFile ||
48
+ record.volumeName !== plan.volumeName || record.bytes !== plan.bytes || record.inodes !== plan.inodes) throw hold('Storage owner record does not match');
49
+ return record;
50
+ }
51
+ export async function writeRecord(path, record, exclusive = false) {
52
+ const file = await fs.open(path, exclusive ? 'wx' : 'r+', 0o600);
53
+ try { await file.truncate(0); await file.writeFile(JSON.stringify(record)); await file.sync(); } finally { await file.close(); }
54
+ }
55
+ export async function loops(checked) {
56
+ let data;
57
+ try { data = JSON.parse(await checked(LOOP_LIST)); } catch (error) { throw hold(`Loop readback unknown: ${error.message}`); }
58
+ if (!Array.isArray(data.loopdevices) || data.loopdevices.some(loop => !/^\/dev\/loop\d+$/.test(loop.name) ||
59
+ typeof loop['back-file'] !== 'string' || ![true, false, 0, 1].includes(loop.autoclear))) throw hold('Incomplete loop-device enumeration');
60
+ return data.loopdevices;
61
+ }
62
+ export function ownLoops(list, plan) {
63
+ // No prefix matching: snap and every other backing file are untouched.
64
+ if (list.some(loop => loop['back-file'] === `${plan.imageFile} (deleted)`)) throw hold('Owned backing file was deleted while attached');
65
+ return list.filter(loop => loop['back-file'] === plan.imageFile);
66
+ }
67
+ export async function inspectVolume(raw, plan) {
68
+ const result = await raw(['docker', 'volume', 'inspect', plan.volumeName]);
69
+ if (result.exitCode !== 0) {
70
+ // Do not mistake daemon/API/permission failures for absence.
71
+ if (result.stderr.toLowerCase().includes(`get ${plan.volumeName}: no such volume`)) return null;
72
+ throw hold(`Volume inspection unknown: ${result.stderr}`);
73
+ }
74
+ try {
75
+ const list = JSON.parse(result.stdout);
76
+ if (list.length !== 1 || list[0].Name !== plan.volumeName) throw Error('unexpected volume');
77
+ return list[0];
78
+ } catch { throw hold('Invalid volume readback'); }
79
+ }
80
+ export function validateVolume(volume, owner, device = null) {
81
+ if (volume.Driver !== 'local' || Object.entries(storageLabels(owner)).some(([key, value]) => volume.Labels?.[key] !== value) ||
82
+ volume.Options?.type !== 'ext4' || volume.Options?.o !== 'nosuid,nodev' ||
83
+ !/^\/dev\/loop\d+$/.test(volume.Options?.device ?? '') || (device && volume.Options.device !== device)) throw hold('Volume ownership/options mismatch');
84
+ }
85
+ export async function unlinkOwned(path) {
86
+ try { await fs.unlink(path); } catch (error) { if (error.code !== 'ENOENT') throw error; }
87
+ }
88
+
89
+ export function unrelatedLoops(list, plan) {
90
+ return JSON.stringify(list.filter(loop => loop['back-file'] !== plan.imageFile).sort((a, b) => a.name.localeCompare(b.name)));
91
+ }
@@ -0,0 +1,75 @@
1
+ import { fs, hold, planContext, privateDirectory, statOrNull } from './storage-support.js';
2
+ import { createStorage } from './storage-execution.js';
3
+ export { createStorage } from './storage-execution.js';
4
+ export { planStorage } from './storage-plan.js';
5
+
6
+ /**
7
+ * B holds its host admission lock through attachment. Production mutations also
8
+ * share a persistent advisory lock across processes; never unlink that lock file.
9
+ * @param {{owner:import('./launcher-contracts.js').Owner, plan:import('./launcher-contracts.js').StoragePlan, policy:import('./launcher-contracts.js').LaunchPolicy}} input
10
+ * @returns {Promise<{loopDevice:string, terms:import('./launcher-contracts.js').Term[]}>}
11
+ */
12
+ export async function prepareStorage(input) { return locked('prepareStorage', input); }
13
+ /** @param {{owner:import('./launcher-contracts.js').Owner, plan:import('./launcher-contracts.js').StoragePlan}} input
14
+ * @returns {Promise<import('./launcher-contracts.js').Term[]>} */
15
+ export async function cleanupStorage(input) { return locked('cleanupStorage', input); }
16
+ /**
17
+ * B supplies fresh Docker IDs for every currently mounting container, before
18
+ * its fetch/test/probe command; static checks alone are never containment proof.
19
+ */
20
+ export async function checkMountedStorage(input) { return locked('checkMountedStorage', input); }
21
+
22
+ async function locked(action, input) {
23
+ const context = planContext(input.owner, input.plan);
24
+ await privateDirectory(context.dir);
25
+ try {
26
+ const file = await fs.open(context.lock, 'wx', 0o600);
27
+ await file.close();
28
+ } catch (error) { if (error.code !== 'EEXIST') throw error; }
29
+ const lock = await statOrNull(context.lock);
30
+ if (!lock?.isFile() || lock.nlink !== 1 || lock.uid !== process.getuid() || lock.mode & 0o077) throw hold('Unsafe storage advisory lock');
31
+ // Fixed worker argv/env; JSON travels on stdin, with no shell interpolation.
32
+ let child;
33
+ try {
34
+ child = Bun.spawn(['/usr/bin/flock', '--exclusive', '--timeout', '30', context.lock,
35
+ process.execPath, import.meta.path, '--internal-worker', action], {
36
+ stdin: 'pipe', stdout: 'pipe', stderr: 'pipe', env: { PATH: '/usr/sbin:/usr/bin:/sbin:/bin', LC_ALL: 'C' },
37
+ });
38
+ child.stdin.write(JSON.stringify(input));
39
+ child.stdin.end();
40
+ } catch (error) { throw hold(`Storage lock worker unavailable: ${error.message}`); }
41
+ const [stdout, stderr, exitCode] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
42
+ let result;
43
+ try { result = JSON.parse(stdout); } catch { throw hold(`Storage lock/worker failed (${exitCode}): ${stderr}`); }
44
+ if (exitCode || result.error) throw Object.assign(Error(result.error ?? stderr), { sandboxHold: result.sandboxHold === true, terms: result.terms });
45
+ return result.value;
46
+ }
47
+
48
+ if (import.meta.main) {
49
+ if (process.argv[2] === '--help') {
50
+ console.log(`Usage: storage.js --help | --internal-worker <prepareStorage|cleanupStorage|checkMountedStorage>
51
+ Private launcher storage worker; input JSON on stdin, output JSON on stdout.
52
+ Side effects: prepare creates a private run-owner record, preallocated ext4 image file,
53
+ launcher-attached loop device (no autoclear), labelled Docker local volume nosuid,nodev.
54
+ Cleanup independently checks containers, removes volume, detaches only the exact
55
+ owned backing file, verifies detach readback, then unlinks image and owner record.
56
+ No launcher-side mount or uncapped directory fallback. Checks exec fixed probes as
57
+ policy uid:gid in every mounting container. Spawns fixed host commands and one worker
58
+ under flock; the 0600 .axstack-storage.lock in the owned directory remains in place.
59
+ No network request, prune, timer, agent, retry, merge or scheduling. Caller B owns
60
+ host identity/liveness/budget validation and admission serialization through attach.
61
+ Exit: 0 facts, 1 invalid input/I/O, 2 containment or cleanup hold.`);
62
+ } else if (process.argv[2] === '--internal-worker' && ['prepareStorage', 'cleanupStorage', 'checkMountedStorage'].includes(process.argv[3])) {
63
+ try {
64
+ const input = JSON.parse(await Bun.stdin.text());
65
+ const value = await createStorage()[process.argv[3]](input);
66
+ console.log(JSON.stringify({ value }));
67
+ } catch (error) {
68
+ console.log(JSON.stringify({ error: error.message, sandboxHold: error.sandboxHold === true, terms: error.terms }));
69
+ process.exitCode = error.sandboxHold ? 2 : 1;
70
+ }
71
+ } else {
72
+ console.error('Invalid storage worker flags; use --help');
73
+ process.exitCode = 1;
74
+ }
75
+ }
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env bun
2
- import { gitArgv } from './git-argv.js';
2
+ import { gitArgv, gitEnv } from './git-argv.js';
3
3
  import {
4
4
  chmod,
5
5
  lstat,
@@ -282,7 +282,7 @@ async function verifyRetirementArchive(archiveRoot, archiveDir, identity, files,
282
282
  }
283
283
 
284
284
  function gitOutput(sourceRoot, args) {
285
- const result = Bun.spawnSync(gitArgv('-C', sourceRoot, ...args), { stdout: 'pipe', stderr: 'pipe' });
285
+ const result = Bun.spawnSync(gitArgv('-C', sourceRoot, ...args), { env: gitEnv(), stdout: 'pipe', stderr: 'pipe' });
286
286
  if (result.exitCode !== 0) {
287
287
  fail(`git ${args.join(' ')} failed: ${result.stderr.toString().trim() || `exit ${result.exitCode}`}`);
288
288
  }