@astrosheep/square 0.3.11 → 0.3.12
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/codex-plugin/.codex-plugin/plugin.json +1 -1
- package/dist/activity.js +2 -7
- package/dist/artifact.js +335 -647
- package/dist/boundary-presentation.js +1 -1
- package/dist/cli/context.js +2 -2
- package/dist/cli/harness-command.js +1 -1
- package/dist/cli/maintenance-commands.js +12 -69
- package/dist/cli/observation-commands.js +11 -18
- package/dist/cli/program.js +3 -2
- package/dist/cli/registry.js +1 -2
- package/dist/cli/square-commands.js +17 -18
- package/dist/compact.js +4 -4
- package/dist/decisions.js +11 -5
- package/dist/delivery-health.js +2 -1
- package/dist/delivery.js +11 -47
- package/dist/help.js +8 -10
- package/dist/index.js +6 -4
- package/dist/list.js +3 -47
- package/dist/model.js +0 -6
- package/dist/notifications.js +16 -8
- package/dist/presentation.js +22 -37
- package/dist/runtime.js +6 -21
- package/dist/square-application.js +9 -78
- package/dist/square-core.js +56 -9
- package/dist/wake-attempts.js +8 -4
- package/guides/participant.md +7 -174
- package/package.json +1 -3
- package/skills/brainstorm/SKILL.md +6 -6
- package/skills/square/.claude-plugin/plugin.json +1 -1
- package/skills/square/SKILL.md +23 -14
- package/skills/square-feedback/SKILL.md +7 -7
- package/dist/doctor.js +0 -36
- package/template.md +0 -4
- package/templates/architect.md +0 -4
- package/templates/brainstorm.md +0 -4
package/dist/artifact.js
CHANGED
|
@@ -1,705 +1,393 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
1
2
|
import fs from 'node:fs';
|
|
2
|
-
import
|
|
3
|
-
import {
|
|
4
|
-
import
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
out.shift();
|
|
19
|
-
while (out.length > 0 && out[out.length - 1] === '')
|
|
20
|
-
out.pop();
|
|
21
|
-
return out
|
|
22
|
-
.map((line) => {
|
|
23
|
-
if (line === '>')
|
|
24
|
-
return '';
|
|
25
|
-
if (line.startsWith('> '))
|
|
26
|
-
return line.slice(2);
|
|
27
|
-
if (line.startsWith('>'))
|
|
28
|
-
return line.slice(1);
|
|
29
|
-
return line;
|
|
30
|
-
})
|
|
31
|
-
.join('\n')
|
|
32
|
-
.trim();
|
|
33
|
-
}
|
|
34
|
-
function actIndex(act) {
|
|
35
|
-
if (act.index === undefined || !Number.isInteger(act.index) || act.index < 0) {
|
|
36
|
-
throw new SquareError('invalid_args', `Invalid square act: missing stable index for ${act.kind}.`);
|
|
37
|
-
}
|
|
38
|
-
return act.index;
|
|
39
|
-
}
|
|
40
|
-
function renderActMarker(act) {
|
|
41
|
-
const marker = {
|
|
42
|
-
index: actIndex(act),
|
|
43
|
-
kind: act.kind,
|
|
44
|
-
actor: act.actor,
|
|
45
|
-
at: act.at,
|
|
46
|
-
...(act.kind === 'say' && act.reach !== undefined ? { reach: act.reach } : {}),
|
|
47
|
-
...(act.kind === 'say' && act.reply !== undefined ? { reply: act.reply } : {}),
|
|
48
|
-
};
|
|
49
|
-
return `${ACT_MARKER_PREFIX} ${JSON.stringify(marker)} -->`;
|
|
50
|
-
}
|
|
51
|
-
function actNeedsBody(act) {
|
|
52
|
-
return act.kind === 'say' || act.kind === 'done' || act.kind === 'hold';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { TextDecoder } from 'node:util';
|
|
5
|
+
import zlib from 'node:zlib';
|
|
6
|
+
import { isWakeRouteKind, nameKey, SquareError, } from './model.js';
|
|
7
|
+
import { parseActivityId } from './square-core.js';
|
|
8
|
+
const SQUARE_MAGIC = Buffer.from('SQUARE01', 'ascii');
|
|
9
|
+
const ARCHIVE_MAGIC = Buffer.from('SQARCH01', 'ascii');
|
|
10
|
+
const LENGTH_BYTES = 4;
|
|
11
|
+
const DIGEST_BYTES = 32;
|
|
12
|
+
const HEADER_BYTES = SQUARE_MAGIC.length + LENGTH_BYTES + DIGEST_BYTES;
|
|
13
|
+
const utf8 = new TextDecoder('utf-8', { fatal: true });
|
|
14
|
+
function invalidArtifact(detail) {
|
|
15
|
+
return new SquareError('invalid_args', `Invalid square artifact: ${detail}`);
|
|
16
|
+
}
|
|
17
|
+
function isObject(value) {
|
|
18
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
53
19
|
}
|
|
54
|
-
|
|
55
|
-
const
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
20
|
+
function hasExactKeys(value, required, optional = []) {
|
|
21
|
+
const allowed = new Set([...required, ...optional]);
|
|
22
|
+
return required.every((key) => Object.hasOwn(value, key))
|
|
23
|
+
&& Object.keys(value).every((key) => allowed.has(key));
|
|
24
|
+
}
|
|
25
|
+
function isFiniteNumber(value) {
|
|
26
|
+
return typeof value === 'number' && Number.isFinite(value);
|
|
27
|
+
}
|
|
28
|
+
function isNonNegativeInteger(value) {
|
|
29
|
+
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
|
|
30
|
+
}
|
|
31
|
+
function isNonblankString(value) {
|
|
32
|
+
return typeof value === 'string' && value.length > 0;
|
|
33
|
+
}
|
|
34
|
+
function isStringArray(value) {
|
|
35
|
+
return Array.isArray(value) && value.every((item) => typeof item === 'string');
|
|
36
|
+
}
|
|
37
|
+
function validateReadCursor(value) {
|
|
38
|
+
return isObject(value)
|
|
39
|
+
&& hasExactKeys(value, ['consumedThroughIndex', 'updatedAt'])
|
|
40
|
+
&& Number.isSafeInteger(value.consumedThroughIndex)
|
|
41
|
+
&& value.consumedThroughIndex >= -1
|
|
42
|
+
&& isFiniteNumber(value.updatedAt);
|
|
43
|
+
}
|
|
44
|
+
function validateDeliveryReceipt(value) {
|
|
45
|
+
return isObject(value)
|
|
46
|
+
&& hasExactKeys(value, ['status', 'at'])
|
|
47
|
+
&& value.status === 'delivered'
|
|
48
|
+
&& isFiniteNumber(value.at);
|
|
49
|
+
}
|
|
50
|
+
function validateWatchLease(value) {
|
|
51
|
+
if (!isObject(value)
|
|
52
|
+
|| !hasExactKeys(value, ['leaseId', 'heartbeatAt', 'expiresAt'], ['ownerId', 'filter'])
|
|
53
|
+
|| !isNonblankString(value.leaseId)
|
|
54
|
+
|| (value.ownerId !== undefined && !isNonblankString(value.ownerId))
|
|
55
|
+
|| !isFiniteNumber(value.heartbeatAt)
|
|
56
|
+
|| !isFiniteNumber(value.expiresAt)
|
|
57
|
+
|| value.expiresAt < value.heartbeatAt)
|
|
58
|
+
return false;
|
|
59
|
+
if (value.filter === undefined)
|
|
60
|
+
return true;
|
|
61
|
+
return isObject(value.filter)
|
|
62
|
+
&& hasExactKeys(value.filter, [], ['participants', 'mention'])
|
|
63
|
+
&& (value.filter.participants === undefined || isStringArray(value.filter.participants))
|
|
64
|
+
&& (value.filter.mention === undefined || typeof value.filter.mention === 'string');
|
|
65
|
+
}
|
|
66
|
+
function validateNotifyLease(value) {
|
|
67
|
+
if (!isObject(value)
|
|
68
|
+
|| !hasExactKeys(value, ['leaseId', 'expiresAt', 'phase'], ['attemptN', 'routeKind'])
|
|
69
|
+
|| !isNonblankString(value.leaseId)
|
|
70
|
+
|| !isFiniteNumber(value.expiresAt)
|
|
71
|
+
|| (value.phase !== 'claimed' && value.phase !== 'dispatching')
|
|
72
|
+
|| (value.attemptN !== undefined && (!Number.isSafeInteger(value.attemptN) || value.attemptN <= 0))
|
|
73
|
+
|| (value.routeKind !== undefined && !isWakeRouteKind(value.routeKind)))
|
|
74
|
+
return false;
|
|
75
|
+
return value.phase !== 'dispatching' || (value.attemptN !== undefined && value.routeKind !== undefined);
|
|
60
76
|
}
|
|
61
|
-
|
|
62
|
-
return
|
|
63
|
-
|
|
64
|
-
nextActIndex,
|
|
65
|
-
cursors: {},
|
|
66
|
-
deliveryReceipts: {},
|
|
67
|
-
leases: {},
|
|
68
|
-
notifyLeases: {},
|
|
69
|
-
};
|
|
77
|
+
function validateRecord(value, item) {
|
|
78
|
+
return isObject(value)
|
|
79
|
+
&& Object.entries(value).every(([key, candidate]) => key.length > 0 && item(candidate));
|
|
70
80
|
}
|
|
71
|
-
function
|
|
72
|
-
|
|
73
|
-
'---',
|
|
74
|
-
`hard_cap: ${formatHardCap(doc.hardCap)}`,
|
|
75
|
-
...(doc.throttlePerMinute === undefined ? [] : [`throttle_per_minute: ${doc.throttlePerMinute}`]),
|
|
76
|
-
`format_version: ${CURRENT_FORMAT_VERSION}`,
|
|
77
|
-
'---',
|
|
78
|
-
].join('\n');
|
|
79
|
-
}
|
|
80
|
-
export function renderSquare(opts, snippet) {
|
|
81
|
-
const templateFile = opts.template
|
|
82
|
-
? new URL(`../templates/${opts.template}.md`, import.meta.url)
|
|
83
|
-
: new URL('../template.md', import.meta.url);
|
|
84
|
-
const template = fs.readFileSync(templateFile, 'utf8');
|
|
85
|
-
const body = template.replace(/^---\n[\s\S]*?\n---\n?/, '').trimStart();
|
|
86
|
-
const genericGuide = fs.readFileSync(new URL('../guides/participant.md', import.meta.url), 'utf8').trim();
|
|
87
|
-
let templateGuide = '';
|
|
88
|
-
if (opts.template) {
|
|
89
|
-
try {
|
|
90
|
-
templateGuide = '\n\n' + fs.readFileSync(new URL(`../guides/${opts.template}.md`, import.meta.url), 'utf8').trim();
|
|
91
|
-
}
|
|
92
|
-
catch {
|
|
93
|
-
// No template-specific guide.
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
const training = [
|
|
97
|
-
'---',
|
|
98
|
-
'',
|
|
99
|
-
WARMUP_HEADING,
|
|
100
|
-
WARMUP_MARKER,
|
|
101
|
-
'',
|
|
102
|
-
genericGuide + templateGuide,
|
|
103
|
-
'',
|
|
104
|
-
].join('\n');
|
|
105
|
-
const normalizedSnippet = snippet.replace(/\r\n/g, '\n').trim();
|
|
106
|
-
return [
|
|
107
|
-
renderFrontmatter({
|
|
108
|
-
hardCap: opts.hardCap,
|
|
109
|
-
throttlePerMinute: opts.throttlePerMinute,
|
|
110
|
-
}),
|
|
111
|
-
'',
|
|
112
|
-
normalizedSnippet,
|
|
113
|
-
'',
|
|
114
|
-
training,
|
|
115
|
-
body,
|
|
116
|
-
].join('\n');
|
|
117
|
-
}
|
|
118
|
-
function sidecarPath(squarePath) {
|
|
119
|
-
return `${squarePath}.runtime.json`;
|
|
120
|
-
}
|
|
121
|
-
function invalidRuntimeSidecar(squarePath, detail) {
|
|
122
|
-
return new SquareError('invalid_args', `Invalid square runtime sidecar ${sidecarPath(squarePath)}: ${detail}`);
|
|
123
|
-
}
|
|
124
|
-
function validateRuntimeSidecar(squarePath, value) {
|
|
125
|
-
if (!isObject(value))
|
|
126
|
-
throw invalidRuntimeSidecar(squarePath, 'expected a JSON object.');
|
|
127
|
-
if (value.version !== 2)
|
|
128
|
-
throw invalidRuntimeSidecar(squarePath, 'unsupported or missing version.');
|
|
129
|
-
if (typeof value.nextActIndex !== 'number' || !Number.isInteger(value.nextActIndex) || value.nextActIndex < 0) {
|
|
130
|
-
throw invalidRuntimeSidecar(squarePath, 'nextActIndex must be a non-negative integer.');
|
|
131
|
-
}
|
|
132
|
-
if (!isObject(value.cursors) || !Object.values(value.cursors).every(isReadCursor)) {
|
|
133
|
-
throw invalidRuntimeSidecar(squarePath, 'cursors contains an invalid read cursor.');
|
|
134
|
-
}
|
|
135
|
-
if (!isObject(value.deliveryReceipts) || !Object.values(value.deliveryReceipts).every(isDeliveryReceiptMap)) {
|
|
136
|
-
throw invalidRuntimeSidecar(squarePath, 'deliveryReceipts contains an invalid receipt map.');
|
|
137
|
-
}
|
|
138
|
-
if (!isObject(value.leases) || !Object.values(value.leases).every(isWatchLease)) {
|
|
139
|
-
throw invalidRuntimeSidecar(squarePath, 'leases contains an invalid watch lease.');
|
|
140
|
-
}
|
|
141
|
-
if (value.notifyLeases !== undefined && (!isObject(value.notifyLeases) || !Object.values(value.notifyLeases).every(isNotifyLease))) {
|
|
142
|
-
throw invalidRuntimeSidecar(squarePath, 'notifyLeases contains an invalid notify lease.');
|
|
143
|
-
}
|
|
144
|
-
return {
|
|
145
|
-
version: 2,
|
|
146
|
-
nextActIndex: value.nextActIndex,
|
|
147
|
-
cursors: value.cursors,
|
|
148
|
-
deliveryReceipts: value.deliveryReceipts,
|
|
149
|
-
leases: value.leases,
|
|
150
|
-
notifyLeases: (value.notifyLeases ?? {}),
|
|
151
|
-
};
|
|
152
|
-
}
|
|
153
|
-
export function loadRuntimeSidecar(squarePath, fallbackRuntime) {
|
|
154
|
-
const sp = sidecarPath(squarePath);
|
|
81
|
+
function parseNotifyLeaseKey(key) {
|
|
82
|
+
let parsed;
|
|
155
83
|
try {
|
|
156
|
-
|
|
157
|
-
let parsed;
|
|
158
|
-
try {
|
|
159
|
-
parsed = JSON.parse(raw);
|
|
160
|
-
}
|
|
161
|
-
catch {
|
|
162
|
-
throw invalidRuntimeSidecar(squarePath, 'malformed JSON.');
|
|
163
|
-
}
|
|
164
|
-
return validateRuntimeSidecar(squarePath, parsed);
|
|
84
|
+
parsed = JSON.parse(key);
|
|
165
85
|
}
|
|
166
|
-
catch
|
|
167
|
-
|
|
168
|
-
return fallbackRuntime;
|
|
169
|
-
}
|
|
170
|
-
throw err;
|
|
86
|
+
catch {
|
|
87
|
+
return undefined;
|
|
171
88
|
}
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
};
|
|
178
|
-
}
|
|
179
|
-
export function saveRuntimeSidecar(squarePath, runtime) {
|
|
180
|
-
const target = sidecarPath(squarePath);
|
|
181
|
-
const normalized = validateRuntimeSidecar(squarePath, runtime);
|
|
182
|
-
const temporary = `${target}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
183
|
-
try {
|
|
184
|
-
fs.writeFileSync(temporary, JSON.stringify(normalized, null, 2));
|
|
185
|
-
fs.renameSync(temporary, target);
|
|
89
|
+
if (!Array.isArray(parsed) || parsed.length !== 2)
|
|
90
|
+
return undefined;
|
|
91
|
+
const [id, name] = parsed;
|
|
92
|
+
if (typeof id !== 'string' || typeof name !== 'string' || name.length === 0 || nameKey(name) !== name) {
|
|
93
|
+
return undefined;
|
|
186
94
|
}
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
95
|
+
const index = parseActivityId(id);
|
|
96
|
+
if (index === undefined)
|
|
97
|
+
return undefined;
|
|
98
|
+
if (JSON.stringify([id, name]) !== key)
|
|
99
|
+
return undefined;
|
|
100
|
+
return { index, name };
|
|
101
|
+
}
|
|
102
|
+
function validateRuntime(value) {
|
|
103
|
+
if (!isObject(value)
|
|
104
|
+
|| !hasExactKeys(value, ['nextActIndex', 'cursors', 'deliveryReceipts', 'leases', 'notifyLeases'])
|
|
105
|
+
|| !isNonNegativeInteger(value.nextActIndex)
|
|
106
|
+
|| !validateRecord(value.cursors, validateReadCursor)
|
|
107
|
+
|| !validateRecord(value.leases, validateWatchLease)
|
|
108
|
+
|| !validateRecord(value.notifyLeases, validateNotifyLease)
|
|
109
|
+
|| !isObject(value.deliveryReceipts))
|
|
110
|
+
return false;
|
|
111
|
+
return Object.entries(value.deliveryReceipts).every(([name, receipts]) => name.length > 0
|
|
112
|
+
&& isObject(receipts)
|
|
113
|
+
&& Object.entries(receipts).every(([id, receipt]) => parseActivityId(id) !== undefined && validateDeliveryReceipt(receipt)));
|
|
114
|
+
}
|
|
115
|
+
function validateAssignedRuntimeReferences(runtime) {
|
|
116
|
+
const bound = runtime.nextActIndex;
|
|
117
|
+
for (const cursor of Object.values(runtime.cursors)) {
|
|
118
|
+
if (cursor.consumedThroughIndex !== -1 && cursor.consumedThroughIndex >= bound)
|
|
119
|
+
return 'future';
|
|
120
|
+
}
|
|
121
|
+
for (const receipts of Object.values(runtime.deliveryReceipts)) {
|
|
122
|
+
for (const id of Object.keys(receipts)) {
|
|
123
|
+
const index = parseActivityId(id);
|
|
124
|
+
if (index === undefined)
|
|
125
|
+
return 'malformed';
|
|
126
|
+
if (index >= bound)
|
|
127
|
+
return 'future';
|
|
190
128
|
}
|
|
191
|
-
catch { }
|
|
192
|
-
throw error;
|
|
193
129
|
}
|
|
130
|
+
for (const key of Object.keys(runtime.notifyLeases)) {
|
|
131
|
+
const parsed = parseNotifyLeaseKey(key);
|
|
132
|
+
if (parsed === undefined)
|
|
133
|
+
return 'malformed';
|
|
134
|
+
if (parsed.index >= bound)
|
|
135
|
+
return 'future';
|
|
136
|
+
}
|
|
137
|
+
return 'ok';
|
|
194
138
|
}
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
return [
|
|
198
|
-
renderFrontmatter({ hardCap: doc.hardCap, throttlePerMinute: doc.throttlePerMinute }),
|
|
199
|
-
'',
|
|
200
|
-
...doc.preamble,
|
|
201
|
-
...(doc.preamble.length > 0 ? [''] : []),
|
|
202
|
-
...warmup,
|
|
203
|
-
'',
|
|
204
|
-
ACTIVITIES_HEADING,
|
|
205
|
-
ACTIVITIES_MARKER,
|
|
206
|
-
...(doc.acts.length === 0 ? [] : ['', doc.acts.map((act, index) => renderArtifactAct(act, { first: index === 0 })).join('\n')]),
|
|
207
|
-
'',
|
|
208
|
-
].join('\n');
|
|
209
|
-
}
|
|
210
|
-
function renderWarmupSection(warmup) {
|
|
211
|
-
if (warmup[0]?.trim() === WARMUP_HEADING)
|
|
212
|
-
return [warmup[0], WARMUP_MARKER, ...warmup.slice(1)];
|
|
213
|
-
return [WARMUP_MARKER, ...warmup];
|
|
214
|
-
}
|
|
215
|
-
export function parsePreamble(text) {
|
|
216
|
-
const lines = text.split('\n');
|
|
217
|
-
const frontmatterEnd = lines.findIndex((line, index) => index > 0 && line === '---');
|
|
218
|
-
if (lines[0] !== '---' || frontmatterEnd < 0)
|
|
219
|
-
throw new SquareError('invalid_args', 'Invalid square: missing frontmatter.');
|
|
220
|
-
const marker = lines.findIndex((line) => line.trim() === WARMUP_MARKER);
|
|
221
|
-
if (marker < 0)
|
|
222
|
-
throw new SquareError('invalid_args', 'Invalid square: missing embedded warmup.');
|
|
223
|
-
const warmupStart = marker > 0 && lines[marker - 1].trim() === WARMUP_HEADING ? marker - 1 : marker;
|
|
224
|
-
const out = lines.slice(frontmatterEnd + 1, warmupStart);
|
|
225
|
-
trimBlankEdges(out);
|
|
226
|
-
return out;
|
|
227
|
-
}
|
|
228
|
-
function trimBlankEdges(lines) {
|
|
229
|
-
while (lines.length > 0 && lines[0] === '')
|
|
230
|
-
lines.shift();
|
|
231
|
-
while (lines.length > 0 && lines[lines.length - 1] === '')
|
|
232
|
-
lines.pop();
|
|
233
|
-
}
|
|
234
|
-
function parseFrontmatter(text) {
|
|
235
|
-
const match = text.match(/^---\n([\s\S]*?)\n---(?:\n|$)/);
|
|
236
|
-
if (!match)
|
|
237
|
-
throw new SquareError('invalid_args', 'Invalid square: missing frontmatter.');
|
|
238
|
-
return match[1];
|
|
239
|
-
}
|
|
240
|
-
export function isObject(value) {
|
|
241
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
139
|
+
function validateActor(value, required) {
|
|
140
|
+
return required ? isNonblankString(value) : value === undefined || isNonblankString(value);
|
|
242
141
|
}
|
|
243
|
-
|
|
244
|
-
if (!isObject(value)
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
value.consumedThroughIndex >= -1 &&
|
|
249
|
-
typeof value.updatedAt === 'number' &&
|
|
250
|
-
Number.isFinite(value.updatedAt));
|
|
251
|
-
}
|
|
252
|
-
export function isDeliveryReceipt(value) {
|
|
253
|
-
if (!isObject(value))
|
|
254
|
-
return false;
|
|
255
|
-
if (value.status !== 'delivered')
|
|
256
|
-
return false;
|
|
257
|
-
if (typeof value.at !== 'number' || !Number.isFinite(value.at))
|
|
258
|
-
return false;
|
|
259
|
-
if (value.reason !== undefined && value.reason !== 'reconciled')
|
|
260
|
-
return false;
|
|
261
|
-
if (value.actor !== undefined && (typeof value.actor !== 'string' || value.actor === ''))
|
|
142
|
+
function validateStoredAct(value) {
|
|
143
|
+
if (!isObject(value)
|
|
144
|
+
|| typeof value.kind !== 'string'
|
|
145
|
+
|| !isNonNegativeInteger(value.index)
|
|
146
|
+
|| !isFiniteNumber(value.at))
|
|
262
147
|
return false;
|
|
263
|
-
|
|
148
|
+
switch (value.kind) {
|
|
149
|
+
case 'join':
|
|
150
|
+
return hasExactKeys(value, ['kind', 'actor', 'at', 'index']) && validateActor(value.actor, true);
|
|
151
|
+
case 'done':
|
|
152
|
+
return hasExactKeys(value, ['kind', 'actor', 'at', 'index'], ['body'])
|
|
153
|
+
&& validateActor(value.actor, true)
|
|
154
|
+
&& (value.body === undefined || typeof value.body === 'string');
|
|
155
|
+
case 'say':
|
|
156
|
+
return hasExactKeys(value, ['kind', 'actor', 'at', 'body', 'index'], ['reach', 'reply'])
|
|
157
|
+
&& validateActor(value.actor, true)
|
|
158
|
+
&& typeof value.body === 'string'
|
|
159
|
+
&& (value.reach === undefined || value.reach === 'bell')
|
|
160
|
+
&& (value.reply === undefined || isNonNegativeInteger(value.reply));
|
|
161
|
+
case 'hold':
|
|
162
|
+
return hasExactKeys(value, ['kind', 'at', 'index'], ['actor', 'body'])
|
|
163
|
+
&& validateActor(value.actor, false)
|
|
164
|
+
&& (value.body === undefined || typeof value.body === 'string');
|
|
165
|
+
case 'resume':
|
|
166
|
+
return hasExactKeys(value, ['kind', 'at', 'index'], ['actor']) && validateActor(value.actor, false);
|
|
167
|
+
case 'read':
|
|
168
|
+
return hasExactKeys(value, ['kind', 'actor', 'at', 'through', 'index'])
|
|
169
|
+
&& validateActor(value.actor, true)
|
|
170
|
+
&& isNonNegativeInteger(value.through);
|
|
171
|
+
default:
|
|
172
|
+
return false;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
function validateActs(value) {
|
|
176
|
+
if (!Array.isArray(value) || !value.every(validateStoredAct))
|
|
264
177
|
return false;
|
|
178
|
+
let previous = -1;
|
|
179
|
+
for (const act of value) {
|
|
180
|
+
if (act.index <= previous)
|
|
181
|
+
return false;
|
|
182
|
+
if (act.kind === 'say' && act.reply !== undefined && act.reply >= act.index)
|
|
183
|
+
return false;
|
|
184
|
+
previous = act.index;
|
|
185
|
+
}
|
|
265
186
|
return true;
|
|
266
187
|
}
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
if (
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
return mention === undefined || typeof mention === 'string';
|
|
292
|
-
}
|
|
293
|
-
export function isNotifyLease(value) {
|
|
294
|
-
if (!isObject(value))
|
|
295
|
-
return false;
|
|
296
|
-
if (typeof value.leaseId !== 'string' || value.leaseId === '')
|
|
297
|
-
return false;
|
|
298
|
-
if (typeof value.expiresAt !== 'number' || !Number.isFinite(value.expiresAt))
|
|
299
|
-
return false;
|
|
300
|
-
if (value.phase !== 'claimed' && value.phase !== 'dispatching')
|
|
301
|
-
return false;
|
|
302
|
-
if (value.attemptN !== undefined && (typeof value.attemptN !== 'number' || !Number.isInteger(value.attemptN) || value.attemptN <= 0))
|
|
303
|
-
return false;
|
|
304
|
-
if (value.routeKind !== undefined && !isWakeRouteKind(value.routeKind))
|
|
305
|
-
return false;
|
|
306
|
-
return value.phase !== 'dispatching' || (value.attemptN !== undefined && value.routeKind !== undefined);
|
|
188
|
+
function validateSquareDoc(value) {
|
|
189
|
+
if (!isObject(value)
|
|
190
|
+
|| !hasExactKeys(value, ['hardCap', 'preamble', 'warmup', 'acts', 'runtime'], ['throttlePerMinute'])
|
|
191
|
+
|| !(value.hardCap === null || (Number.isSafeInteger(value.hardCap) && value.hardCap > 0))
|
|
192
|
+
|| (value.throttlePerMinute !== undefined
|
|
193
|
+
&& (!Number.isSafeInteger(value.throttlePerMinute) || value.throttlePerMinute <= 0))
|
|
194
|
+
|| !isStringArray(value.preamble)
|
|
195
|
+
|| !isStringArray(value.warmup)
|
|
196
|
+
|| !validateActs(value.acts)
|
|
197
|
+
|| !validateRuntime(value.runtime)) {
|
|
198
|
+
throw invalidArtifact('snapshot schema is malformed.');
|
|
199
|
+
}
|
|
200
|
+
const acts = value.acts;
|
|
201
|
+
const runtime = value.runtime;
|
|
202
|
+
const historyBoundary = acts.at(-1)?.index ?? -1;
|
|
203
|
+
if (runtime.nextActIndex <= historyBoundary) {
|
|
204
|
+
throw invalidArtifact('nextActIndex is behind the activity history.');
|
|
205
|
+
}
|
|
206
|
+
const references = validateAssignedRuntimeReferences(runtime);
|
|
207
|
+
if (references === 'malformed')
|
|
208
|
+
throw invalidArtifact('snapshot schema is malformed.');
|
|
209
|
+
if (references === 'future')
|
|
210
|
+
throw invalidArtifact('runtime references an unassigned activity index.');
|
|
211
|
+
return value;
|
|
307
212
|
}
|
|
308
|
-
function
|
|
309
|
-
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
const
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
const
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
const
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
const match = frontmatter.match(/^format_version:\s*(\d+)\s*$/m);
|
|
336
|
-
if (!match) {
|
|
337
|
-
throw invalidVersionGuidance('Invalid square: missing format_version in frontmatter.');
|
|
213
|
+
function encodeEnvelope(magic, value) {
|
|
214
|
+
const json = Buffer.from(JSON.stringify(value), 'utf8');
|
|
215
|
+
const payload = zlib.gzipSync(json, { level: 9 });
|
|
216
|
+
if (payload.length > 0xffff_ffff)
|
|
217
|
+
throw invalidArtifact('compressed payload is too large.');
|
|
218
|
+
const header = Buffer.alloc(HEADER_BYTES);
|
|
219
|
+
magic.copy(header, 0);
|
|
220
|
+
header.writeUInt32BE(payload.length, magic.length);
|
|
221
|
+
crypto.createHash('sha256').update(payload).digest().copy(header, magic.length + LENGTH_BYTES);
|
|
222
|
+
return Buffer.concat([header, payload]);
|
|
223
|
+
}
|
|
224
|
+
function decodeEnvelope(bytes, magic) {
|
|
225
|
+
if (bytes.length < HEADER_BYTES)
|
|
226
|
+
throw invalidArtifact('truncated header.');
|
|
227
|
+
if (!bytes.subarray(0, magic.length).equals(magic))
|
|
228
|
+
throw invalidArtifact('bad magic or unsupported format version.');
|
|
229
|
+
const length = bytes.readUInt32BE(magic.length);
|
|
230
|
+
if (bytes.length !== HEADER_BYTES + length)
|
|
231
|
+
throw invalidArtifact('payload length does not match the file.');
|
|
232
|
+
const expected = bytes.subarray(magic.length + LENGTH_BYTES, HEADER_BYTES);
|
|
233
|
+
const payload = bytes.subarray(HEADER_BYTES);
|
|
234
|
+
const actual = crypto.createHash('sha256').update(payload).digest();
|
|
235
|
+
if (!crypto.timingSafeEqual(expected, actual))
|
|
236
|
+
throw invalidArtifact('payload digest mismatch.');
|
|
237
|
+
let inflated;
|
|
238
|
+
try {
|
|
239
|
+
inflated = zlib.gunzipSync(payload);
|
|
338
240
|
}
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
throw invalidVersionGuidance(`Invalid square: unsupported format_version ${version} (expected ${CURRENT_FORMAT_VERSION}).`);
|
|
241
|
+
catch {
|
|
242
|
+
throw invalidArtifact('payload is not valid gzip data.');
|
|
342
243
|
}
|
|
343
|
-
return version;
|
|
344
|
-
}
|
|
345
|
-
export function parseSquare(text) {
|
|
346
|
-
parseFormatVersion(text);
|
|
347
|
-
const runtime = emptyRuntimeState(0);
|
|
348
|
-
const parsedActs = parseActs(text);
|
|
349
|
-
runtime.nextActIndex = parsedActs.nextActIndex;
|
|
350
|
-
return {
|
|
351
|
-
hardCap: parseCap(text),
|
|
352
|
-
throttlePerMinute: parseThrottle(text),
|
|
353
|
-
preamble: parsePreamble(text),
|
|
354
|
-
warmup: parseWarmup(text),
|
|
355
|
-
acts: parsedActs.acts,
|
|
356
|
-
runtime,
|
|
357
|
-
};
|
|
358
|
-
}
|
|
359
|
-
export function loadSquare(squarePath) {
|
|
360
244
|
let text;
|
|
361
245
|
try {
|
|
362
|
-
text =
|
|
246
|
+
text = utf8.decode(inflated);
|
|
363
247
|
}
|
|
364
|
-
catch
|
|
365
|
-
|
|
366
|
-
throw new SquareError('not_found', `square file not found: ${squarePath}`);
|
|
367
|
-
}
|
|
368
|
-
throw err;
|
|
248
|
+
catch {
|
|
249
|
+
throw invalidArtifact('payload is not valid UTF-8.');
|
|
369
250
|
}
|
|
370
|
-
const doc = parseSquare(text);
|
|
371
|
-
const markdownRuntime = doc.runtime;
|
|
372
|
-
const sidecar = loadRuntimeSidecar(squarePath, markdownRuntime);
|
|
373
|
-
// Markdown owns the activity history; runtime state owns delivery metadata.
|
|
374
|
-
// Preserve whichever history boundary is furthest ahead so a missing or
|
|
375
|
-
// stale sidecar can never cause an index to be reused.
|
|
376
|
-
doc.runtime = mergeRuntimeState(markdownRuntime, sidecar);
|
|
377
|
-
return doc;
|
|
378
|
-
}
|
|
379
|
-
function isSquareMarker(line) {
|
|
380
|
-
return /^<!-- square:(warmup|activities) -->$/.test(line.trim());
|
|
381
|
-
}
|
|
382
|
-
function findActivitiesMarker(lines, after = -1) {
|
|
383
|
-
return lines.findIndex((line, index) => index > after && line.trim() === ACTIVITIES_MARKER);
|
|
384
|
-
}
|
|
385
|
-
export function parseWarmup(text) {
|
|
386
|
-
const lines = text.split('\n');
|
|
387
|
-
const marker = lines.findIndex((line) => line.trim() === WARMUP_MARKER);
|
|
388
|
-
if (marker < 0)
|
|
389
|
-
throw new SquareError('invalid_args', 'Invalid square: missing embedded warmup.');
|
|
390
|
-
const start = marker > 0 && lines[marker - 1].trim() === WARMUP_HEADING ? marker - 1 : marker;
|
|
391
|
-
const endMarker = findActivitiesMarker(lines, start);
|
|
392
|
-
if (endMarker < 0)
|
|
393
|
-
throw new SquareError('invalid_args', 'Invalid square: missing ACTIVITIES section.');
|
|
394
|
-
const end = lines[endMarker].trim() === ACTIVITIES_MARKER && endMarker > 0 && lines[endMarker - 1].trim() === ACTIVITIES_HEADING
|
|
395
|
-
? endMarker - 1
|
|
396
|
-
: endMarker;
|
|
397
|
-
const out = lines.slice(start, end).filter((line) => !isSquareMarker(line));
|
|
398
|
-
trimSection(out);
|
|
399
|
-
return out;
|
|
400
|
-
}
|
|
401
|
-
function parseReach(value) {
|
|
402
|
-
if (value === undefined)
|
|
403
|
-
return undefined;
|
|
404
|
-
if (value === 'bell')
|
|
405
|
-
return 'bell';
|
|
406
|
-
if (isObject(value) && typeof value.beside === 'string')
|
|
407
|
-
return { beside: value.beside };
|
|
408
|
-
throw new SquareError('invalid_args', 'Invalid square: malformed act reach metadata.');
|
|
409
|
-
}
|
|
410
|
-
export function parseActMarker(line) {
|
|
411
|
-
if (line === undefined || !line.startsWith(ACT_MARKER_PREFIX))
|
|
412
|
-
return null;
|
|
413
|
-
const match = line.match(/^<!-- square:act\s+(\{.*\})\s*-->$/);
|
|
414
|
-
if (!match)
|
|
415
|
-
return null;
|
|
416
|
-
let parsed;
|
|
417
251
|
try {
|
|
418
|
-
|
|
252
|
+
return JSON.parse(text);
|
|
419
253
|
}
|
|
420
254
|
catch {
|
|
421
|
-
throw
|
|
422
|
-
}
|
|
423
|
-
if (!isObject(parsed))
|
|
424
|
-
throw new SquareError('invalid_args', 'Invalid square: act marker is missing index metadata.');
|
|
425
|
-
const index = parsed.index;
|
|
426
|
-
if (typeof index !== 'number' || !Number.isInteger(index) || index < 0) {
|
|
427
|
-
throw new SquareError('invalid_args', 'Invalid square: act marker is missing index metadata.');
|
|
255
|
+
throw invalidArtifact('payload is not valid JSON.');
|
|
428
256
|
}
|
|
257
|
+
}
|
|
258
|
+
export function emptyRuntimeState(nextActIndex = 0) {
|
|
429
259
|
return {
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
...(parsed.reply !== undefined ? { reply: parseReply(parsed.reply) } : {}),
|
|
260
|
+
nextActIndex,
|
|
261
|
+
cursors: {},
|
|
262
|
+
deliveryReceipts: {},
|
|
263
|
+
leases: {},
|
|
264
|
+
notifyLeases: {},
|
|
436
265
|
};
|
|
437
266
|
}
|
|
438
|
-
function
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
}
|
|
442
|
-
return value;
|
|
267
|
+
function normalizedLines(value) {
|
|
268
|
+
const normalized = value.replace(/\r\n/g, '\n').trim();
|
|
269
|
+
return normalized === '' ? [] : normalized.split('\n');
|
|
443
270
|
}
|
|
444
|
-
function
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
}
|
|
448
|
-
if (marker.kind !== kind) {
|
|
449
|
-
throw new SquareError('invalid_args', `Invalid square: act marker kind ${marker.kind} does not match ${kind}.`);
|
|
450
|
-
}
|
|
451
|
-
if (!sameName(marker.actor, actor)) {
|
|
452
|
-
throw new SquareError('invalid_args', `Invalid square: act marker actor ${marker.actor} does not match ${actor}.`);
|
|
453
|
-
}
|
|
454
|
-
if (marker.at === undefined) {
|
|
455
|
-
throw new SquareError('invalid_args', `Invalid square: act marker is missing timestamp for ${kind} ${actor}.`);
|
|
456
|
-
}
|
|
457
|
-
if (marker.at !== head.at) {
|
|
458
|
-
throw new SquareError('invalid_args', `Invalid square: act marker timestamp does not match ${kind} ${actor}.`);
|
|
271
|
+
function readGuide(name) {
|
|
272
|
+
try {
|
|
273
|
+
return fs.readFileSync(new URL(`../guides/${name}.md`, import.meta.url), 'utf8').trim();
|
|
459
274
|
}
|
|
460
|
-
|
|
461
|
-
|
|
275
|
+
catch (error) {
|
|
276
|
+
if (error.code === 'ENOENT') {
|
|
277
|
+
throw new SquareError('invalid_args', `Unknown square guide: ${name}`);
|
|
278
|
+
}
|
|
279
|
+
throw error;
|
|
462
280
|
}
|
|
281
|
+
}
|
|
282
|
+
export function createSquareDoc(options, snippet) {
|
|
283
|
+
const guides = [readGuide('participant')];
|
|
284
|
+
if (options.template !== undefined)
|
|
285
|
+
guides.push(readGuide(options.template));
|
|
463
286
|
return {
|
|
464
|
-
|
|
465
|
-
...(
|
|
466
|
-
|
|
287
|
+
hardCap: options.hardCap,
|
|
288
|
+
...(options.throttlePerMinute === undefined ? {} : { throttlePerMinute: options.throttlePerMinute }),
|
|
289
|
+
preamble: normalizedLines(snippet),
|
|
290
|
+
warmup: normalizedLines(guides.join('\n\n')),
|
|
291
|
+
acts: [],
|
|
292
|
+
runtime: emptyRuntimeState(),
|
|
467
293
|
};
|
|
468
294
|
}
|
|
469
|
-
export function
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
}
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
const match = line.match(/^_(say|join|done|hold|resume) · ([^_]+)_\s*$/);
|
|
485
|
-
if (!match)
|
|
486
|
-
return null;
|
|
487
|
-
const at = parseTimestamp(match[2]);
|
|
488
|
-
if (!Number.isFinite(at) || !V2_KINDS.has(match[1]))
|
|
489
|
-
return null;
|
|
490
|
-
return { kind: match[1], actor, at };
|
|
491
|
-
}
|
|
492
|
-
function isActSeparator(lines, index) {
|
|
493
|
-
return lines[index]?.trim().startsWith(ACT_MARKER_PREFIX) === true;
|
|
494
|
-
}
|
|
495
|
-
function parseActBlock(blockLines) {
|
|
496
|
-
let i = 0;
|
|
497
|
-
const marker = parseActMarker(blockLines[i]?.trim());
|
|
498
|
-
if (!marker)
|
|
499
|
-
throw new SquareError('invalid_args', `Invalid square: expected act marker, got: ${blockLines[i] ?? ''}`);
|
|
500
|
-
i++;
|
|
501
|
-
const actor = parseParticipantHeading(blockLines[i] ?? '');
|
|
502
|
-
if (!actor)
|
|
503
|
-
throw new SquareError('invalid_args', `Invalid square: expected participant heading, got: ${blockLines[i] ?? ''}`);
|
|
504
|
-
i++;
|
|
505
|
-
if (blockLines[i] === '')
|
|
506
|
-
i++;
|
|
507
|
-
const head = parseActLine(blockLines[i] ?? '', actor);
|
|
508
|
-
if (!head)
|
|
509
|
-
throw new SquareError('invalid_args', `Invalid square: expected act line, got: ${blockLines[i] ?? ''}`);
|
|
510
|
-
i++;
|
|
511
|
-
const meta = normalizeActMeta(marker, head.kind, actor, head);
|
|
512
|
-
let body = '';
|
|
513
|
-
if (head.kind === 'say' || head.kind === 'done' || head.kind === 'hold') {
|
|
514
|
-
if (blockLines[i] === '')
|
|
515
|
-
i++;
|
|
516
|
-
body = unquoteBody(blockLines.slice(i));
|
|
295
|
+
export function encodeSquare(doc) {
|
|
296
|
+
return encodeEnvelope(SQUARE_MAGIC, validateSquareDoc(doc));
|
|
297
|
+
}
|
|
298
|
+
export function decodeSquare(bytes) {
|
|
299
|
+
return validateSquareDoc(decodeEnvelope(bytes, SQUARE_MAGIC));
|
|
300
|
+
}
|
|
301
|
+
export function encodeArchive(acts) {
|
|
302
|
+
if (!validateActs(acts))
|
|
303
|
+
throw invalidArtifact('archive activity schema is malformed.');
|
|
304
|
+
return encodeEnvelope(ARCHIVE_MAGIC, { acts });
|
|
305
|
+
}
|
|
306
|
+
export function decodeArchive(bytes) {
|
|
307
|
+
const value = decodeEnvelope(bytes, ARCHIVE_MAGIC);
|
|
308
|
+
if (!isObject(value) || !hasExactKeys(value, ['acts']) || !validateActs(value.acts)) {
|
|
309
|
+
throw invalidArtifact('archive schema is malformed.');
|
|
517
310
|
}
|
|
518
|
-
return
|
|
519
|
-
...head,
|
|
520
|
-
body,
|
|
521
|
-
index: meta.index,
|
|
522
|
-
...(meta.reach !== undefined ? { reach: meta.reach } : {}),
|
|
523
|
-
...(meta.reply !== undefined ? { reply: meta.reply } : {}),
|
|
524
|
-
};
|
|
311
|
+
return value.acts;
|
|
525
312
|
}
|
|
526
|
-
function
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
const indexes = new Set();
|
|
530
|
-
let maxIndex = -1;
|
|
531
|
-
let detectedFirst = -1;
|
|
532
|
-
for (let i = 0; i < lines.length;) {
|
|
533
|
-
if (lines[i] === '') {
|
|
534
|
-
i++;
|
|
535
|
-
continue;
|
|
536
|
-
}
|
|
537
|
-
let end = i + 1;
|
|
538
|
-
while (end < lines.length && !isActSeparator(lines, end))
|
|
539
|
-
end++;
|
|
540
|
-
const act = parseActBlock(lines.slice(i, end));
|
|
541
|
-
if (detectedFirst === -1)
|
|
542
|
-
detectedFirst = act.index;
|
|
543
|
-
if (indexes.has(act.index))
|
|
544
|
-
throw new SquareError('invalid_args', `Invalid square: duplicate act index ${act.index}.`);
|
|
545
|
-
indexes.add(act.index);
|
|
546
|
-
maxIndex = Math.max(maxIndex, act.index);
|
|
547
|
-
acts.push(act);
|
|
548
|
-
i = end;
|
|
313
|
+
function readArtifact(squarePath) {
|
|
314
|
+
try {
|
|
315
|
+
return fs.readFileSync(squarePath);
|
|
549
316
|
}
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
throw new SquareError('invalid_args', 'Invalid square: act indexes must be contiguous from the first retained index.');
|
|
317
|
+
catch (error) {
|
|
318
|
+
if (error.code === 'ENOENT') {
|
|
319
|
+
throw new SquareError('not_found', `square file not found: ${squarePath}`);
|
|
554
320
|
}
|
|
321
|
+
throw error;
|
|
555
322
|
}
|
|
556
|
-
return { acts, nextActIndex: indexes.size > 0 ? maxIndex + 1 : 0 };
|
|
557
|
-
}
|
|
558
|
-
function isDivider(line) {
|
|
559
|
-
return line.trim() === '---';
|
|
560
|
-
}
|
|
561
|
-
function trimSection(lines) {
|
|
562
|
-
while (lines.length > 0 && (lines[0] === '' || isDivider(lines[0])))
|
|
563
|
-
lines.shift();
|
|
564
|
-
while (lines.length > 0 && (lines[lines.length - 1] === '' || isDivider(lines[lines.length - 1])))
|
|
565
|
-
lines.pop();
|
|
566
323
|
}
|
|
567
|
-
function
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
hardCap: null,
|
|
572
|
-
preamble: [],
|
|
573
|
-
warmup: [],
|
|
574
|
-
acts: [],
|
|
575
|
-
quarantined: [],
|
|
576
|
-
};
|
|
324
|
+
function requireSquareExtension(squarePath) {
|
|
325
|
+
if (!squarePath.endsWith('.square')) {
|
|
326
|
+
throw new SquareError('invalid_args', `Square artifacts must use the .square extension: ${squarePath}`);
|
|
327
|
+
}
|
|
577
328
|
}
|
|
578
|
-
function
|
|
329
|
+
function atomicWrite(target, bytes) {
|
|
330
|
+
const temporary = path.join(path.dirname(target), `.${path.basename(target)}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);
|
|
331
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
579
332
|
try {
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
return { ok: false, reason: 'act marker is missing kind/actor metadata.' };
|
|
583
|
-
const actor = parseParticipantHeading(blockLines[1] ?? '');
|
|
584
|
-
if (!actor)
|
|
585
|
-
return { ok: false, reason: `act block missing participant heading, got: ${blockLines[1] ?? ''}` };
|
|
586
|
-
const headLine = blockLines[2] === '' ? blockLines[3] : blockLines[2];
|
|
587
|
-
if (!parseActLine(headLine ?? '', actor))
|
|
588
|
-
return { ok: false, reason: `act block missing or malformed timestamp line, got: ${headLine ?? ''}` };
|
|
589
|
-
return { ok: true, act: parseActBlock(blockLines) };
|
|
333
|
+
fs.writeFileSync(temporary, bytes);
|
|
334
|
+
fs.renameSync(temporary, target);
|
|
590
335
|
}
|
|
591
|
-
catch {
|
|
592
|
-
|
|
336
|
+
catch (error) {
|
|
337
|
+
try {
|
|
338
|
+
fs.unlinkSync(temporary);
|
|
339
|
+
}
|
|
340
|
+
catch { }
|
|
341
|
+
throw error;
|
|
593
342
|
}
|
|
594
343
|
}
|
|
595
|
-
function
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
const
|
|
616
|
-
if (!
|
|
617
|
-
|
|
618
|
-
let j = i + 1;
|
|
619
|
-
while (j < lines.length && !isActBlockStart(lines[j]))
|
|
620
|
-
j++;
|
|
621
|
-
quarantined.push({ raw: lines.slice(i, j).join('\n'), reason: 'expected current-format act marker' });
|
|
622
|
-
i = j;
|
|
623
|
-
continue;
|
|
624
|
-
}
|
|
625
|
-
const blockStart = i;
|
|
626
|
-
let j = i + 1;
|
|
627
|
-
while (j < lines.length && !isActBlockStart(lines[j]))
|
|
628
|
-
j++;
|
|
629
|
-
const blockLines = lines.slice(blockStart, j);
|
|
630
|
-
const outcome = parseBlock(blockLines);
|
|
631
|
-
if (outcome.ok) {
|
|
632
|
-
const index = outcome.act.index;
|
|
633
|
-
if (seenIndexes.has(index))
|
|
634
|
-
problems.push({ kind: 'duplicate_index', message: `duplicate act index ${index}.` });
|
|
635
|
-
seenIndexes.add(index);
|
|
636
|
-
acts.push({ act: outcome.act, raw: blockLines.join('\n') });
|
|
637
|
-
}
|
|
638
|
-
else {
|
|
639
|
-
problems.push({ kind: 'act_block', message: outcome.reason });
|
|
640
|
-
quarantined.push({ raw: blockLines.join('\n'), reason: outcome.reason });
|
|
344
|
+
export function writeSquareFile(squarePath, doc) {
|
|
345
|
+
requireSquareExtension(squarePath);
|
|
346
|
+
atomicWrite(squarePath, encodeSquare(doc));
|
|
347
|
+
}
|
|
348
|
+
export function loadSquare(squarePath) {
|
|
349
|
+
requireSquareExtension(squarePath);
|
|
350
|
+
return decodeSquare(readArtifact(squarePath));
|
|
351
|
+
}
|
|
352
|
+
export function writeArchiveFile(archivePath, acts) {
|
|
353
|
+
atomicWrite(archivePath, encodeArchive(acts));
|
|
354
|
+
}
|
|
355
|
+
export function loadArchive(archivePath) {
|
|
356
|
+
return decodeArchive(readArtifact(archivePath));
|
|
357
|
+
}
|
|
358
|
+
export function probeSquare(squarePath) {
|
|
359
|
+
if (!squarePath.endsWith('.square'))
|
|
360
|
+
return undefined;
|
|
361
|
+
let descriptor;
|
|
362
|
+
try {
|
|
363
|
+
descriptor = fs.openSync(squarePath, 'r');
|
|
364
|
+
const magic = Buffer.alloc(SQUARE_MAGIC.length);
|
|
365
|
+
if (fs.readSync(descriptor, magic, 0, magic.length, 0) !== magic.length || !magic.equals(SQUARE_MAGIC)) {
|
|
366
|
+
return undefined;
|
|
641
367
|
}
|
|
642
|
-
i = j;
|
|
643
368
|
}
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
const min = uniqueIndexes[0];
|
|
647
|
-
const max = uniqueIndexes[uniqueIndexes.length - 1];
|
|
648
|
-
if (max - min + 1 !== uniqueIndexes.length) {
|
|
649
|
-
problems.push({ kind: 'non_contiguous_indexes', message: 'act indexes are not contiguous.' });
|
|
650
|
-
}
|
|
369
|
+
catch {
|
|
370
|
+
return undefined;
|
|
651
371
|
}
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
const fmMatch = text.match(/^---\n([\s\S]*?)\n---(?:\n|$)/);
|
|
656
|
-
if (!fmMatch)
|
|
657
|
-
return unfixableResult('cannot locate frontmatter: missing opening/closing "---" delimiters.');
|
|
658
|
-
const frontmatter = fmMatch[1];
|
|
659
|
-
const lines = text.split('\n');
|
|
660
|
-
if (!lines.some((line) => line.trim() === WARMUP_MARKER) || !lines.some((line) => line.trim() === ACTIVITIES_MARKER)) {
|
|
661
|
-
return unfixableResult('cannot locate the warmup/activities section markers; the act stream boundaries are unknown.');
|
|
372
|
+
finally {
|
|
373
|
+
if (descriptor !== undefined)
|
|
374
|
+
fs.closeSync(descriptor);
|
|
662
375
|
}
|
|
663
|
-
const problems = [];
|
|
664
|
-
const fvMatch = frontmatter.match(/^format_version:\s*(\d+)\s*$/m);
|
|
665
|
-
const formatVersion = fvMatch ? parseInt(fvMatch[1], 10) : undefined;
|
|
666
|
-
if (formatVersion === undefined)
|
|
667
|
-
return unfixableResult('missing format_version in frontmatter. Create a new square with `square build`.');
|
|
668
|
-
if (formatVersion !== CURRENT_FORMAT_VERSION)
|
|
669
|
-
return unfixableResult(`format_version ${formatVersion} is no longer supported. Create a new square with \`square build\`.`);
|
|
670
|
-
let hardCap = null;
|
|
671
|
-
const hcMatch = frontmatter.match(/^hard_cap:\s*(-1|\d+)\s*$/m);
|
|
672
|
-
if (!hcMatch)
|
|
673
|
-
problems.push({ kind: 'hard_cap', message: 'missing or malformed hard_cap in frontmatter.' });
|
|
674
|
-
else
|
|
675
|
-
hardCap = hcMatch[1] === '-1' ? null : parseInt(hcMatch[1], 10);
|
|
676
|
-
let throttlePerMinute;
|
|
677
|
-
const tMatch = frontmatter.match(/^throttle_per_minute:\s*(\d+)\s*$/m);
|
|
678
|
-
if (tMatch)
|
|
679
|
-
throttlePerMinute = parseInt(tMatch[1], 10);
|
|
680
|
-
let preamble = [];
|
|
681
376
|
try {
|
|
682
|
-
|
|
377
|
+
return loadSquare(squarePath);
|
|
683
378
|
}
|
|
684
|
-
catch
|
|
685
|
-
|
|
379
|
+
catch {
|
|
380
|
+
return undefined;
|
|
686
381
|
}
|
|
687
|
-
|
|
382
|
+
}
|
|
383
|
+
export function diagnoseSquareFile(squarePath) {
|
|
688
384
|
try {
|
|
689
|
-
|
|
385
|
+
return { problems: [], doc: loadSquare(squarePath) };
|
|
690
386
|
}
|
|
691
|
-
catch (
|
|
692
|
-
|
|
387
|
+
catch (error) {
|
|
388
|
+
return {
|
|
389
|
+
unfixable: error instanceof Error ? error.message : String(error),
|
|
390
|
+
problems: [],
|
|
391
|
+
};
|
|
693
392
|
}
|
|
694
|
-
const { acts, quarantined } = diagnoseActs(text, problems);
|
|
695
|
-
return {
|
|
696
|
-
formatVersion,
|
|
697
|
-
problems,
|
|
698
|
-
hardCap,
|
|
699
|
-
throttlePerMinute,
|
|
700
|
-
preamble,
|
|
701
|
-
warmup,
|
|
702
|
-
acts,
|
|
703
|
-
quarantined,
|
|
704
|
-
};
|
|
705
393
|
}
|