-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworkpads.js
More file actions
3549 lines (3273 loc) · 136 KB
/
Copy pathworkpads.js
File metadata and controls
3549 lines (3273 loc) · 136 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
const fs = require("fs");
const path = require("path");
const http = require("http");
const net = require("net");
const { URL } = require("url");
const { spawnSync } = require("child_process");
const zlib = require("zlib");
const crypto = require("crypto");
const WPCodec = require("@workpads/codec");
const ROOT = __dirname;
const DATA_DIR = path.join(ROOT, ".workpads");
const RECORDS_FILE = path.join(DATA_DIR, "records.json");
const STORAGE_POLICIES_FILE = path.join(DATA_DIR, "storage-policies.json");
const BROWSER_STATE_FILE = path.join(DATA_DIR, "browser-state.json");
const DEFAULT_TEMPLATE_PATH = path.join(
ROOT,
"templates",
"runtime",
"svc-basic.v1.json"
);
const DEFAULT_BASE_URL = "https://workpads.me/p";
// ── ANSI colour ───────────────────────────────────────────────────────────────
const TTY = process.stdout.isTTY;
const C = TTY ? {
reset: "\x1b[0m",
bold: "\x1b[1m",
faint: "\x1b[2m",
signal: "\x1b[36m", // teal — IDs, URLs, codec info
warm: "\x1b[33m", // amber — action numbers
green: "\x1b[32m", // green — status / valid
gold: "\x1b[93m", // gold — warnings
red: "\x1b[31m", // red — errors
} : Object.fromEntries(
["reset","bold","faint","signal","warm","green","gold","red"].map(k => [k, ""])
);
function clr(k, t) { return C[k] + t + C.reset; }
function rule(w) { return "─".repeat(w || 66); }
function wrapIndent(text, indent, width) {
const words = String(text || "").split(" ");
const lines = [];
let line = "";
for (const w of words) {
if (line && (indent + line + " " + w).length > width) {
lines.push(indent + line);
line = w;
} else {
line = line ? line + " " + w : w;
}
}
if (line) lines.push(indent + line);
return lines.join("\n");
}
function toNumber(value, fallback = 0) {
const n = Number(value);
return Number.isNaN(n) ? fallback : n;
}
function parseArgs(argv) {
const args = { _: [] };
for (let i = 0; i < argv.length; i += 1) {
const part = argv[i];
if (part.startsWith("--")) {
const key = part.slice(2);
const next = argv[i + 1];
if (!next || next.startsWith("--")) {
args[key] = true;
} else {
if (args[key] === undefined) {
args[key] = next;
} else if (Array.isArray(args[key])) {
args[key].push(next);
} else {
args[key] = [args[key], next];
}
i += 1;
}
} else {
args._.push(part);
}
}
return args;
}
function ensureStore() {
fs.mkdirSync(DATA_DIR, { recursive: true });
if (!fs.existsSync(RECORDS_FILE)) {
fs.writeFileSync(RECORDS_FILE, JSON.stringify([], null, 2));
}
if (!fs.existsSync(STORAGE_POLICIES_FILE)) {
fs.writeFileSync(STORAGE_POLICIES_FILE, JSON.stringify({}, null, 2));
}
}
function loadBrowserState() {
ensureStore();
if (!fs.existsSync(BROWSER_STATE_FILE)) return null;
try {
return JSON.parse(fs.readFileSync(BROWSER_STATE_FILE, "utf8"));
} catch (_) {
return null;
}
}
function saveBrowserState(state) {
ensureStore();
fs.writeFileSync(BROWSER_STATE_FILE, JSON.stringify(state, null, 2));
}
function clearBrowserState() {
try {
if (fs.existsSync(BROWSER_STATE_FILE)) fs.unlinkSync(BROWSER_STATE_FILE);
} catch (_) {}
}
function loadTemplate(templatePath = DEFAULT_TEMPLATE_PATH) {
return JSON.parse(fs.readFileSync(templatePath, "utf8"));
}
function loadRecords() {
ensureStore();
return JSON.parse(fs.readFileSync(RECORDS_FILE, "utf8"));
}
function saveRecords(records) {
ensureStore();
fs.writeFileSync(RECORDS_FILE, JSON.stringify(records, null, 2));
}
function loadStoragePolicies() {
ensureStore();
return JSON.parse(fs.readFileSync(STORAGE_POLICIES_FILE, "utf8"));
}
function saveStoragePolicies(policies) {
ensureStore();
fs.writeFileSync(STORAGE_POLICIES_FILE, JSON.stringify(policies, null, 2));
}
function readKvFile(filePath) {
const lines = fs
.readFileSync(filePath, "utf8")
.split("\n")
.map((line) => line.trim())
.filter((line) => line && !line.startsWith("#"));
const out = {};
for (const line of lines) {
const idx = line.indexOf(":");
if (idx < 0) continue;
const key = line.slice(0, idx).trim();
const value = line.slice(idx + 1).trim();
if (!out[key]) out[key] = [];
out[key].push(value);
}
return out;
}
function parseKvTemplate(filePath) {
const parsed = readKvFile(filePath);
const templateId = parsed.template_id && parsed.template_id[0];
const version = toNumber(parsed.version && parsed.version[0], 1);
const title = parsed.title && parsed.title[0];
const variants = parsed.variants ? parsed.variants[0].split(",").map((v) => v.trim()).filter(Boolean) : [];
const pads = parsed.pads ? parsed.pads[0].split(",").map((v) => v.trim()).filter(Boolean) : [];
const fieldLines = parsed.field || [];
const fields = fieldLines.map((line) => {
const parts = line.split("|").map((x) => x.trim());
const field = {
id: parts[0],
label: parts[1],
type: parts[2],
required: parts[3] === "required",
max: null,
pad: null,
key: null
};
for (let i = 4; i < parts.length; i += 1) {
const p = parts[i];
if (p.startsWith("max=")) field.max = toNumber(p.slice(4), null);
if (p.startsWith("pad=")) field.pad = p.slice(4);
if (p.startsWith("key=")) field.key = p.slice(4);
}
return field;
});
return normalizeTemplate({
template_id: templateId,
version,
title,
variants,
pads,
fields
});
}
function parseYamlTemplate(filePath) {
const raw = fs.readFileSync(filePath, "utf8");
const lines = raw.split("\n");
const out = { variants: [], pads: [], fields: [] };
let section = "";
let currentField = null;
function pushField() {
if (!currentField) return;
if (currentField.required === undefined) currentField.required = false;
if (currentField.max !== undefined) currentField.max = toNumber(currentField.max, null);
out.fields.push(currentField);
currentField = null;
}
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) continue;
if (trimmed === "variants:") {
pushField();
section = "variants";
continue;
}
if (trimmed === "pads:") {
pushField();
section = "pads";
continue;
}
if (trimmed === "fields:") {
pushField();
section = "fields";
continue;
}
if (section === "variants" && trimmed.startsWith("- ")) {
out.variants.push(trimmed.slice(2).trim());
continue;
}
if (section === "pads" && trimmed.startsWith("- ")) {
out.pads.push(trimmed.slice(2).trim());
continue;
}
if (section === "fields") {
if (trimmed.startsWith("- ")) {
pushField();
currentField = {};
const maybePair = trimmed.slice(2).trim();
if (maybePair.includes(":")) {
const idx = maybePair.indexOf(":");
const k = maybePair.slice(0, idx).trim();
const v = maybePair.slice(idx + 1).trim();
currentField[k] = parseYamlScalar(v);
}
continue;
}
if (currentField && trimmed.includes(":")) {
const idx = trimmed.indexOf(":");
const k = trimmed.slice(0, idx).trim();
const v = trimmed.slice(idx + 1).trim();
currentField[k] = parseYamlScalar(v);
continue;
}
}
if (trimmed.includes(":")) {
const idx = trimmed.indexOf(":");
const key = trimmed.slice(0, idx).trim();
const value = trimmed.slice(idx + 1).trim();
out[key] = parseYamlScalar(value);
}
}
pushField();
return normalizeTemplate(out);
}
function parseYamlScalar(value) {
if (value === "true") return true;
if (value === "false") return false;
if (/^\d+$/.test(value)) return toNumber(value, 0);
return value.replace(/^"(.*)"$/, "$1").replace(/^'(.*)'$/, "$1");
}
function normalizeTemplate(input) {
const templateId = input.template_id || input.templateId;
const version = toNumber(input.version, 1);
const title = input.title;
const variants = Array.isArray(input.variants) ? input.variants : [];
const pads = Array.isArray(input.pads) ? input.pads : ["process", "actions", "details", "story"];
const fields = Array.isArray(input.fields) ? input.fields : [];
if (!templateId) throw new Error("Template missing template_id");
if (!title) throw new Error("Template missing title");
if (!Array.isArray(variants) || variants.length === 0) throw new Error("Template missing variants");
if (!Array.isArray(fields) || fields.length === 0) throw new Error("Template missing fields");
const compactKeys = {};
const normalizedFields = fields.map((f) => {
if (!f.id || !f.type || !f.label) {
throw new Error(`Invalid field entry: ${JSON.stringify(f)}`);
}
const out = {
id: f.id,
label: f.label,
type: f.type,
required: Boolean(f.required),
max: f.max === null || f.max === undefined ? null : toNumber(f.max, null),
pad: f.pad || null
};
if (f.key) compactKeys[f.id] = f.key;
return out;
});
return {
templateId,
version,
title,
variants,
pads,
compactKeys,
fields: normalizedFields
};
}
function parseTemplateFile(filePath, format) {
if (format === "kv") return parseKvTemplate(filePath);
if (format === "yaml") return parseYamlTemplate(filePath);
throw new Error(`Unsupported format: ${format}`);
}
function parseKeyValuePairs(setValue) {
if (!setValue) return [];
if (Array.isArray(setValue)) return setValue;
return [setValue];
}
// FLAGS3 field names — shorthand accepted in --set without namespace prefix
const FLAGS3_KEYS = ["context_label","tag","qty_unit","date_end","attachment","uid","url"];
function applySetPairs(record, pairs) {
for (const pair of pairs) {
const idx = pair.indexOf("=");
if (idx < 0) continue;
const key = pair.slice(0, idx).trim();
const value = pair.slice(idx + 1).trim();
if (key.startsWith("process.")) {
record.process[key.replace("process.", "")] = value;
} else if (key.startsWith("financial.")) {
if (!record.financial) record.financial = {};
record.financial[key.replace("financial.", "")] = value;
} else if (key.startsWith("flags3.")) {
if (!record.flags3) record.flags3 = {};
record.flags3[key.replace("flags3.", "")] = value;
} else if (key.startsWith("agreement.")) {
if (!record.agreement) record.agreement = {};
record.agreement[key.replace("agreement.", "")] = value;
} else if (key === "details" || key === "story") {
record[key] = value;
} else if (key.startsWith("flags4.")) {
if (!record.flags4) record.flags4 = {};
record.flags4[key.replace("flags4.", "")] = value;
} else if (FLAGS3_KEYS.includes(key)) {
if (!record.flags3) record.flags3 = {};
record.flags3[key] = value;
} else if (FLAGS4_CONTACT_KEYS.includes(key) || FLAGS4_FINANCIAL_KEYS.includes(key)) {
if (!record.flags4) record.flags4 = {};
record.flags4[key] = value;
} else {
record.process[key] = value;
}
}
}
function flattenForCodec(record) {
const flat = Object.assign({}, record.process || {});
if (record.details) flat.details = record.details;
if (record.story) flat.story = record.story;
if (Array.isArray(record.actions) && record.actions.length > 0) flat.actions = record.actions;
// FLAGS3 and FLAGS4 fields passed directly (codec picks up by name)
if (record.flags3) Object.assign(flat, record.flags3);
if (record.flags4) Object.assign(flat, record.flags4);
return flat;
}
function unflattenFromCodec(flat) {
const PROCESS_FIELDS = ["job","customer","date","location","meeting_time","start_time","end_time","customer_phone","worker"];
const proc = {};
PROCESS_FIELDS.forEach((k) => { if (flat[k] != null) proc[k] = flat[k]; });
let actions = [];
if (Array.isArray(flat.actions)) {
actions = flat.actions;
} else if (typeof flat.actions === "string" && flat.actions) {
actions = flat.actions.split("\n").filter(Boolean).map((t) => ({ title: t, notes: "" }));
}
const flags3 = {};
FLAGS3_KEYS.forEach((k) => { if (flat[k] != null) flags3[k] = flat[k]; });
return {
process: proc,
actions,
details: flat.details || "",
story: flat.story || "",
...(Object.keys(flags3).length ? { flags3 } : {}),
};
}
function normalizeRecordComments(record) {
if (!Array.isArray(record.comments)) record.comments = [];
record.comments = record.comments.map((c) => {
if (typeof c === "string") {
return { n: "", x: c, ts: new Date().toISOString() };
}
return {
n: c.n || "",
x: c.x || "",
ts: c.ts || new Date().toISOString()
};
});
}
function buildShareLinkForRecord(record) {
const flat = flattenForCodec(record);
const link = WPCodec.encode(flat);
return { link, bytes: Buffer.byteLength(link, "utf8") };
}
// ── Display helpers ───────────────────────────────────────────────────────────
function printResult(command, status, pairs) {
const col = Math.max(...pairs.map(([k]) => k.length));
console.log(`${command.padEnd(10)} ${status}`);
pairs.forEach(([k, v]) => console.log(` ${k.padEnd(col)} : ${v}`));
}
function resolveOutPath(arg) {
return path.isAbsolute(arg) ? arg : path.join(process.cwd(), arg);
}
function newRecordId(records) {
const seq = records.reduce((max, r) => Math.max(max, Number(r.seq || 0)), 0) + 1;
return { id: `loc_${String(seq).padStart(6, "0")}`, seq };
}
function printHelp() {
console.log(`Workpads CLI
Usage:
workpads template:validate --file <path> --format kv|yaml
workpads template:compile --file <path> --format kv|yaml --out <path>
workpads template:show --template <template-id>
workpads create --template svc-basic --variant plain --set process.job="Job title" [--business biz_001] [--storage-override ephemeral|stored]
workpads edit --record <id> --set details="..." --add-action "Title|Notes" [--business biz_001] [--storage-override ephemeral|stored]
workpads create --template svc-basic --set process.job="..." [--add-participant "Name|role|phone"]
[--amount 125.00 --direction O<O --currency GBP] [--tax-rate 200] [--expense-cat job-charge|cogs|running-cost]
workpads edit --record <id> [--add-participant "Name|role|phone"] [--amount <val>] [--set-financial-state paymentConfirmed]
workpads share --record <id> [--trig <expr>] [--ctrig <expr>] [--draft] [--no-forward] [--ack] [--chain]
workpads share --record <id> --encrypt <passphrase> (#1ps/ AES-CTR full)
workpads share --record <id> --partial-encrypt <passphrase> (#1ph/ header clear)
workpads share --record <id> --template-key <template-path> (#1pt/ template-keyed)
workpads share --record <id> --billboard (#1pb/ public)
workpads share --record <id> --anon [--anon-alias "Local trader"] (#1pb/ anonymous)
workpads share --record <id> --financial (#1pf/ financial presentation)
workpads share --record <id> --bundle --template <path> (data-sync bundle)
workpads import --url <share-link> [--pass <passphrase>] [--template <path>]
workpads render --record <id> [--json]
workpads inspect --record <id> [--trig <expr>]
workpads ctrig:eval --ctrig <expr|preset> [--record <id>] [--ctx key=value ...]
workpads list:share --items "item1,item2,item3" [--label "My list"]
workpads agreement:create --title "Job contract" --party "Alice" --worker "Bob" [--terms "..."] [--type service-contract] [--expiry 30] [--ctrig <expr>]
workpads agreement:accept --record <id> --name "Alice" [--role customer]
workpads agreement:status --record <id>
workpads agreement:complete --record <id>
workpads agreement:dispute --record <id> [--reason "..."]
workpads export --record <id> --out <path>
workpads list [--json]
workpads delete --record <id>
workpads storage:get --business <id>
workpads storage:set --business <id> --default ephemeral|stored [--ttl-hours N] [--allow-override true|false]
workpads storage:resolve --business <id> [--override ephemeral|stored]
workpads comment:add --record <id> --text "<comment>" [--name "<display>"]
workpads comment:list --record <id>
workpads comment:delete --record <id> --index <n>
workpads dashboard [--json]
workpads howto [--role owner|dispatcher|receiver|team|supervisor]
workpads browser [--port 8787] [--ui latest|v1] [--auto-port true|false] [--max-port-tries 20]
workpads browser:status
workpads browser:stop
Notes:
- Record store: .workpads/records.json
- Base URL default: ${DEFAULT_BASE_URL}
`);
}
function checkPortAvailable(port) {
return new Promise((resolve) => {
const tester = net.createServer();
tester.once("error", () => resolve(false));
tester.once("listening", () => {
tester.close(() => resolve(true));
});
tester.listen(port, "127.0.0.1");
});
}
async function findAvailablePort(startPort, maxTries) {
for (let i = 0; i < maxTries; i += 1) {
const candidate = startPort + i;
// eslint-disable-next-line no-await-in-loop
const ok = await checkPortAvailable(candidate);
if (ok) return candidate;
}
return null;
}
function printHowTo(role) {
const sections = {
owner: `OWNER: Set policy defaults
node ./workpads.js storage:set --business biz_001 --default ephemeral --ttl-hours 24 --allow-override true
node ./workpads.js storage:get --business biz_001`,
dispatcher: `DISPATCHER: Create, edit, and share
node ./workpads.js create --template svc-basic --variant plain --business biz_001 --set process.job="Replace faucet"
node ./workpads.js edit --record loc_000001 --add-action "Arrive|Inspect site" --set details="Bring standard tools"
node ./workpads.js share --record loc_000001`,
receiver: `RECEIVER: Import and view
echo "https://workpads.me/new#<payload>" | node ./workpads.js import
node ./workpads.js render --record loc_000002`,
team: `TEAM: Comment workflow
node ./workpads.js comment:add --record loc_000001 --text "Parts delivered" --name "Alex"
node ./workpads.js comment:list --record loc_000001`,
supervisor: `SUPERVISOR: Daily dashboard
node ./workpads.js list
node ./workpads.js dashboard`
};
if (role) {
const key = String(role).toLowerCase();
if (!sections[key]) {
throw new Error("Invalid --role. Expected owner|dispatcher|receiver|team|supervisor");
}
console.log(sections[key]);
return;
}
console.log(
[
"WORKPADS HOW-TO",
"",
sections.owner,
"",
sections.dispatcher,
"",
sections.receiver,
"",
sections.team,
"",
sections.supervisor,
"",
"Docs:",
" - cli.md",
" - cheat-sheet.md"
].join("\n")
);
}
function expandFromUrl(url) {
const flat = WPCodec.decode(url);
return unflattenFromCodec(flat);
}
function commandTemplateValidate(args) {
const filePath = args.file;
const format = args.format || "kv";
if (!filePath) throw new Error("Missing --file");
const full = path.isAbsolute(filePath) ? filePath : path.join(ROOT, filePath);
if (!fs.existsSync(full)) throw new Error(`File not found: ${full}`);
const normalized = parseTemplateFile(full, format);
console.log(
JSON.stringify(
{
ok: true,
templateId: normalized.templateId,
version: normalized.version,
fields: normalized.fields.length
},
null,
2
)
);
}
function commandTemplateCompile(args) {
const filePath = args.file;
const format = args.format || "kv";
const outPath = args.out;
if (!filePath) throw new Error("Missing --file");
if (!outPath) throw new Error("Missing --out");
const full = path.isAbsolute(filePath) ? filePath : path.join(ROOT, filePath);
const outFull = path.isAbsolute(outPath) ? outPath : path.join(ROOT, outPath);
const normalized = parseTemplateFile(full, format);
fs.mkdirSync(path.dirname(outFull), { recursive: true });
fs.writeFileSync(outFull, JSON.stringify(normalized, null, 2));
console.log(`Compiled template -> ${outFull}`);
}
function commandTemplateShow(args) {
const templateId = args.template || "svc-basic";
const runtimePath = path.join(ROOT, "templates", "runtime", `${templateId}.v1.json`);
if (!fs.existsSync(runtimePath)) throw new Error(`Template runtime file not found: ${runtimePath}`);
console.log(fs.readFileSync(runtimePath, "utf8"));
}
// Parse "Name|role|phone|email" participant shorthand
function parseParticipant(str) {
const ROLE_TYPES = { customer:0, worker:1, supplier:2 };
const parts = String(str).split("|").map(s => s.trim());
const name = parts[0] || "";
const role = parts[1] || "customer";
const phone = parts[2] || "";
const email = parts[3] || "";
const roleType = ROLE_TYPES[role] != null ? ROLE_TYPES[role] : 0;
return { name, roleType, phone: phone||undefined, email: email||undefined,
isSender: role === "worker" || role === "sender" };
}
function applyParticipants(record, addArgs) {
if (!addArgs) return;
const items = Array.isArray(addArgs) ? addArgs : [addArgs];
if (!record.participants) record.participants = [];
for (const item of items) record.participants.push(parseParticipant(item));
}
// FLAGS4 contact field names (when baseTemplate=3)
const FLAGS4_CONTACT_KEYS = ["website","social_handle","business_hours","alt_phone","meeting_location"];
// FLAGS4 financial field names (when baseTemplate=1 or 2)
const FLAGS4_FINANCIAL_KEYS = ["service_ref","expiry_date"];
function applyFinancialArgs(record, args) {
const hasFinArgs = args.amount || args.direction || args["compound-line"] || args.domain;
if (!hasFinArgs) return;
if (!record.financial) record.financial = {};
const f = record.financial;
if (args.amount) f.amount = args.amount;
if (args.direction) f.direction = args.direction;
if (args.currency) f.currency = args.currency;
if (args["decimal-pos"]) f.decimalPos = Number(args["decimal-pos"]);
if (args["tax-rate"]) f.taxRate = Number(args["tax-rate"]);
if (args["tax-code"]) f.taxCode = Number(args["tax-code"]);
if (args["worker-amount"]) f.workerAmount = args["worker-amount"];
if (args["expense-cat"]) f.expenseCat = args["expense-cat"];
if (args.subtype) f.subtype = Number(args.subtype);
if (args.rounding) f.rounding = Number(args.rounding);
if (args.qty) { f.qtySplit = true; f.qty = args.qty; }
if (args.rate) { f.qtySplit = true; f.rate = args.rate; }
if (args.billed) f.billed = args.billed !== "false";
if (args.domain) f.domain = Number(args.domain);
// Compound lines: --compound-line "Label|amount[|type=N]" (repeatable)
if (args["compound-line"]) {
const lines = Array.isArray(args["compound-line"]) ? args["compound-line"] : [args["compound-line"]];
f.compoundLines = (f.compoundLines || []).concat(lines.map(parseCompoundLine));
// Total = sum of lines if not explicitly set
if (!f.amount) {
const total = f.compoundLines.reduce((s, l) => s + parseFloat(l.amount || 0), 0);
f.amount = total.toFixed(2);
}
}
}
function commandCreate(args) {
const template = loadTemplate();
const records = loadRecords();
const { id, seq } = newRecordId(records);
const variant = args.variant || "plain";
const record = {
id,
seq,
templateId: args.template || template.templateId,
variant,
process: {},
actions: [],
details: "",
story: "",
comments: [],
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString()
};
normalizeRecordComments(record);
// State-commit template variant
if (args.template === "state-commit") {
record.variant = "state-commit";
record.templateId = "state-commit";
if (!record.financial) record.financial = {};
}
applySetPairs(record, parseKeyValuePairs(args.set));
applyParticipants(record, args["add-participant"]);
applyFinancialArgs(record, args);
// State-commit extra financial flags
if (record.variant === "state-commit" && args["commit-type"] != null)
record.financial.scCommitType = Number(args["commit-type"]);
if (record.variant === "state-commit" && args["period-type"] != null)
record.financial.scPeriodType = Number(args["period-type"]);
if (!record.process.job) {
throw new Error("Missing required field: process.job");
}
const storage = resolveStorageDecision(args, null);
if (storage) record.storage = storage;
records.push(record);
saveRecords(records);
console.log(JSON.stringify(record, null, 2));
}
function commandEdit(args) {
if (!args.record) throw new Error("Missing --record");
const records = loadRecords();
const record = records.find((r) => r.id === args.record);
if (!record) throw new Error(`Record not found: ${args.record}`);
normalizeRecordComments(record);
applySetPairs(record, parseKeyValuePairs(args.set));
applyParticipants(record, args["add-participant"]);
applyFinancialArgs(record, args);
if (args["add-action"]) {
const [title, notes] = String(args["add-action"]).split("|");
record.actions.push({ title: title || "", notes: notes || "" });
}
if (args["set-financial-state"]) {
if (!record.financial) record.financial = {};
record.financial[args["set-financial-state"]] = true;
}
const storage = resolveStorageDecision(args, record.storage && record.storage.businessId);
if (storage) record.storage = storage;
record.updatedAt = new Date().toISOString();
saveRecords(records);
console.log(JSON.stringify(record, null, 2));
}
// ── Wire helpers ──────────────────────────────────────────────────────────────
function toB64Url(buf) {
return Buffer.from(buf).toString("base64")
.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}
function fromB64Url(str) {
const padded = str + "==".slice(0, (4 - str.length % 4) % 4);
return Buffer.from(padded.replace(/-/g, "+").replace(/_/g, "/"), "base64");
}
// Get raw (decompressed) pads-v1 frame bytes for a flat record + opts
function getRawFrame(flat, opts) {
const { compressed } = WPCodec.encodeBinary(flat, opts || {});
return zlib.inflateRawSync(Buffer.from(compressed));
}
// ── Financial codec helpers ───────────────────────────────────────────────────
// I>O notation → codec bits
const IO_STATES = {
"I<I":{ioDirection:0,ioTime:0,ioEffect:0}, "I>I":{ioDirection:0,ioTime:1,ioEffect:0},
"I<O":{ioDirection:0,ioTime:0,ioEffect:1}, "I>O":{ioDirection:0,ioTime:1,ioEffect:1},
"O<O":{ioDirection:1,ioTime:0,ioEffect:1}, "O>O":{ioDirection:1,ioTime:1,ioEffect:1},
"O<I":{ioDirection:1,ioTime:0,ioEffect:0}, "O>I":{ioDirection:1,ioTime:1,ioEffect:0},
};
const IO_BY_BITS = {};
for (const [k,v] of Object.entries(IO_STATES)) {
IO_BY_BITS[`${v.ioDirection}${v.ioTime}${v.ioEffect}`] = k;
}
// transaction-classification.md §7 worker UI labels
const IO_LABELS = {
"I<I":"Payment received","I>I":"Invoice sent","I<O":"Refund given","I>O":"Credit note",
"O<O":"Expense paid","O>O":"Bill received","O<I":"Reimbursed","O>I":"Reimbursement pending",
};
// 2-bit currency slot (setup byte) + optional extended byte
const CURRENCY_SLOT = { GBP:0, USD:1, EUR:2 };
function parseCurrencyOpts(code) {
const up = String(code || "GBP").toUpperCase();
if (CURRENCY_SLOT[up] !== undefined) return { currency: CURRENCY_SLOT[up] };
return { currency: 3, currencyCode: up.codePointAt(0) & 0xFF };
}
// Expense category name → 2-bit fin_control value
const EXPENSE_CATS = {
"job-charge":0, "charge":0, "billed":0,
"cogs":1, "job-cost":1,
"running-cost":2, "running":2, "overhead":2,
};
// Convert record.financial object → codec encodeFrame opts
function financialToCodecOpts(fin) {
if (!fin || (fin.amount == null && fin.customerAmount == null && !fin.compoundLines)) return {};
const io = IO_STATES[fin.direction] || {};
const dp = fin.decimalPos != null ? Number(fin.decimalPos) : 2;
const taxCode= fin.taxCode != null ? Number(fin.taxCode) : (fin.taxRate ? 1 : 0);
const expCat = fin.expenseCat != null ? (EXPENSE_CATS[fin.expenseCat] ?? Number(fin.expenseCat)) : 0;
const amt = fin.amount != null ? fin.amount : fin.customerAmount;
const hasCompound = Array.isArray(fin.compoundLines) && fin.compoundLines.length > 0;
return {
domain: Number(fin.domain || 1),
decimalPos: dp,
...parseCurrencyOpts(fin.currency),
taxCode,
...(fin.taxRate != null ? { taxRate: Number(fin.taxRate) } : {}),
...(fin.taxAmount != null ? { taxAmount: Number(fin.taxAmount) } : {}),
...(amt != null ? { customerAmount: amt } : {}),
...(fin.workerAmount != null ? { workerAmount: String(fin.workerAmount) } : {}),
billed: !!fin.billed,
expenseCat: expCat,
qtySplit: !!fin.qtySplit,
...(fin.qty != null ? { qty: String(fin.qty) } : {}),
...(fin.rate != null ? { rate: String(fin.rate) } : {}),
...io,
ioSubtype: Number(fin.subtype || 0),
rounding: Number(fin.rounding || 0),
...(hasCompound ? { compoundValue: true, compoundLines: fin.compoundLines } : {}),
...(fin.hasTotalSummary != null ? { hasTotalSummary: !!fin.hasTotalSummary } : {}),
...(fin.hasSubtotals != null ? { hasSubtotals: !!fin.hasSubtotals } : {}),
};
}
// Parse compound line shorthand: "Label|amount[|type=N][|qty=N|rate=N]"
function parseCompoundLine(str) {
const CHARGE_TYPES = {
custom:0, urgency:1, "after-hours":2, travel:3, delivery:4,
"equipment-hire":5, materials:6, subcontractor:7, cancellation:8,
deposit:9, credit:10, warranty:11, compliance:12, fx:13, processing:14, multi:15,
};
const parts = String(str).split("|").map(s => s.trim());
const line = { name: parts[0] || "", amount: parts[1] || "0" };
for (let i = 2; i < parts.length; i++) {
const kv = parts[i].split("=");
if (kv[0] === "type") line.lineType = CHARGE_TYPES[kv[1]] ?? Number(kv[1]);
if (kv[0] === "qty") line.qty = kv[1];
if (kv[0] === "rate") line.rate = kv[1];
if (kv[0] === "tax") line.taxMode = Number(kv[1]);
}
return line;
}
// Build C-TRIG context from a stored record (for ctrig:eval --record)
function buildCTrigContext(record) {
const p = record.process || {};
const fin = record.financial || {};
const ag = record.agreement || {};
return {
has_phone: !!(p.customer_phone),
has_email: false,
has_uid: !!(record.flags3 && record.flags3.uid),
is_org: false,
has_chain: !!(record.chainParent),
ack_received: !!(record.ackReceived),
date_reached: p.date ? (new Date(p.date) <= new Date()) : false,
payment_confirmed: !!(fin.paymentConfirmed),
ratification_complete: ag.state === "active" || ag.state === "completed",
marker_written: !!(record.markerWritten),
linked_record_exists: !!(record.chainParent || record.linkedRecord),
all_parties_acked: Array.isArray(ag.parties) && ag.parties.length >= 2 && ag.parties.every(p => p.accepted),
full_payment_confirmed: !!(fin.fullPaymentConfirmed),
deposit_received: !!(fin.depositReceived),
partial_payment: !!(fin.partialPayment),
};
}
// ── Security wrapper (#1ps/) ──────────────────────────────────────────────────
// Spec: security-wrapper.md Layers: AES-CTR-128 + preamble byte
// Omits SEED_POISON and FIELD_SCRAMBLE (preamble bits left 0; decoders must tolerate)
function secureEncode(frameBytes, passphrase) {
const salt = crypto.randomBytes(4);
const master = crypto.createHash("sha256")
.update(Buffer.from(passphrase, "utf8")).update(salt).digest();
const cipherKey = master.slice(0, 16);
const iv = Buffer.alloc(16); cipherKey.copy(iv); // iv = cipher_key (safe: salt ensures unique master)
const deflated = zlib.deflateRawSync(frameBytes);
const cipher = crypto.createCipheriv("aes-128-ctr", cipherKey, iv);
const encrypted = Buffer.concat([cipher.update(deflated), cipher.final()]);
const preamble = 0x40 | (cipherKey[0] & 0x07); // AES=1, KEY_HINT=low3 of cipher_key[0]
return "workpads.me/p#1ps/" + toB64Url(salt) + "." + toB64Url(Buffer.concat([Buffer.from([preamble]), encrypted]));
}
function secureDecode(url, passphrase) {
const frag = url.slice(url.indexOf("#") + 1);
if (!frag.startsWith("1ps/")) throw new Error("Not a #1ps/ secure URL");
const payload = frag.slice(4);
const dotIdx = payload.indexOf(".");
if (dotIdx < 0) throw new Error("#1ps/ URL missing '.' separator");
const salt = fromB64Url(payload.slice(0, dotIdx));
const inner = fromB64Url(payload.slice(dotIdx + 1));
const preamble = inner[0];
const aesOn = (preamble >> 6) & 1;
if (!aesOn) throw new Error("AES bit not set in preamble — cannot decrypt");
const keyHint = preamble & 0x07;
const master = crypto.createHash("sha256")
.update(Buffer.from(passphrase, "utf8")).update(salt).digest();
const cipherKey = master.slice(0, 16);
if ((cipherKey[0] & 0x07) !== keyHint) throw new Error("KEY_HINT mismatch — wrong passphrase?");
const iv = Buffer.alloc(16); cipherKey.copy(iv);
const decipher = crypto.createDecipheriv("aes-128-ctr", cipherKey, iv);
const deflated = Buffer.concat([decipher.update(inner.slice(1)), decipher.final()]);
return zlib.inflateRawSync(deflated); // raw pads-v1 frame bytes
}
// #1ph/ — partial scramble: meta bytes left clear, rest AES-CTR
// Receiver sees BASE_TEMPLATE + DOMAIN before entering passphrase.
function partialSecureEncode(frameBytes, passphrase) {
const salt = crypto.randomBytes(4);
const master = crypto.createHash("sha256").update(Buffer.from(passphrase,"utf8")).update(salt).digest();
const cipherKey = master.slice(0,16);
const iv = Buffer.alloc(16); cipherKey.copy(iv);
// Clear header: meta1 always 1B; add meta2 if bit7 set; add setup+tx bytes if domain>0
let clearLen = 1;
if (frameBytes.length > 1 && (frameBytes[0] & 0x80)) {
clearLen = 2;
if (frameBytes.length > 3 && ((frameBytes[1] >> 2) & 0x3) > 0) clearLen = 4;
}
const clearHeader = frameBytes.slice(0, Math.min(clearLen, frameBytes.length));
const inner = frameBytes.slice(clearHeader.length);
const deflated = zlib.deflateRawSync(inner);
const cipher = crypto.createCipheriv("aes-128-ctr", cipherKey, iv);
const encrypted = Buffer.concat([cipher.update(deflated), cipher.final()]);
const preamble = 0x40 | (cipherKey[0] & 0x07);
const combined = Buffer.concat([Buffer.from([preamble]), clearHeader, encrypted]);
return "workpads.me/p#1ph/" + toB64Url(salt) + "." + toB64Url(combined);
}
function partialSecureDecode(url, passphrase) {
const frag = url.slice(url.indexOf("#") + 1);
if (!frag.startsWith("1ph/")) throw new Error("Not a #1ph/ URL");
const payload = frag.slice(4);
const dotIdx = payload.indexOf(".");
if (dotIdx < 0) throw new Error("#1ph/ URL missing '.' separator");
const salt = fromB64Url(payload.slice(0, dotIdx));
const combined = fromB64Url(payload.slice(dotIdx + 1));
const preamble = combined[0];
const keyHint = preamble & 0x07;
const master = crypto.createHash("sha256").update(Buffer.from(passphrase,"utf8")).update(salt).digest();
const cipherKey = master.slice(0,16);
if ((cipherKey[0] & 0x07) !== keyHint) throw new Error("KEY_HINT mismatch — wrong passphrase?");
const iv = Buffer.alloc(16); cipherKey.copy(iv);
// After preamble: clear_header bytes then encrypted payload
// We need to determine clear_header length from meta1
const afterPreamble = combined.slice(1);
const meta1Byte = afterPreamble[0];
let clearLen = 1;
if ((meta1Byte & 0x80) && afterPreamble.length > 1) {
clearLen = 2;
if (afterPreamble.length > 3 && ((afterPreamble[1] >> 2) & 0x3) > 0) clearLen = 4;
}
clearLen = Math.min(clearLen, afterPreamble.length);
const clearHeader = afterPreamble.slice(0, clearLen);
const encryptedPart = afterPreamble.slice(clearLen);
const decipher = crypto.createDecipheriv("aes-128-ctr", cipherKey, iv);
const deflated = Buffer.concat([decipher.update(encryptedPart), decipher.final()]);
const innerBytes = zlib.inflateRawSync(deflated);
return Buffer.concat([clearHeader, innerBytes]);
}
// #1pt/ — template-keyed: key = SHA-256(template_bytes || salt)[0:16]
// salt is random per-encode so same template → different keys across records
function templateKeyedEncode(frameBytes, templatePath) {
const tmplBytes = fs.readFileSync(templatePath);
const salt = crypto.randomBytes(4);
const cipherKey = crypto.createHash("sha256").update(tmplBytes).update(salt).digest().slice(0, 16);
const iv = Buffer.alloc(16); cipherKey.copy(iv);
const deflated = zlib.deflateRawSync(frameBytes);
const cipher = crypto.createCipheriv("aes-128-ctr", cipherKey, iv);
const encrypted = Buffer.concat([cipher.update(deflated), cipher.final()]);
const preamble = 0x40 | (cipherKey[0] & 0x07);
return "workpads.me/p#1pt/" + toB64Url(salt) + "." + toB64Url(Buffer.concat([Buffer.from([preamble]), encrypted]));
}
function templateKeyedDecode(url, templatePath) {
const frag = url.slice(url.indexOf("#") + 1);
if (!frag.startsWith("1pt/")) throw new Error("Not a #1pt/ URL");
const payload = frag.slice(4);
const dotIdx = payload.indexOf(".");
if (dotIdx < 0) throw new Error("#1pt/ URL missing '.' separator");
const salt = fromB64Url(payload.slice(0, dotIdx));
const tmplBytes = fs.readFileSync(templatePath);
const cipherKey = crypto.createHash("sha256").update(tmplBytes).update(salt).digest().slice(0, 16);
const iv = Buffer.alloc(16); cipherKey.copy(iv);
const inner = fromB64Url(payload.slice(dotIdx + 1));
const preamble = inner[0];
if ((cipherKey[0] & 0x07) !== (preamble & 0x07)) throw new Error("KEY_HINT mismatch — wrong template or salt?");
const decipher = crypto.createDecipheriv("aes-128-ctr", cipherKey, iv);
const deflated = Buffer.concat([decipher.update(inner.slice(1)), decipher.final()]);
return zlib.inflateRawSync(deflated);
}
// ── Data Sync Bundle (workpads.me/sync#1pa/) ──────────────────────────────────
// Spec: data-sync-bundle.md