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