@pinelabs/skills-cli 0.0.0-stage → 0.5.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.
@@ -0,0 +1,277 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { CliError, ensure, object, keys, portable, allowedTarget, safe, read, json, sha, JOURNAL, LOCK, MANIFEST, LIMIT } from './core.js';
6
+ const MAX_OPERATIONS = 10000;
7
+ function encode(value) { return value === null ? null : value.toString('base64'); }
8
+ export function operation(rel, before, after, executable = false, beforeMode = 0o644, afterMode = executable ? 0o755 : 0o644) { return { path: rel, before: encode(before), after: encode(after), executable, beforeMode: before === null ? null : beforeMode, afterMode: after === null ? null : afterMode }; }
9
+ function bytes(value) {
10
+ if (value === null)
11
+ return null;
12
+ ensure(typeof value === 'string' && value.length <= LIMIT * 2 && /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value), 'Invalid journal content', 'ERECOVERY', 5);
13
+ const data = Buffer.from(value, 'base64');
14
+ ensure(data.toString('base64') === value, 'Noncanonical journal content', 'ERECOVERY', 5);
15
+ return data;
16
+ }
17
+ function equal(a, b) { return a === null || b === null ? a === b : sha(a) === sha(b); }
18
+ async function atomic(root, rel, data, mode = 0o600) {
19
+ let target = await safe(root, rel);
20
+ await fs.mkdir(path.dirname(target), { recursive: true });
21
+ target = await safe(root, rel);
22
+ const temporary = `${target}.pinelabs-${randomUUID()}.tmp`;
23
+ const file = await fs.open(temporary, 'wx', mode);
24
+ try {
25
+ await file.writeFile(data);
26
+ await file.chmod(mode);
27
+ await file.sync();
28
+ }
29
+ finally {
30
+ await file.close();
31
+ }
32
+ try {
33
+ await safe(root, rel);
34
+ await fs.rename(temporary, target);
35
+ }
36
+ finally {
37
+ await fs.unlink(temporary).catch(() => undefined);
38
+ }
39
+ }
40
+ async function installImage(root, op, image, mode) {
41
+ allowedTarget(op.path);
42
+ if (image === null)
43
+ await fs.unlink(await safe(root, op.path));
44
+ else
45
+ await atomic(root, op.path, image, mode ?? 0o600);
46
+ }
47
+ /** Read-only liveness check, shared by dry-run and guarded recovery. Fail closed. */
48
+ async function staleLock(root) {
49
+ const prior = await read(root, LOCK);
50
+ if (prior === null)
51
+ return null;
52
+ let value;
53
+ try {
54
+ const parsed = json(prior);
55
+ object(parsed);
56
+ value = parsed;
57
+ }
58
+ catch {
59
+ throw new CliError('ELOCK', 'Cannot parse lock owner; inspect lock manually', 5);
60
+ }
61
+ ensure(value.host === os.hostname() && Number.isSafeInteger(value.pid) && Number(value.pid) > 0 && Number(value.pid) <= 2147483647, 'Cannot establish stale local-lock owner; inspect lock manually', 'ELOCK', 5);
62
+ let alive = true;
63
+ try {
64
+ process.kill(Number(value.pid), 0);
65
+ }
66
+ catch (e) {
67
+ if (e.code === 'ESRCH')
68
+ alive = false;
69
+ }
70
+ ensure(!alive, 'Lock owner is alive or cannot be verified dead; recovery refused', 'ELOCK', 5);
71
+ return prior;
72
+ }
73
+ async function lock(root, recovery) {
74
+ const dir = await safe(root, '.pinelabs');
75
+ await fs.mkdir(dir, { recursive: true });
76
+ const guardian = '.pinelabs/skills-recovery.lock';
77
+ let guard;
78
+ if (recovery) {
79
+ try {
80
+ guard = await fs.open(await safe(root, guardian), 'wx', 0o600);
81
+ }
82
+ catch {
83
+ throw new CliError('ELOCK', 'Recovery is already claimed. If interrupted, verify its process has stopped before manually removing .pinelabs/skills-recovery.lock.', 5);
84
+ }
85
+ }
86
+ let handle;
87
+ try {
88
+ if (recovery) {
89
+ const prior = await staleLock(root);
90
+ if (prior) {
91
+ ensure(equal(await read(root, LOCK), prior), 'Lock changed during recovery', 'ELOCK', 5);
92
+ await fs.unlink(await safe(root, LOCK));
93
+ }
94
+ }
95
+ try {
96
+ handle = await fs.open(await safe(root, LOCK), 'wx', 0o600);
97
+ }
98
+ catch {
99
+ throw new CliError('ELOCK', 'Installer lock exists. Wait for the owner, or run recover after an interrupted process has stopped.', 5);
100
+ }
101
+ await handle.writeFile(JSON.stringify({ pid: process.pid, host: os.hostname(), token: randomUUID() }));
102
+ await handle.sync();
103
+ }
104
+ catch (e) {
105
+ if (guard) {
106
+ await guard.close();
107
+ await fs.unlink(await safe(root, guardian));
108
+ }
109
+ throw e;
110
+ }
111
+ return async () => {
112
+ await handle.close();
113
+ await fs.unlink(await safe(root, LOCK));
114
+ if (guard) {
115
+ await guard.close();
116
+ await fs.unlink(await safe(root, guardian));
117
+ }
118
+ await fs.rmdir(dir).catch(() => undefined);
119
+ };
120
+ }
121
+ export async function pending(root) { return (await read(root, JOURNAL)) !== null; }
122
+ async function missingDirectories(root, ops) {
123
+ const candidates = new Set(['.pinelabs']);
124
+ for (const op of ops) {
125
+ const parts = op.path.split('/').slice(0, -1);
126
+ for (let i = 1; i <= parts.length; i++)
127
+ candidates.add(parts.slice(0, i).join('/'));
128
+ }
129
+ const missing = [];
130
+ for (const rel of candidates) {
131
+ try {
132
+ await fs.lstat(await safe(root, rel));
133
+ }
134
+ catch (e) {
135
+ if (e.code === 'ENOENT')
136
+ missing.push(rel);
137
+ else
138
+ throw e;
139
+ }
140
+ }
141
+ return missing;
142
+ }
143
+ function parseJournal(data) {
144
+ ensure(data.length <= LIMIT * 4, 'Journal too large', 'ERECOVERY', 5);
145
+ let value;
146
+ try {
147
+ value = JSON.parse(data.toString('utf8'));
148
+ }
149
+ catch {
150
+ throw new CliError('ERECOVERY', 'Invalid journal JSON; retained for manual inspection', 5);
151
+ }
152
+ object(value);
153
+ keys(value, ['schemaVersion', 'state', 'id', 'operations', 'createdDirectories']);
154
+ ensure(value.schemaVersion === 1 && value.state === 'applying' && typeof value.id === 'string', 'Unsupported journal', 'ERECOVERY', 5);
155
+ ensure(Array.isArray(value.operations) && value.operations.length <= MAX_OPERATIONS, 'Invalid journal operations', 'ERECOVERY', 5);
156
+ const seen = new Set();
157
+ for (const op of value.operations) {
158
+ object(op);
159
+ keys(op, ['path', 'before', 'after', 'executable', 'beforeMode', 'afterMode']);
160
+ ensure(typeof op.path === 'string' && typeof op.executable === 'boolean', 'Invalid operation', 'ERECOVERY', 5);
161
+ allowedTarget(op.path);
162
+ ensure(!seen.has(op.path), 'Repeated journal path', 'ERECOVERY', 5);
163
+ seen.add(op.path);
164
+ bytes(op.before);
165
+ bytes(op.after);
166
+ for (const [image, mode] of [[op.before, op.beforeMode], [op.after, op.afterMode]])
167
+ ensure(image === null ? mode === null : Number.isInteger(mode) && Number(mode) >= 0 && Number(mode) <= 0o777, 'Invalid journal permission mode', 'ERECOVERY', 5);
168
+ }
169
+ ensure(value.operations.at(-1)?.path === MANIFEST, 'Journal must finish with the ownership manifest', 'ERECOVERY', 5);
170
+ ensure(Array.isArray(value.createdDirectories) && value.createdDirectories.every(d => {
171
+ portable(d);
172
+ return d === '.pinelabs' || d === '.github' || d === '.agents' || d === '.agents/skills' || /^\.agents\/skills\/[a-z0-9-]+(?:\/.+)?$/.test(d);
173
+ }), 'Unsafe recovery directory list', 'ERECOVERY', 5);
174
+ return value;
175
+ }
176
+ async function matches(root, rel, image, mode) {
177
+ if (!equal(await read(root, rel), image))
178
+ return false;
179
+ return image === null || process.platform === 'win32' || ((await fs.stat(await safe(root, rel))).mode & 0o777) === mode;
180
+ }
181
+ async function preflight(root, journal, undo) {
182
+ for (const op of journal.operations) {
183
+ const before = await matches(root, op.path, bytes(op.before), op.beforeMode), after = await matches(root, op.path, bytes(op.after), op.afterMode);
184
+ ensure(undo ? before || after : before, `File changed during transaction: ${op.path}. No forced overwrite; inspect/recover manually.`, 'ECONFLICT', 3);
185
+ }
186
+ }
187
+ async function cleanupDirectories(root, rels) {
188
+ for (const rel of [...new Set(rels)].sort((a, b) => b.length - a.length))
189
+ await fs.rmdir(await safe(root, rel)).catch(e => {
190
+ if (!['ENOTEMPTY', 'EEXIST', 'ENOENT'].includes(e.code ?? ''))
191
+ throw e;
192
+ });
193
+ }
194
+ async function rollback(root, journal) {
195
+ await preflight(root, journal, true);
196
+ for (const op of [...journal.operations].reverse()) {
197
+ const before = bytes(op.before);
198
+ if (!await matches(root, op.path, before, op.beforeMode)) {
199
+ ensure(await matches(root, op.path, bytes(op.after), op.afterMode), `Concurrent edit during rollback: ${op.path}`, 'ERECOVERY', 5);
200
+ await installImage(root, op, before, op.beforeMode);
201
+ }
202
+ }
203
+ await fs.unlink(await safe(root, JOURNAL));
204
+ await cleanupDirectories(root, journal.createdDirectories);
205
+ }
206
+ export async function commit(root, operations, hooks = {}, dryRun = false) {
207
+ if (operations.length === 0)
208
+ return;
209
+ ensure(operations.length <= MAX_OPERATIONS, `Batch exceeds ${MAX_OPERATIONS} journal operations, including manifest/guidance. Split the request.`, 'EBATCHLIMIT', 4);
210
+ const createdDirectories = await missingDirectories(root, operations);
211
+ const journal = { schemaVersion: 1, state: 'applying', id: randomUUID(), operations, createdDirectories };
212
+ const encoded = Buffer.from(JSON.stringify(journal));
213
+ // Creation and recovery use the same wire validator, before even acquiring a project lock.
214
+ parseJournal(encoded);
215
+ if (dryRun) {
216
+ await preflight(root, journal, false);
217
+ return;
218
+ }
219
+ const release = await lock(root, false);
220
+ try {
221
+ await hooks.afterLock?.();
222
+ ensure(!await pending(root), 'Interrupted transaction exists; run recover first', 'ERECOVERY', 5);
223
+ await preflight(root, journal, false);
224
+ await atomic(root, JOURNAL, encoded);
225
+ try {
226
+ for (const [i, op] of operations.entries()) {
227
+ ensure(await matches(root, op.path, bytes(op.before), op.beforeMode), `Concurrent edit: ${op.path}`, 'ECONFLICT', 3);
228
+ if (op.path === MANIFEST)
229
+ for (const done of operations.slice(0, i))
230
+ ensure(await matches(root, done.path, bytes(done.after), done.afterMode), `Concurrent edit before ownership commit: ${done.path}`, 'ECONFLICT', 3);
231
+ await installImage(root, op, bytes(op.after), op.afterMode);
232
+ await hooks.afterOperation?.(i);
233
+ }
234
+ await fs.unlink(await safe(root, JOURNAL));
235
+ }
236
+ catch (e) {
237
+ try {
238
+ await rollback(root, journal);
239
+ }
240
+ catch {
241
+ throw new CliError('ERECOVERY', 'Transaction incomplete; journal retained. Stop other writers, inspect changes and run recover. No unknown edits were overwritten.', 5);
242
+ }
243
+ throw new CliError('ETRANSACTION', `Operation failed; changes rolled back: ${e instanceof Error ? e.message : 'I/O error'}`, 5);
244
+ }
245
+ await hooks.afterJournalRemoval?.();
246
+ const parents = operations.filter(o => o.after === null && o.path.startsWith('.agents/skills/')).flatMap(o => {
247
+ const p = o.path.split('/').slice(0, -1);
248
+ return p.map((_, i) => p.slice(0, i + 1).join('/')).filter(x => x.startsWith('.agents/skills/'));
249
+ });
250
+ await cleanupDirectories(root, parents);
251
+ }
252
+ finally {
253
+ await release();
254
+ }
255
+ }
256
+ export async function recover(root, dryRun) {
257
+ const raw = await read(root, JOURNAL);
258
+ const journal = raw === null ? null : parseJournal(raw);
259
+ if (journal)
260
+ await preflight(root, journal, true);
261
+ const prior = await staleLock(root);
262
+ if (!journal && !prior)
263
+ return { status: 'noop', changes: [] };
264
+ const changes = journal ? journal.operations.map(o => o.path) : [LOCK];
265
+ if (dryRun)
266
+ return { status: 'dry-run', changes };
267
+ const release = await lock(root, true);
268
+ try {
269
+ ensure(equal(await read(root, JOURNAL), raw), 'Journal changed during recovery', 'ERECOVERY', 5);
270
+ if (journal)
271
+ await rollback(root, journal);
272
+ }
273
+ finally {
274
+ await release();
275
+ }
276
+ return { status: 'ok', changes };
277
+ }
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@pinelabs/skills-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.5.0",
4
+ "private": false,
5
+ "description": "Install Pine Labs agent skills into a project for Codex and GitHub Copilot",
6
+ "type": "module",
7
+ "bin": {
8
+ "pinelabs-skills": "dist/cli.js"
9
+ },
10
+ "engines": {
11
+ "node": "^24.0.0 || ^26.0.0"
12
+ },
13
+ "files": [
14
+ "dist/",
15
+ "resources/",
16
+ "schemas/",
17
+ "README.md",
18
+ "CHANGELOG.md"
19
+ ],
20
+ "scripts": {
21
+ "build": "tsc && node scripts/build-resources.mjs",
22
+ "test": "node --test test/*.test.mjs",
23
+ "check": "tsc --noEmit",
24
+ "pack:smoke": "node scripts/pack-smoke.mjs"
25
+ },
26
+ "license": "UNLICENSED",
27
+ "dependencies": {
28
+ "yaml": "2.9.1"
29
+ },
30
+ "devDependencies": {
31
+ "@types/node": "24.19.2",
32
+ "typescript": "7.0.2"
33
+ },
34
+ "publishConfig": {
35
+ "access": "public",
36
+ "registry": "https://registry.npmjs.org/"
37
+ },
38
+ "keywords": [
39
+ "agent-skills",
40
+ "codex",
41
+ "copilot",
42
+ "architecture",
43
+ "pine-labs"
44
+ ]
45
+ }