-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpipebuilder.py
More file actions
executable file
·3565 lines (3266 loc) · 149 KB
/
Copy pathpipebuilder.py
File metadata and controls
executable file
·3565 lines (3266 loc) · 149 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 python3
"""PipeBuilder: capability reuse and workspace construction across AI coding agents.
PipeBuilder packages standard Skills and platform-native Rules, Hooks, Commands,
Agents, and MCP configurations into reusable capability bundles. It generates
native project configurations for Codex, Cursor, CodeBuddy, and Claude Code.
A workspace that is decoupled from the project directory and independently
selects its agents and capability combination is called a PipeSpace. Multiple
PipeSpace task pipelines may reference the same project.
Distribution and runtime requirements
-------------------------------------
This file is an independently distributable single-file CLI. It does not depend
on this repository's README, docs, tests, or any third-party Python package.
Python 3.7+ is required. System Git is required only when using a Git Provider.
Quick start
-----------
python3 pipebuilder.py init [SPACE] [--name NAME] [--format text|json]
python3 pipebuilder.py check [SPACE] [--format text|json] [--offline]
python3 pipebuilder.py explain [SPACE] [--format text|json] [--offline]
python3 pipebuilder.py build [SPACE] [--format text|json] [--offline] [--dry-run]
python3 pipebuilder.py verify [SPACE] [--format text|json]
python3 pipebuilder.py clean [SPACE] [--format text|json]
python3 pipebuilder.py --version
python3 pipebuilder.py --help
SPACE defaults to the current directory when omitted. Run check or
build --dry-run before build. --offline resolves Git Providers only from an
existing lock and the local immutable Git cache, without contacting origin.
Minimal PipeSpace inputs
------------------------
<space>/
├── pipespace.json
└── <manifest.name>.code-workspace
Minimal pipespace.json:
{"schema":"pipespace.v1", "name":"my-space", "agents":["codex"],
"skills":[], "tags":[], "skillProviders":[]}
Minimal my-space.code-workspace:
{"folders":[{"path":"."}]}
Commands automatically discover nested PipeSpaces by finding pipespace.json
within three directory levels. Configure or disable discovery in pipespace.json:
{"children":{"scanDepth":3}}
The complete hierarchy is planned before writes, built root-to-children, and
cleaned children-to-root. Hidden, generated, and symlinked directories are not
scanned.
Optional space-level sources:
.pipebuilder/agents/<agent>/
.pipebuilder/skills/<skill>/SKILL.md
External Skill Providers are declared in pipespace.json.skillProviders.
Supported forms:
{"type":"folder", "path":"../shared-skills"}
{"type":"folder", "path":"../component", "subdir":"skills",
"command":{"cwd":".", "args":["node","build.mjs","--output","{pipespaceRoot}"]}}
{"type":"git", "url":"https://example/repo.git", "branch":"main", "subdir":"skills"}
{"type":"git", "url":"https://example/repo.git", "tag":"v1.0.0", "subdir":"skills"}
Git Providers must specify exactly one of branch or tag. Authentication is
delegated to the Git credential helper or SSH agent; credentials must never be
written to the manifest. Git mirrors and immutable snapshots are cached under
<space>/.pipebuilder/cache/git/ as ignored local Builder state.
For Folder and Git Providers, subdir is the Skill Provider root and defaults to
the current directory. An optional command runs after a normal build by default.
Its cwd is relative to the Provider source root, its args bypass the shell, and
{pipespaceRoot}, {sourceRoot}, and {providerRoot} are expanded. check, explain,
and build --dry-run do not invoke the command.
Ownership and outputs
---------------------
Platform configurations and installed Skills are Builder-owned targets.
Human-owned sources may only reside in .pipebuilder/agents, .pipebuilder/skills,
or external Providers. build records ownership in .pipebuilder/lock.json; clean
removes only files that a valid lock proves are Builder-managed. Do not directly
maintain generated AGENTS.md, CLAUDE.md, .codex, .cursor, .codebuddy, .claude,
or .agents/skills content. Modify the source and run build again instead.
Automation should use --format json and rely on stable diagnostic codes in
pipebuilder-report.v1. It must not parse human-readable messages. Run this
file with --help at any time for complete command documentation.
"""
from __future__ import annotations
import argparse
import ast
import dataclasses
import hashlib
import io
import json
import os
import re
import shutil
import socket
import stat
import subprocess
import sys
import tarfile
import tempfile
import time
import unicodedata
from contextlib import ExitStack
from pathlib import Path
from typing import Any, Iterable
from datetime import datetime, timezone
from urllib.parse import urlsplit
try:
import tomllib as _tomllib
except ImportError: # Python 3.7-3.10 use the dependency-free compatibility parser below.
_tomllib = None
VERSION = "0.1.3"
REPORT_SCHEMA = "pipebuilder-report.v1"
LOCK_SCHEMA = "pipebuilder-lock.v1"
SPACE_SCHEMA = "pipespace.v1"
TREE_LOCK_SCHEMA = "pipespace-tree-lock.v1"
DEFAULT_CHILD_SCAN_DEPTH = 3
MAX_CHILD_SCAN_DEPTH = 32
AGENTS = ("codex", "cursor", "codebuddy", "claude-code")
NAME_RE = re.compile(r"^[a-z][a-z0-9-]*$")
BARE_TOML_KEY_RE = re.compile(r"^[A-Za-z0-9_-]+$")
SECRET_KEY_RE = re.compile(
r"(^|[_-])(token|password|passwd|secret|api[_-]?key|authorization|credential)([_-]|$)",
re.IGNORECASE,
)
LEGACY_NAMES = (
"tagents",
"private",
"harness-space.json",
"harness-space-tree.json",
"pipespace-tree.json",
".harness-builder",
".harness-agents",
".harness-space.yaml",
".harness-lock.yaml",
)
DISCOVERY_RESERVED_ROOTS = {
".agents",
".claude",
".codebuddy",
".codex",
".cursor",
".git",
".harness-builder",
".pipebuilder",
}
DISCOVERY_EXCLUDED_DIRS = DISCOVERY_RESERVED_ROOTS | {
"__pycache__",
"build",
"dist",
"node_modules",
"out",
"target",
}
DISCOVERY_EXCLUDED_KEYS = frozenset(item.casefold() for item in DISCOVERY_EXCLUDED_DIRS)
ADAPTER_VERSIONS = {"codex": "2", "cursor": "1", "codebuddy": "2", "claude-code": "2"}
ADAPTER_STATUS = {
"codex": "client-verified",
"cursor": "client-verified",
"codebuddy": "generated-only",
"claude-code": "client-verified",
}
CODEX_FORBIDDEN_PROJECT_KEYS = {
"openai_base_url",
"chatgpt_base_url",
"apps_mcp_product_sku",
"model_provider",
"model_providers",
"notify",
"profile",
"profiles",
"experimental_realtime_ws_base_url",
"otel",
}
DIAGNOSTIC_ACTIONS = {
"PB001": "Correct pipespace.json or the ownership lock to match the documented schema.",
"PB002": "Use a lowercase kebab-case PipeSpace name.",
"PB003": "Create the required <manifest-name>.code-workspace file.",
"PB004": "Correct the workspace folders and paths.",
"PB005": "Correct the Provider path or create the directory.",
"PB006": "Use a supported Skill Provider type.",
"PB007": "Add the Skill to a configured Provider or remove it from the explicit selection.",
"PB008": "Correct the Skill package and SKILL.md frontmatter.",
"PB009": "Use the supported native artifact grammar for this Agent.",
"PB010": "Resolve the ownership, target, or semantic conflict and rebuild.",
"PB011": "Remove the unsafe path, secret, or configuration and retry.",
"PB012": "Use an implemented Agent adapter.",
"PB013": "Wait for the active build or clean operation to finish.",
"PB014": "Confirm the process is gone, then remove the stale build.lock.",
"PB015": "Migrate the legacy HarnessBuilder / THarness layout before building.",
"PB016": "Correct the Provider post command or its runtime dependencies and retry.",
"PB017": "Correct nested PipeSpace inputs or the recorded hierarchy state and retry.",
"PBW001": "Review the selected Provider and shadowed Skill candidates.",
"PBW002": "Prefer a standard Skill for new Claude Code workflows.",
"PBW003": "Review the generated platform security surface before use.",
}
@dataclasses.dataclass(frozen=True)
class Diagnostic:
level: str
code: str
message: str
sources: tuple[str, ...] = ()
target: str | None = None
semantic_key: str | None = None
suggested_action: str | None = None
def as_dict(self) -> dict[str, Any]:
result: dict[str, Any] = {
"level": self.level,
"code": self.code,
"message": self.message,
"sources": list(self.sources),
}
if self.target is not None:
result["target"] = self.target
if self.semantic_key is not None:
result["semanticKey"] = self.semantic_key
if self.target is None and self.semantic_key is None:
result["semanticKey"] = self.code
result["suggestedAction"] = self.suggested_action or DIAGNOSTIC_ACTIONS.get(
self.code,
"Review the diagnostic source and correct the PipeSpace input.",
)
return result
class PipeBuilderError(Exception):
def __init__(self, diagnostic: Diagnostic):
super().__init__(diagnostic.message)
self.diagnostic = diagnostic
def fail(
code: str,
message: str,
*,
sources: Iterable[str] = (),
target: str | None = None,
semantic_key: str | None = None,
action: str | None = None,
) -> None:
raise PipeBuilderError(
Diagnostic(
"error",
code,
message,
tuple(sources),
target,
semantic_key,
action,
)
)
def sha256_bytes(data: bytes) -> str:
return "sha256:" + hashlib.sha256(data).hexdigest()
def sha256_file(path: Path) -> str:
return sha256_bytes(path.read_bytes())
def canonical_json(value: Any) -> str:
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
def json_bytes(value: Any) -> bytes:
return (json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2) + "\n").encode()
def portable_rel(root: Path, path: Path) -> str:
try:
return path.relative_to(root).as_posix() or "."
except ValueError:
return path.as_posix()
def read_json(path: Path, code: str, label: str) -> Any:
try:
return json.loads(path.read_text(encoding="utf-8"))
except FileNotFoundError:
fail(code, f"{label} not found: {path.name}", sources=(path.as_posix(),))
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
fail(code, f"Invalid {label}: {exc}", sources=(path.as_posix(),))
def require_string_list(value: Any, field: str, *, nonempty: bool = False) -> list[str]:
if not isinstance(value, list) or any(not isinstance(item, str) or not item for item in value):
fail("PB001", f"manifest.{field} must be an array of non-empty strings")
if nonempty and not value:
fail("PB001", f"manifest.{field} must contain at least one item")
if len(set(value)) != len(value):
fail("PB001", f"manifest.{field} must not contain duplicates")
return list(value)
def yaml_scalar(value: str) -> str:
value = value.strip()
if len(value) >= 2 and value[0] == value[-1] == '"':
try:
parsed = json.loads(value)
except json.JSONDecodeError:
return value[1:-1]
return parsed if isinstance(parsed, str) else value
if len(value) >= 2 and value[0] == value[-1] == "'":
return value[1:-1].replace("''", "'")
return value
def yaml_inline_list(value: str, path: Path, key: str, code: str = "PB008") -> list[Any]:
try:
parsed = json.loads(value)
except json.JSONDecodeError:
try:
parsed = ast.literal_eval(value)
except (SyntaxError, ValueError):
if value.startswith("[") and value.endswith("]"):
parsed = [yaml_scalar(item) for item in value[1:-1].split(",") if item.strip()]
else:
parsed = None
if not isinstance(parsed, list):
fail(code, f"Invalid inline list for {key}", sources=(path.as_posix(),))
return parsed
def yaml_block_scalar(marker: str, body: list[str]) -> str:
nonempty = [len(line) - len(line.lstrip()) for line in body if line.strip()]
indent = min(nonempty) if nonempty else 0
values = [line[indent:] if line.strip() else "" for line in body]
if marker.startswith("|"):
result = "\n".join(values)
else:
chunks: list[str] = []
for value in values:
if not value:
chunks.append("\n")
elif chunks and not chunks[-1].endswith("\n"):
chunks.append(" " + value)
else:
chunks.append(value)
result = "".join(chunks)
if marker.endswith("-"):
return result.rstrip("\n")
return result.rstrip("\n") + "\n"
def parse_frontmatter(path: Path) -> dict[str, Any]:
try:
text = path.read_text(encoding="utf-8-sig")
except UnicodeDecodeError:
fail("PB008", "SKILL.md must be UTF-8", sources=(path.as_posix(),))
lines = text.splitlines()
if not lines or lines[0].strip() != "---":
fail("PB008", "SKILL.md is missing YAML frontmatter", sources=(path.as_posix(),))
try:
end = next(i for i in range(1, len(lines)) if lines[i].strip() == "---")
except StopIteration:
fail("PB008", "SKILL.md frontmatter is not closed", sources=(path.as_posix(),))
fields: list[tuple[str, str, list[str]]] = []
i = 1
while i < end:
raw = lines[i]
i += 1
stripped = raw.strip()
if not stripped or stripped.startswith("#"):
continue
if raw[:1].isspace() or ":" not in raw:
fail("PB008", f"Unsupported SKILL.md frontmatter syntax: {stripped}", sources=(path.as_posix(),))
key, raw_value = raw.split(":", 1)
key = key.strip()
value = raw_value.strip()
if not key:
fail("PB008", "Empty SKILL.md frontmatter key", sources=(path.as_posix(),))
body: list[str] = []
while i < end and (not lines[i].strip() or lines[i][:1].isspace() or lines[i].lstrip().startswith("#")):
body.append(lines[i])
i += 1
fields.append((key, value, body))
data: dict[str, Any] = {}
for key, value, body in fields:
if key in data:
fail("PB008", f"Duplicate SKILL.md frontmatter key: {key}", sources=(path.as_posix(),))
if key not in {"name", "description", "tags"}:
continue
if key == "tags":
if value:
data[key] = yaml_inline_list(value, path, key) if value.startswith("[") else yaml_scalar(value)
else:
items: list[str] = []
for nested_raw in body:
nested = nested_raw.strip()
if not nested or nested.startswith("#"):
continue
if not nested.startswith("- "):
fail("PB008", "Skill tags must be a YAML list", sources=(path.as_posix(),))
items.append(yaml_scalar(nested[2:]))
data[key] = items
elif value.startswith(("|", ">")):
if not re.fullmatch(r"[>|](?:[+-]?[1-9]?|[1-9][+-]?)", value):
fail("PB008", f"Invalid block scalar marker for {key}", sources=(path.as_posix(),))
data[key] = yaml_block_scalar(value, body)
elif any(line.strip() and not line.lstrip().startswith("#") for line in body):
fail("PB008", f"{key} must be a scalar", sources=(path.as_posix(),))
else:
data[key] = yaml_scalar(value)
return data
def valid_string_or_string_list(value: Any) -> bool:
return (isinstance(value, str) and bool(value.strip())) or (
isinstance(value, list) and all(isinstance(item, str) and item.strip() for item in value)
)
def validate_codebuddy_agent(path: Path) -> None:
data = parse_frontmatter_generic(path)
for key in ("name", "description"):
if not isinstance(data.get(key), str) or not data[key].strip():
fail("PB009", f"{path.name} must declare non-empty {key} frontmatter", sources=(path.as_posix(),))
if "mode" in data and (not isinstance(data["mode"], str) or not data["mode"].strip()):
fail("PB009", "CodeBuddy agent mode must be a non-empty string", sources=(path.as_posix(),))
for key in ("tools", "allowedTools", "disallowedTools"):
if key in data and not valid_string_or_string_list(data[key]):
fail("PB009", f"CodeBuddy agent {key} must be a string or string list", sources=(path.as_posix(),))
def validate_claude_agent(path: Path) -> dict[str, Any]:
data = parse_frontmatter_generic(path)
for key in ("name", "description"):
if not isinstance(data.get(key), str) or not data[key].strip():
fail("PB009", f"{path.name} must declare non-empty {key} frontmatter", sources=(path.as_posix(),))
for key in ("tools", "disallowedTools", "skills"):
if key in data and not valid_string_or_string_list(data[key]):
fail("PB009", f"Claude agent {key} must be a string or string list", sources=(path.as_posix(),))
if "isolation" in data and data["isolation"] != "worktree":
fail("PB009", "Claude agent isolation must be worktree", sources=(path.as_posix(),))
if "hooks" in data and not isinstance(data["hooks"], dict):
fail("PB009", "Claude agent hooks must be a mapping", sources=(path.as_posix(),))
return data
def validate_claude_rule(path: Path) -> None:
try:
first = path.read_text(encoding="utf-8-sig").splitlines()[0]
except (UnicodeDecodeError, IndexError):
fail("PB009", "Claude rule must be UTF-8 and non-empty", sources=(path.as_posix(),))
if first.strip() != "---":
return
data = parse_frontmatter_generic(path)
if "paths" in data and not valid_string_or_string_list(data["paths"]):
fail("PB009", "Claude rule paths must be a string or string list", sources=(path.as_posix(),))
def parse_frontmatter_generic(path: Path) -> dict[str, Any]:
try:
lines = path.read_text(encoding="utf-8-sig").splitlines()
except UnicodeDecodeError:
fail("PB009", "Agent Markdown must be UTF-8", sources=(path.as_posix(),))
if not lines or lines[0].strip() != "---":
fail("PB009", "Agent Markdown is missing frontmatter", sources=(path.as_posix(),))
try:
end = next(i for i in range(1, len(lines)) if lines[i].strip() == "---")
except StopIteration:
fail("PB009", "Agent Markdown frontmatter is not closed", sources=(path.as_posix(),))
fields: list[tuple[str, str, list[str]]] = []
i = 1
while i < end:
raw = lines[i]
i += 1
if not raw.strip() or raw.lstrip().startswith("#"):
continue
if raw[:1].isspace() or ":" not in raw:
fail("PB009", f"Unsupported Agent Markdown frontmatter syntax: {raw.strip()}", sources=(path.as_posix(),))
key, value = raw.split(":", 1)
body: list[str] = []
while i < end and (not lines[i].strip() or lines[i][:1].isspace() or lines[i].lstrip().startswith("#")):
body.append(lines[i])
i += 1
fields.append((key.strip(), value.strip(), body))
data: dict[str, Any] = {}
for key, value, body in fields:
if not key or key in data:
fail("PB009", f"Invalid or duplicate Agent Markdown frontmatter key: {key}", sources=(path.as_posix(),))
if value.startswith("["):
data[key] = yaml_inline_list(value, path, key, "PB009")
elif value.startswith(("|", ">")):
data[key] = yaml_block_scalar(value, body)
elif not value and body:
items: list[str] = []
list_shaped = True
for nested_raw in body:
nested = nested_raw.strip()
if not nested or nested.startswith("#"):
continue
if not nested.startswith("- "):
list_shaped = False
break
items.append(yaml_scalar(nested[2:]))
data[key] = items if list_shaped else {"__raw__": "\n".join(body)}
else:
data[key] = yaml_scalar(value)
return data
@dataclasses.dataclass
class Manifest:
path: Path
name: str
description: str | None
agents: list[str]
skills: list[str]
tags: list[str]
providers: list[dict[str, Any]]
child_scan_depth: int
@dataclasses.dataclass(frozen=True)
class TreeChild:
path: str
expect_name: str
root: Path
@dataclasses.dataclass(frozen=True)
class SpaceTree:
root: Path
path: Path
parent_name: str
children: list[TreeChild]
scan_depth: int
@dataclasses.dataclass(frozen=True)
class TreeMember:
kind: str
path: str
expect_name: str
root: Path
@dataclasses.dataclass
class WorkspaceFolder:
name: str
path: str
resolved: Path
@dataclasses.dataclass
class Workspace:
path: Path
folders: list[WorkspaceFolder]
@dataclasses.dataclass
class Provider:
provider_id: str
root: Path
source_root: Path
configured_path: str
priority: int
digest: str
provider_type: str = "folder"
url: str | None = None
selector_kind: str | None = None
selector_value: str | None = None
commit: str | None = None
subdir: str | None = None
command: dict[str, Any] | None = None
@dataclasses.dataclass
class Skill:
name: str
description: str
tags: list[str]
root: Path
provider: Provider
digest: str
selected_by: str = ""
matched_tags: list[str] = dataclasses.field(default_factory=list)
shadowed: list[dict[str, str]] = dataclasses.field(default_factory=list)
@dataclasses.dataclass
class Contribution:
target: str
content: bytes
source: str
logical_type: str
merge: str = "plain"
executable: bool = False
semantic_key: str | None = None
risks: list[dict[str, str]] = dataclasses.field(default_factory=list)
@dataclasses.dataclass
class Operation:
target: str
content: bytes
sources: list[str]
logical_type: str
operation: str
executable: bool = False
semantic_key: str = ""
risks: list[dict[str, str]] = dataclasses.field(default_factory=list)
@property
def digest(self) -> str:
return sha256_bytes(self.content)
def detect_legacy(root: Path) -> None:
found = [name for name in LEGACY_NAMES if (root / name).exists() or (root / name).is_symlink()]
found.extend(path.name for path in root.glob("*.code-workspace.src"))
if found:
fail(
"PB015",
"Legacy THarness layout detected: " + ", ".join(sorted(set(found))),
sources=tuple(sorted(set(found))),
action="Migrate legacy HarnessBuilder / THarness layout to pipespace.json and .pipebuilder before building.",
)
def validate_provider_subdir(value: Any, index: int) -> str:
subdir = value if value is not None else "."
if not isinstance(subdir, str) or not subdir.strip():
fail("PB001", f"skillProviders[{index}].subdir must be a non-empty relative POSIX path")
subdir_path = Path(subdir)
if subdir_path.is_absolute() or "\\" in subdir or any(part in {"", ".."} for part in subdir.split("/")):
fail("PB001", f"skillProviders[{index}].subdir must be a safe relative POSIX path")
return subdir_path.as_posix()
def validate_provider_command(value: Any, index: int) -> dict[str, Any] | None:
if value is None:
return None
if not isinstance(value, dict) or set(value) - {"cwd", "args"} or "args" not in value:
fail("PB001", f"skillProviders[{index}].command accepts cwd and required args")
cwd = value.get("cwd", ".")
if (
not isinstance(cwd, str)
or not cwd.strip()
or Path(cwd).is_absolute()
or "\\" in cwd
or any(part in {"", ".."} for part in cwd.split("/"))
):
fail("PB001", f"skillProviders[{index}].command.cwd must be a safe relative POSIX path")
arguments = value.get("args")
if (
not isinstance(arguments, list)
or not arguments
or any(not isinstance(argument, str) or not argument or any(ord(char) < 32 for char in argument) for argument in arguments)
):
fail("PB001", f"skillProviders[{index}].command.args must be an array of non-empty strings")
return {"cwd": Path(cwd).as_posix(), "args": list(arguments)}
def load_manifest(root: Path) -> Manifest:
path = root / "pipespace.json"
raw = read_json(path, "PB001", "manifest")
if not isinstance(raw, dict):
fail("PB001", "pipespace.json must contain a JSON object", sources=(path.as_posix(),))
required = {"schema", "name", "agents", "skills", "tags", "skillProviders"}
missing = sorted(required - raw.keys())
unknown = sorted(raw.keys() - required - {"description", "children"})
if missing:
fail("PB001", "Missing manifest fields: " + ", ".join(missing), sources=(path.as_posix(),))
if unknown:
fail("PB001", "Unknown manifest fields: " + ", ".join(unknown), sources=(path.as_posix(),))
if raw.get("schema") != SPACE_SCHEMA:
fail("PB001", f"manifest.schema must be {SPACE_SCHEMA}", sources=(path.as_posix(),))
name = raw.get("name")
if not isinstance(name, str) or not NAME_RE.fullmatch(name):
fail("PB002", "manifest.name must match ^[a-z][a-z0-9-]*$", sources=(path.as_posix(),))
agents = require_string_list(raw.get("agents"), "agents", nonempty=True)
unknown_agents = [agent for agent in agents if agent not in AGENTS]
if unknown_agents:
fail("PB001", "Unknown agents: " + ", ".join(unknown_agents), sources=(path.as_posix(),))
skills = require_string_list(raw.get("skills"), "skills")
for skill in skills:
if not NAME_RE.fullmatch(skill):
fail("PB001", f"Invalid skill name in manifest: {skill}", sources=(path.as_posix(),))
tags = require_string_list(raw.get("tags"), "tags")
providers_raw = raw.get("skillProviders")
if not isinstance(providers_raw, list):
fail("PB001", "manifest.skillProviders must be an array", sources=(path.as_posix(),))
providers: list[dict[str, Any]] = []
seen_provider_specs: set[str] = set()
for index, item in enumerate(providers_raw):
if not isinstance(item, dict) or not isinstance(item.get("type"), str):
fail("PB001", f"skillProviders[{index}] must be an object with a type", sources=(path.as_posix(),))
kind = item["type"]
if kind == "folder":
allowed = {"type", "path", "subdir", "command"}
if set(item) - allowed or not {"type", "path"}.issubset(item):
fail("PB001", f"skillProviders[{index}] folder accepts type, path, optional subdir and command", sources=(path.as_posix(),))
configured = item.get("path")
if not isinstance(configured, str) or not configured.strip():
fail("PB001", f"skillProviders[{index}].path must be a non-empty string", sources=(path.as_posix(),))
if Path(configured).is_absolute():
fail("PB001", f"skillProviders[{index}].path must be relative", sources=(path.as_posix(),))
normalized_subdir = validate_provider_subdir(item.get("subdir"), index)
command = validate_provider_command(item.get("command"), index)
normalized_provider_path = Path(os.path.normpath(configured)).as_posix()
normalized = {"type": kind, "path": os.path.normcase(normalized_provider_path), "subdir": normalized_subdir}
provider = {"type": kind, "path": configured, "subdir": normalized_subdir}
if command is not None:
normalized["command"] = command
provider["command"] = command
elif kind == "git":
allowed = {"type", "url", "branch", "tag", "subdir", "command"}
if set(item) - allowed or not {"type", "url"}.issubset(item):
fail(
"PB001",
f"skillProviders[{index}] git accepts type, url, exactly one of branch/tag, and optional subdir",
sources=(path.as_posix(),),
)
selectors = [key for key in ("branch", "tag") if key in item]
if len(selectors) != 1:
fail("PB001", f"skillProviders[{index}] git requires exactly one of branch or tag", sources=(path.as_posix(),))
url = item.get("url")
if not isinstance(url, str) or not url.strip() or any(ord(char) < 32 for char in url):
fail("PB001", f"skillProviders[{index}].url must be a non-empty string", sources=(path.as_posix(),))
parsed_url = urlsplit(url)
if parsed_url.password is not None or (parsed_url.scheme in {"http", "https"} and parsed_url.username is not None):
fail("PB011", f"skillProviders[{index}].url must not contain credentials", sources=(path.as_posix(),))
if parsed_url.scheme in {"http", "https"} and (parsed_url.query or parsed_url.fragment):
fail("PB011", f"skillProviders[{index}].url must not contain query credentials or fragments", sources=(path.as_posix(),))
selector_kind = selectors[0]
selector_value = item.get(selector_kind)
if (
not isinstance(selector_value, str)
or not selector_value.strip()
or selector_value.startswith(("-", "refs/"))
or selector_value.endswith(("/", ".", ".lock"))
or ".." in selector_value
or "//" in selector_value
or "@{" in selector_value
or selector_value == "@"
or "\\" in selector_value
or any(part.startswith(".") or part.endswith(".lock") for part in selector_value.split("/"))
or any(char.isspace() or ord(char) < 32 or char in "~^:?*[" for char in selector_value)
):
fail("PB001", f"skillProviders[{index}].{selector_kind} is not a safe Git name", sources=(path.as_posix(),))
normalized_subdir = validate_provider_subdir(item.get("subdir"), index)
command = validate_provider_command(item.get("command"), index)
normalized = {
"type": kind,
"url": url,
selector_kind: selector_value,
"subdir": normalized_subdir,
}
provider = dict(normalized)
if command is not None:
normalized["command"] = command
provider["command"] = command
else:
fail("PB006", f"Unsupported provider type: {kind}", sources=(path.as_posix(),))
spec = canonical_json(normalized)
if spec in seen_provider_specs:
fail("PB001", f"Duplicate skill provider at index {index}", sources=(path.as_posix(),))
seen_provider_specs.add(spec)
providers.append(provider)
description = raw.get("description")
if description is not None and not isinstance(description, str):
fail("PB001", "manifest.description must be a string", sources=(path.as_posix(),))
children = raw.get("children", {"scanDepth": DEFAULT_CHILD_SCAN_DEPTH})
if not isinstance(children, dict) or set(children) != {"scanDepth"}:
fail(
"PB001",
"manifest.children accepts exactly scanDepth",
sources=(path.as_posix(),),
semantic_key="children",
)
scan_depth = children.get("scanDepth")
if (
isinstance(scan_depth, bool)
or not isinstance(scan_depth, int)
or not 0 <= scan_depth <= MAX_CHILD_SCAN_DEPTH
):
fail(
"PB001",
f"manifest.children.scanDepth must be an integer from 0 to {MAX_CHILD_SCAN_DEPTH}",
sources=(path.as_posix(),),
semantic_key="children.scanDepth",
)
return Manifest(path, name, description, agents, skills, tags, providers, scan_depth)
def is_discovery_excluded(path: Path) -> bool:
return path.name.startswith(".") or path.name.casefold() in DISCOVERY_EXCLUDED_KEYS
def discover_space_tree(root: Path) -> SpaceTree:
root = root.resolve()
parent = load_manifest(root)
children: list[TreeChild] = []
def scan(directory: Path, depth: int) -> None:
if depth >= parent.child_scan_depth:
return
try:
entries = sorted(
directory.iterdir(),
key=lambda item: unicodedata.normalize("NFC", item.name).casefold(),
)
except OSError as exc:
fail("PB017", f"Cannot scan nested PipeSpaces: {exc}", sources=(directory.as_posix(),))
for entry in entries:
if entry.is_symlink() or is_discovery_excluded(entry) or not entry.is_dir():
continue
manifest_path = entry / "pipespace.json"
if manifest_path.is_symlink():
fail("PB017", "Nested pipespace.json must not be a symlink", sources=(manifest_path.as_posix(),))
if manifest_path.exists():
child_manifest = load_manifest(entry)
children.append(
TreeChild(
entry.relative_to(root).as_posix(),
child_manifest.name,
entry.resolve(),
)
)
scan(entry, depth + 1)
if parent.child_scan_depth:
scan(root, 0)
return SpaceTree(root, parent.path, parent.name, children, parent.child_scan_depth)
def tree_members(tree: SpaceTree) -> list[TreeMember]:
return [TreeMember("parent", ".", tree.parent_name, tree.root)] + [
TreeMember("child", item.path, item.expect_name, item.root) for item in tree.children
]
def load_workspace(root: Path, manifest: Manifest) -> Workspace:
path = root / f"{manifest.name}.code-workspace"
if not path.exists():
fail("PB003", f"workspace not found: {path.name}", sources=(path.as_posix(),))
raw = read_json(path, "PB004", "workspace")
if not isinstance(raw, dict) or not isinstance(raw.get("folders"), list) or not raw["folders"]:
fail("PB004", "workspace.folders must be a non-empty array", sources=(path.as_posix(),))
folders: list[WorkspaceFolder] = []
names: set[str] = set()
resolved_keys: set[str] = set()
for index, item in enumerate(raw["folders"]):
if not isinstance(item, dict):
fail("PB004", f"workspace.folders[{index}] must be an object", sources=(path.as_posix(),))
configured = item.get("path")
if not isinstance(configured, str) or not configured.strip() or Path(configured).is_absolute():
fail(
"PB004",
f"workspace.folders[{index}].path must be a non-empty relative path",
sources=(path.as_posix(),),
)
resolved = (root / configured).resolve()
if not resolved.is_dir():
fail("PB004", f"Workspace folder does not exist: {configured}", sources=(path.as_posix(), configured))
if "name" not in item:
name = resolved.name
if not name:
fail(
"PB004",
f"workspace.folders[{index}].name could not be derived from path: {configured}",
sources=(path.as_posix(),),
)
else:
name = item.get("name")
if not isinstance(name, str) or not name.strip():
fail("PB004", f"workspace.folders[{index}].name must be non-empty", sources=(path.as_posix(),))
if name in names:
fail("PB004", f"Duplicate workspace folder name: {name}", sources=(path.as_posix(),))
key = os.path.normcase(str(resolved))
if key in resolved_keys:
fail("PB004", f"Duplicate resolved workspace folder path: {configured}", sources=(path.as_posix(),))
names.add(name)
resolved_keys.add(key)
folders.append(WorkspaceFolder(name, Path(configured).as_posix(), resolved))
return Workspace(path, folders)
def default_space_name(root: Path) -> str:
"""Use the Space directory name when init does not receive --name."""
return root.name
def init_relative_directory(root: Path, configured: str | None, option: str) -> tuple[str, Path] | None:
if configured is None:
return None
if not configured.strip() or Path(configured).is_absolute():
fail("PB001", f"{option} must be a non-empty relative path", sources=(root.as_posix(),))
normalized = Path(os.path.normpath(configured)).as_posix()
resolved = (root / normalized).resolve()
if not resolved.is_dir():
fail("PB005", f"{option} directory not found: {configured}", sources=(configured,))
return normalized, resolved
def init_space(
root: Path,
requested_name: str | None = None,
project_path: str | None = None,
shared_skills_path: str | None = None,
) -> tuple[Manifest, list[str], list[str]]:
"""Create missing required inputs and validate required inputs that already exist."""
detect_legacy(root)
manifest_path = root / "pipespace.json"
created: list[str] = []
validated: list[str] = []
if requested_name is not None and not NAME_RE.fullmatch(requested_name):
fail("PB002", "--name must match ^[a-z][a-z0-9-]*$", sources=(manifest_path.as_posix(),))
project = init_relative_directory(root, project_path, "--project")
shared_skills = init_relative_directory(root, shared_skills_path, "--shared-skills")
if project is not None and project[1] == root.resolve():
fail("PB004", "--project must not resolve to the PipeSpace root", sources=(project[0],))
if shared_skills is not None:
pipebuilder_skill = shared_skills[1] / "pipebuilder"
if not pipebuilder_skill.is_dir() or not (pipebuilder_skill / "SKILL.md").is_file():
fail(
"PB005",
f"--shared-skills does not contain pipebuilder/SKILL.md: {shared_skills[0]}",
sources=(shared_skills[0],),
)
provider = Provider(
"init-shared-skills",
shared_skills[1],
shared_skills[1],
shared_skills[0],
1,
tree_digest(shared_skills[1]),
)
read_skill(provider, pipebuilder_skill)
if manifest_path.exists() or manifest_path.is_symlink():
manifest = load_manifest(root)
if requested_name is not None and requested_name != manifest.name:
fail(
"PB002",
f"--name {requested_name!r} does not match existing manifest.name {manifest.name!r}",
sources=(manifest_path.as_posix(),),
)
if shared_skills is not None:
matching_providers = [
item
for item in manifest.providers
if item["type"] == "folder"
and Path(os.path.normpath(item["path"])).as_posix() == shared_skills[0]
and item.get("subdir", ".") == "."
]
if "pipebuilder" not in manifest.skills or not matching_providers:
fail(
"PB001",
"Existing pipespace.json does not match --shared-skills bootstrap configuration",
sources=(manifest_path.as_posix(),),
)
validated.append(manifest_path.name)
manifest_content: bytes | None = None
else:
name = requested_name or default_space_name(root)
if not NAME_RE.fullmatch(name):
fail(
"PB002",
f"Space directory name {name!r} is not a valid manifest.name; use --name",
sources=(root.as_posix(),),
action="Use --name with a lowercase kebab-case name, or rename the Space directory.",
)
manifest = Manifest(
manifest_path,
name,
None,
list(AGENTS),
["pipebuilder"] if shared_skills is not None else [],
[],
(
[{"type": "folder", "path": shared_skills[0], "subdir": "."}]
if shared_skills is not None
else []
),
DEFAULT_CHILD_SCAN_DEPTH,
)
manifest_content = json_bytes(
{
"schema": SPACE_SCHEMA,
"name": name,
"agents": list(AGENTS),
"skills": ["pipebuilder"] if shared_skills is not None else [],
"tags": [],