pantheon-opencode 1.4.3 → 1.5.0-beta.10

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.
Files changed (118) hide show
  1. package/.pantheon/code-mode/README.md +93 -0
  2. package/.pantheon/code-mode/checkpoint-session.py +7 -0
  3. package/.pantheon/code-mode/checkpoint-session.sh +11 -0
  4. package/.pantheon/code-mode/checkpoint_session.py +481 -0
  5. package/.pantheon/code-mode/compress-inline.py +450 -0
  6. package/.pantheon/code-mode/eval-llm-judge.py +255 -0
  7. package/.pantheon/code-mode/eval-monte-carlo.py +368 -0
  8. package/.pantheon/code-mode/eval-run.py +197 -0
  9. package/.pantheon/code-mode/eval-static.py +321 -0
  10. package/.pantheon/code-mode/example-sync.sh +5 -0
  11. package/.pantheon/code-mode/manifest.json +21 -0
  12. package/.pantheon/code-mode/session-end-save.py +186 -0
  13. package/.pantheon/code-mode/session-end-save.sh +18 -0
  14. package/.pantheon/code-mode/test-allowed.sh +5 -0
  15. package/.pantheon/code-mode/test-auto-continue-checkpoint.sh +179 -0
  16. package/.pantheon/code-mode/test-env.sh +7 -0
  17. package/.pantheon/code-mode/test-prlimit.sh +9 -0
  18. package/.pantheon/code-mode/test-timeout.sh +6 -0
  19. package/CHANGELOG.md +1026 -0
  20. package/README.md +292 -1080
  21. package/README.pt-BR.md +308 -0
  22. package/bin/pantheon-init.mjs +207 -31
  23. package/opencode.json +1 -0
  24. package/package.json +34 -14
  25. package/plugin.json +15 -0
  26. package/pyproject.toml +65 -0
  27. package/scripts/_pantheon_paths.py +48 -7
  28. package/scripts/ci-validate-yaml.py +7 -2
  29. package/scripts/code_mode_server.py +451 -44
  30. package/scripts/cost.mjs +30 -14
  31. package/scripts/doctor.mjs +306 -129
  32. package/scripts/generate-preset-docs.mjs +127 -66
  33. package/scripts/generate-prompts.sh +2 -2
  34. package/scripts/install/cli-ui.mjs +23 -10
  35. package/scripts/install/config-migration.mjs +399 -0
  36. package/scripts/install/health-check.mjs +3 -3
  37. package/scripts/install/model-picker.mjs +72 -23
  38. package/scripts/install/opencode-version.mjs +47 -0
  39. package/scripts/install/opencode.mjs +396 -121
  40. package/scripts/install/plugin.mjs +89 -49
  41. package/scripts/install/shared.mjs +55 -159
  42. package/scripts/install/strings.mjs +129 -0
  43. package/scripts/install-mcp.mjs +45 -232
  44. package/scripts/manifest-inventory.mjs +410 -0
  45. package/scripts/mcp_persistence_server.py +798 -60
  46. package/scripts/mcp_resources_server.py +144 -40
  47. package/scripts/memory_mcp_server.py +2 -2
  48. package/scripts/package-evidence.mjs +242 -0
  49. package/scripts/probe-context-rehydrate.mjs +240 -0
  50. package/scripts/probe-pantheon-cost.mjs +313 -0
  51. package/scripts/recover-zenodo-deposition.mjs +146 -0
  52. package/scripts/release-beta-version.mjs +56 -60
  53. package/scripts/sync-artifacts.mjs +169 -0
  54. package/scripts/sync-tui.mjs +135 -42
  55. package/scripts/test-opencode-v1-v2-sandbox.sh +862 -0
  56. package/scripts/uninstall.mjs +298 -954
  57. package/scripts/validate-zenodo-release.mjs +154 -0
  58. package/scripts/validation-policy.mjs +7 -7
  59. package/scripts/version-check.mjs +113 -108
  60. package/scripts/versioning.mjs +230 -86
  61. package/scripts/zenodo-artifact.mjs +21 -0
  62. package/scripts/zenodo-release-state.mjs +53 -0
  63. package/src/agents/mnemosyne.md +1 -1
  64. package/src/agents/zeus.md +27 -16
  65. package/src/mcp/_pantheon_paths.py +48 -7
  66. package/src/mcp/code_mode_server.py +451 -44
  67. package/src/mcp/eval_store.py +1 -1
  68. package/src/mcp/mcp_persistence_server.py +798 -60
  69. package/src/mcp/mcp_resources_server.py +144 -40
  70. package/src/mcp/pantheon_vision_server.py +1 -1
  71. package/src/mcp/toon_codec.py +491 -0
  72. package/src/pantheon/auto-wake.ts +1 -5
  73. package/src/pantheon/background-job-board.ts +110 -2
  74. package/src/pantheon/compaction-handoff.ts +304 -0
  75. package/src/pantheon/cost-command.ts +356 -69
  76. package/src/pantheon/delegate-manager.ts +766 -0
  77. package/src/pantheon/delegation-classifier.ts +307 -0
  78. package/src/pantheon/delegation-enforce.ts +13 -12
  79. package/src/pantheon/delegation-finalize.ts +406 -0
  80. package/src/pantheon/delegation-notify.ts +212 -0
  81. package/src/pantheon/delegation-toast.ts +73 -0
  82. package/src/pantheon/delegation.ts +1337 -0
  83. package/src/pantheon/file-persistence-salvage.ts +64 -0
  84. package/src/pantheon/file-persistence.ts +194 -45
  85. package/src/pantheon/goal-loop.ts +2 -2
  86. package/src/pantheon/goal-store.ts +1 -1
  87. package/src/pantheon/hashline/tool.ts +2 -2
  88. package/src/pantheon/model-command.ts +2 -1
  89. package/src/pantheon/native-probe.ts +234 -0
  90. package/src/pantheon/native-task-status.ts +139 -0
  91. package/src/pantheon/permission-eval.ts +284 -0
  92. package/src/pantheon/provider-capabilities.ts +221 -0
  93. package/src/pantheon/provider-stream-tracker.ts +182 -0
  94. package/src/pantheon/shared-board.ts +37 -0
  95. package/src/pantheon/step-cap.ts +110 -0
  96. package/src/pantheon/task-result-guard.ts +107 -0
  97. package/src/pantheon/token-opt.ts +689 -0
  98. package/src/pantheon/tool-ceiling.ts +159 -0
  99. package/src/pantheon/toon-codec.ts +481 -0
  100. package/src/pantheon/tui-version-check.ts +1 -3
  101. package/src/pantheon/v2-bridge.ts +129 -0
  102. package/src/pantheon/v2-events.ts +148 -0
  103. package/src/pantheon/v2-hooks.ts +287 -0
  104. package/src/pantheon/v2-tool-definitions.ts +331 -0
  105. package/src/pantheon/zeus-delegate-with-retry.ts +406 -0
  106. package/src/plugin-v2/index.ts +21 -0
  107. package/src/plugin-v2.ts +824 -0
  108. package/src/plugin.ts +261 -51
  109. package/src/plugins/pantheon-hooks.ts +51 -0
  110. package/src/plugins/tui/dist/tui.d.ts +116 -24
  111. package/src/plugins/tui/dist/tui.d.ts.map +1 -1
  112. package/src/plugins/tui/dist/tui.js +416 -149
  113. package/src/plugins/tui/dist/tui.tsx +456 -87
  114. package/src/plugins/tui/package-lock.json +51 -51
  115. package/src/plugins/tui/package.json +7 -7
  116. package/src/plugins/tui/src/index.tsx +462 -95
  117. package/src/skills/README.md +0 -2
  118. package/src/pantheon/tool-context.ts +0 -41
@@ -17,7 +17,7 @@ from pathlib import Path
17
17
  from typing import Any
18
18
 
19
19
  import yaml
20
- from _pantheon_paths import pantheon_home, pantheon_project
20
+ from _pantheon_paths import has_symlink_component, pantheon_home, pantheon_project
21
21
  from eval_store import get_latest_eval, list_evals
22
22
  from mcp.server.fastmcp import FastMCP
23
23
 
@@ -25,6 +25,88 @@ from mcp.server.fastmcp import FastMCP
25
25
  _PANTHEON_HOME: Path = pantheon_home()
26
26
  _PANTHEON_PROJECT: Path | None = pantheon_project()
27
27
 
28
+
29
+ def _within(path: Path, parent: Path) -> bool:
30
+ """Return whether ``path`` is contained by ``parent`` after resolution."""
31
+ try:
32
+ path.relative_to(parent)
33
+ except ValueError:
34
+ return False
35
+ return True
36
+
37
+
38
+ def _safe_root(root: Path, parent: Path) -> Path | None:
39
+ """Return a physical resource root only when its layout is trusted.
40
+
41
+ Local ``.opencode`` and ``.pantheon`` directories are trust boundaries:
42
+ accepting either as a symlink would make all resources below it
43
+ untrusted, even when the link happens to point inside the project.
44
+ """
45
+ if parent.is_symlink() or has_symlink_component(parent):
46
+ return None
47
+ # Keep the project root lexical until this trust-boundary check. This
48
+ # rejects PANTHEON_PROJECT/cwd symlinks instead of resolving them away.
49
+ if parent.name in {".opencode", ".pantheon"} and parent.parent.is_symlink():
50
+ return None
51
+ if root.is_symlink():
52
+ return None
53
+ if not root.exists() or not root.is_dir():
54
+ return None
55
+ parent_resolved = parent.resolve()
56
+ resolved = root.resolve()
57
+ if parent.name in {".opencode", ".pantheon"} and not _within(
58
+ parent_resolved, parent.parent.resolve()
59
+ ):
60
+ return None
61
+ return resolved if _within(resolved, parent_resolved) else None
62
+
63
+
64
+ def _resource_root(name: str) -> Path | None:
65
+ """Choose a project-local root before the global installation root.
66
+
67
+ A present but unsafe project root is ignored rather than followed; this
68
+ preserves the global fallback while preventing symlink escapes.
69
+ """
70
+ candidates: list[tuple[Path, Path]] = []
71
+ if _PANTHEON_PROJECT is not None:
72
+ if name in {"agents", "skills"}:
73
+ local = _PANTHEON_PROJECT / ".opencode"
74
+ candidates.append((local / name, local))
75
+ elif name in {"deepwork", "memory-bank"}:
76
+ local = _PANTHEON_PROJECT / ".pantheon"
77
+ candidates.append((local / name, local))
78
+ candidates.append((_PANTHEON_HOME / name, _PANTHEON_HOME))
79
+ for root, parent in candidates:
80
+ safe = _safe_root(root, parent)
81
+ if safe is not None:
82
+ return safe
83
+ return None
84
+
85
+
86
+ def _resource_roots(name: str) -> list[Path]:
87
+ """Return safe resource roots in local-first precedence order."""
88
+ roots: list[Path] = []
89
+ if _PANTHEON_PROJECT is not None:
90
+ base_name = ".opencode" if name in {"agents", "skills"} else ".pantheon"
91
+ base = _PANTHEON_PROJECT / base_name
92
+ local = _safe_root(base / name, base)
93
+ if local is not None:
94
+ roots.append(local)
95
+ global_root = _safe_root(_PANTHEON_HOME / name, _PANTHEON_HOME)
96
+ if global_root is not None:
97
+ roots.append(global_root)
98
+ return roots
99
+
100
+
101
+ def _safe_child(root: Path, relative: str) -> Path | None:
102
+ """Resolve a child while rejecting every lexical symlink component."""
103
+ candidate = root / relative
104
+ if has_symlink_component(candidate):
105
+ return None
106
+ resolved = candidate.resolve()
107
+ return resolved if _within(resolved, root.resolve()) else None
108
+
109
+
28
110
  # ── FastMCP App ───────────────────────────────────────────────────────────────
29
111
  mcp = FastMCP(
30
112
  "Pantheon Resources",
@@ -67,17 +149,27 @@ def _get_role_from_frontmatter(frontmatter: dict[str, Any]) -> str:
67
149
  )
68
150
  async def list_agents() -> str:
69
151
  """Return a markdown list of all agents with their roles."""
70
- agents_dir = _PANTHEON_HOME / "agents"
71
- if not agents_dir.is_dir():
152
+ agents_dirs = _resource_roots("agents")
153
+ if not agents_dirs:
72
154
  return "Agents directory not found."
73
155
 
74
156
  agents: list[str] = []
75
- for f in sorted(agents_dir.iterdir()):
76
- if f.suffix == ".md" and f.stem.lower() != "readme":
77
- frontmatter = _parse_yaml_frontmatter(f)
78
- name = frontmatter.get("name", f.stem)
79
- role = _get_role_from_frontmatter(frontmatter)
80
- agents.append(f"- **{name}** — {role}")
157
+ seen: set[str] = set()
158
+ for agents_dir in agents_dirs:
159
+ for entry in sorted(agents_dir.iterdir()):
160
+ f = _safe_child(agents_dir, entry.name)
161
+ if (
162
+ f is not None
163
+ and f.is_file()
164
+ and f.suffix == ".md"
165
+ and f.stem.lower() != "readme"
166
+ and f.name not in seen
167
+ ):
168
+ seen.add(f.name)
169
+ frontmatter = _parse_yaml_frontmatter(f)
170
+ name = frontmatter.get("name", f.stem)
171
+ role = _get_role_from_frontmatter(frontmatter)
172
+ agents.append(f"- **{name}** — {role}")
81
173
 
82
174
  return "\n".join(agents) if agents else "No agents found."
83
175
 
@@ -88,19 +180,23 @@ async def list_agents() -> str:
88
180
  )
89
181
  async def list_skills() -> str:
90
182
  """Return a markdown list of all skills with descriptions."""
91
- skills_dir = _PANTHEON_HOME / "skills"
92
- if not skills_dir.is_dir():
183
+ skills_dirs = _resource_roots("skills")
184
+ if not skills_dirs:
93
185
  return "Skills directory not found."
94
186
 
95
187
  skills: list[str] = []
96
- for f in sorted(skills_dir.iterdir()):
97
- if f.is_dir():
98
- skill_file = f / "SKILL.md"
99
- if skill_file.exists():
100
- frontmatter = _parse_yaml_frontmatter(skill_file)
101
- name = frontmatter.get("name", f.name)
102
- desc = frontmatter.get("description", "No description")
103
- skills.append(f"- **{name}** — {desc}")
188
+ seen: set[str] = set()
189
+ for skills_dir in skills_dirs:
190
+ for entry in sorted(skills_dir.iterdir()):
191
+ f = _safe_child(skills_dir, entry.name)
192
+ if f is not None and f.is_dir() and f.name not in seen:
193
+ skill_file = _safe_child(f, "SKILL.md")
194
+ if skill_file is not None and skill_file.is_file():
195
+ seen.add(f.name)
196
+ frontmatter = _parse_yaml_frontmatter(skill_file)
197
+ name = frontmatter.get("name", f.name)
198
+ desc = frontmatter.get("description", "No description")
199
+ skills.append(f"- **{name}** — {desc}")
104
200
 
105
201
  return "\n".join(skills) if skills else "No skills found."
106
202
 
@@ -111,10 +207,10 @@ async def list_skills() -> str:
111
207
  )
112
208
  async def get_routing() -> str:
113
209
  """Return the full content of routing.yml."""
114
- routing_file = _PANTHEON_HOME / "routing.yml"
115
- if not routing_file.exists() and _PANTHEON_PROJECT:
116
- routing_file = _PANTHEON_PROJECT / "src" / "routing.yml"
117
- if not routing_file.exists():
210
+ routing_file = _safe_child(_PANTHEON_HOME, "routing.yml")
211
+ if routing_file is None and _PANTHEON_PROJECT:
212
+ routing_file = _safe_child(_PANTHEON_PROJECT / "src", "routing.yml")
213
+ if routing_file is None or not routing_file.exists():
118
214
  return "routing.yml not found."
119
215
  return routing_file.read_text(encoding="utf-8")
120
216
 
@@ -128,11 +224,17 @@ async def get_routing() -> str:
128
224
  )
129
225
  async def get_agent(agent_name: str) -> str:
130
226
  """Return the full content of an agent file, case-insensitively."""
131
- agents_dir = _PANTHEON_HOME / "agents"
132
227
  name_lower = agent_name.lower()
133
- for f in agents_dir.iterdir():
134
- if f.suffix == ".md" and f.stem.lower() == name_lower:
135
- return f.read_text(encoding="utf-8")
228
+ for agents_dir in _resource_roots("agents"):
229
+ for entry in agents_dir.iterdir():
230
+ f = _safe_child(agents_dir, entry.name)
231
+ if (
232
+ f is not None
233
+ and f.is_file()
234
+ and f.suffix == ".md"
235
+ and f.stem.lower() == name_lower
236
+ ):
237
+ return f.read_text(encoding="utf-8")
136
238
  return f"Agent '{agent_name}' not found."
137
239
 
138
240
 
@@ -142,10 +244,11 @@ async def get_agent(agent_name: str) -> str:
142
244
  )
143
245
  async def get_deepwork_plan(slug: str) -> str:
144
246
  """Return PLAN.md content for a deepwork slug."""
145
- if _PANTHEON_PROJECT is None:
247
+ deepwork_dir = _resource_root("deepwork")
248
+ if deepwork_dir is None:
146
249
  return f"Deepwork '{slug}' not found. (PANTHEON_PROJECT not set)"
147
- plan_file = _PANTHEON_PROJECT / ".pantheon" / "deepwork" / slug / "PLAN.md"
148
- if not plan_file.exists():
250
+ plan_file = _safe_child(deepwork_dir, f"{slug}/PLAN.md")
251
+ if plan_file is None or not plan_file.is_file():
149
252
  return f"Deepwork '{slug}' not found."
150
253
  return plan_file.read_text(encoding="utf-8")
151
254
 
@@ -157,10 +260,11 @@ async def get_deepwork_plan(slug: str) -> str:
157
260
  )
158
261
  async def get_deepwork_status(slug: str) -> str:
159
262
  """Return STATUS.md content for a deepwork slug, or a default message."""
160
- if _PANTHEON_PROJECT is None:
263
+ deepwork_dir = _resource_root("deepwork")
264
+ if deepwork_dir is None:
161
265
  return "STATUS.md not found. (PANTHEON_PROJECT not set)"
162
- status_file = _PANTHEON_PROJECT / ".pantheon" / "deepwork" / slug / "STATUS.md"
163
- if not status_file.exists():
266
+ status_file = _safe_child(deepwork_dir, f"{slug}/STATUS.md")
267
+ if status_file is None or not status_file.is_file():
164
268
  return "STATUS.md not found. Current state: IN PROGRESS"
165
269
  return status_file.read_text(encoding="utf-8")
166
270
 
@@ -171,8 +275,9 @@ async def get_deepwork_status(slug: str) -> str:
171
275
  )
172
276
  async def get_skill(name: str) -> str:
173
277
  """Return SKILL.md content for a skill directory."""
174
- skill_file = _PANTHEON_HOME / "skills" / name / "SKILL.md"
175
- if not skill_file.exists():
278
+ skills_dir = _resource_root("skills")
279
+ skill_file = _safe_child(skills_dir, f"{name}/SKILL.md") if skills_dir else None
280
+ if skill_file is None or not skill_file.is_file():
176
281
  return f"Skill '{name}' not found."
177
282
  return skill_file.read_text(encoding="utf-8")
178
283
 
@@ -188,12 +293,11 @@ async def get_memory_bank(path: str) -> str:
188
293
  Security: resolves absolute path and verifies it stays within
189
294
  .pantheon/memory-bank/ to prevent directory traversal attacks.
190
295
  """
191
- if _PANTHEON_PROJECT is None:
296
+ memory_dir = _resource_root("memory-bank")
297
+ if memory_dir is None:
192
298
  return "Memory bank not available. (PANTHEON_PROJECT not set)"
193
- resolved = (_PANTHEON_PROJECT / ".pantheon" / "memory-bank" / path).resolve()
194
- mb_dir = (_PANTHEON_PROJECT / ".pantheon" / "memory-bank").resolve()
195
-
196
- if not str(resolved).startswith(str(mb_dir)):
299
+ resolved = _safe_child(memory_dir, path)
300
+ if resolved is None:
197
301
  return "Path traversal blocked: access denied."
198
302
 
199
303
  if not resolved.exists() or not resolved.is_file():
@@ -25,7 +25,7 @@ import json
25
25
  import os
26
26
  import sqlite3
27
27
  import time
28
- from datetime import datetime, timezone
28
+ from datetime import UTC, datetime
29
29
  from pathlib import Path
30
30
  from typing import Any
31
31
 
@@ -198,7 +198,7 @@ def _parse_iso_ts(value: str) -> float:
198
198
  """
199
199
  dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
200
200
  if dt.tzinfo is None:
201
- dt = dt.replace(tzinfo=timezone.utc)
201
+ dt = dt.replace(tzinfo=UTC)
202
202
  return dt.timestamp()
203
203
 
204
204
 
@@ -0,0 +1,242 @@
1
+ #!/usr/bin/env node
2
+ /** Build and verify the single immutable npm package evidence artifact. */
3
+
4
+ import { execFileSync } from 'node:child_process'
5
+ import { createHash } from 'node:crypto'
6
+ import {
7
+ existsSync,
8
+ lstatSync,
9
+ mkdirSync,
10
+ mkdtempSync,
11
+ readdirSync,
12
+ readFileSync,
13
+ realpathSync,
14
+ rmSync,
15
+ writeFileSync,
16
+ } from 'node:fs'
17
+ import { tmpdir } from 'node:os'
18
+ import { isAbsolute, join } from 'node:path'
19
+ import { validateInventory } from './manifest-inventory.mjs'
20
+
21
+ const CI_ARGS = ['ci', '--ignore-scripts', '--omit=dev', '--no-audit', '--no-fund']
22
+ const REQUIRED_PAYLOAD = [
23
+ 'package/package.json',
24
+ 'package/plugin.json',
25
+ 'package/pyproject.toml',
26
+ 'package/src/plugins/tui/package.json',
27
+ 'package/src/plugins/tui/package-lock.json',
28
+ 'package/src/plugin.ts',
29
+ 'package/src/plugin-v2.ts',
30
+ 'package/src/pantheon/v2-bridge.ts',
31
+ 'package/src/plugins/tui/dist/tui.js',
32
+ 'package/src/plugins/tui/dist/server.js',
33
+ 'package/bin/pantheon-init.mjs',
34
+ 'package/scripts/doctor.mjs',
35
+ 'package/.pantheon/code-mode/compress-inline.py',
36
+ ]
37
+
38
+ function fail(message) {
39
+ throw new Error(message)
40
+ }
41
+
42
+ function resolveTargetSha(root, supplied) {
43
+ const raw =
44
+ supplied ?? execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8' })
45
+ const sha = String(raw).trim().toLowerCase()
46
+ if (!/^[0-9a-f]{40}$/.test(sha))
47
+ fail('target SHA must be a full lowercase 40-character hexadecimal SHA')
48
+ return sha
49
+ }
50
+
51
+ function createOutputDirectory(outputDir) {
52
+ const directory = outputDir ?? mkdtempSync(join(tmpdir(), 'pantheon-package-evidence-'))
53
+ mkdirSync(directory, { recursive: true })
54
+ if (readdirSync(directory).length !== 0) fail(`output directory must be empty: ${directory}`)
55
+ return { directory }
56
+ }
57
+
58
+ function packOnce(root, outputDir) {
59
+ const raw = execFileSync(
60
+ 'npm',
61
+ ['pack', '--ignore-scripts', '--json', '--pack-destination', outputDir],
62
+ { cwd: root, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 },
63
+ )
64
+ let result
65
+ try {
66
+ result = JSON.parse(raw)
67
+ } catch (error) {
68
+ fail(`npm pack returned malformed JSON: ${error.message}`)
69
+ }
70
+ if (!Array.isArray(result) || result.length !== 1 || typeof result[0]?.filename !== 'string') {
71
+ fail('npm pack must produce exactly one JSON result')
72
+ }
73
+ const tgzFiles = readdirSync(outputDir).filter((name) => name.endsWith('.tgz'))
74
+ if (tgzFiles.length !== 1)
75
+ fail(`package evidence requires exactly one .tgz, found ${tgzFiles.length}`)
76
+ if (tgzFiles[0] !== result[0].filename)
77
+ fail('npm pack result does not identify the sole .tgz artifact')
78
+ return join(outputDir, tgzFiles[0])
79
+ }
80
+
81
+ function validateArchiveEntries(tarball) {
82
+ const listing = execFileSync('tar', ['-tzf', tarball], { encoding: 'utf8' })
83
+ const entries = listing.split('\n').filter(Boolean)
84
+ if (entries.length === 0) fail('package tarball is empty')
85
+ for (const entry of entries) {
86
+ const normalized = entry.replace(/\/$/, '')
87
+ const parts = normalized.split('/')
88
+ if (
89
+ isAbsolute(normalized) ||
90
+ normalized.includes('\\') ||
91
+ parts.includes('..') ||
92
+ (!normalized.startsWith('package/') && normalized !== 'package')
93
+ ) {
94
+ fail(`unsafe package archive entry: ${entry}`)
95
+ }
96
+ }
97
+ const detailed = execFileSync('tar', ['-tvzf', tarball], { encoding: 'utf8' })
98
+ for (const line of detailed.split('\n').filter(Boolean)) {
99
+ if (/^[lh]/i.test(line)) fail(`package archive contains a link entry: ${line}`)
100
+ }
101
+ return new Set(entries)
102
+ }
103
+
104
+ function extractSafely(tarball, workDir) {
105
+ const extractionRoot = join(workDir, 'extract')
106
+ mkdirSync(extractionRoot)
107
+ validateArchiveEntries(tarball)
108
+ execFileSync(
109
+ 'tar',
110
+ ['-xzf', tarball, '--directory', extractionRoot, '--no-same-owner', '--no-same-permissions'],
111
+ { encoding: 'utf8' },
112
+ )
113
+ const realRoot = realpathSync(extractionRoot)
114
+ const walk = (current) => {
115
+ const stat = lstatSync(current)
116
+ if (stat.isSymbolicLink()) fail(`package archive extraction contains a symlink: ${current}`)
117
+ const resolved = realpathSync(current)
118
+ if (resolved !== realRoot && !resolved.startsWith(`${realRoot}/`)) {
119
+ fail(`package archive extraction escaped its temporary directory: ${current}`)
120
+ }
121
+ if (stat.isDirectory()) for (const name of readdirSync(current)) walk(join(current, name))
122
+ }
123
+ walk(extractionRoot)
124
+ return join(extractionRoot, 'package')
125
+ }
126
+
127
+ function validatePayload(packageRoot, inventory) {
128
+ for (const relativePath of REQUIRED_PAYLOAD) {
129
+ const path = join(packageRoot, relativePath.replace(/^package\//, ''))
130
+ if (!existsSync(path) || !lstatSync(path).isFile())
131
+ fail(`required package payload is missing: ${relativePath}`)
132
+ }
133
+ for (const document of inventory.documents) {
134
+ const { entry, path: sourcePath } = document
135
+ const packagedPath = join(packageRoot, entry.file)
136
+ if (entry.role === 'lock' && entry.file === 'package-lock.json' && !existsSync(packagedPath)) {
137
+ // npm-packlist excludes the package root lockfile by policy. It remains
138
+ // validated below as source evidence, but is not fabricated in the tgz.
139
+ continue
140
+ }
141
+ if (!existsSync(packagedPath) || !lstatSync(packagedPath).isFile())
142
+ fail(`versioned package payload is missing: package/${entry.file}`)
143
+ if (sha256(sourcePath) !== sha256(packagedPath))
144
+ fail(`published package payload differs from source: ${entry.file}`)
145
+ }
146
+ }
147
+
148
+ function collectLockfileEvidence(inventory, entries, packageRoot) {
149
+ return inventory.documents
150
+ .filter(({ entry }) => entry.role === 'lock')
151
+ .map(({ entry, data, path: sourcePath }) => {
152
+ const archivePath = `package/${entry.file}`
153
+ const packagedPath = join(packageRoot, entry.file)
154
+ const publishedInTarball = entries.has(archivePath)
155
+ return {
156
+ file: entry.file,
157
+ sourceSha256: sha256(sourcePath),
158
+ publishedSha256: publishedInTarball ? sha256(packagedPath) : null,
159
+ sourceName: data.name,
160
+ sourceVersion: data.version,
161
+ lockfileVersion: data.lockfileVersion,
162
+ parity: 'validated-against-manifest',
163
+ publishedInTarball,
164
+ }
165
+ })
166
+ }
167
+
168
+ function installProductionDependencies(root) {
169
+ // The root package-lock.json is source evidence only: npm-packlist omits it
170
+ // from the root of an npm package, so root ci must validate the source tree.
171
+ execFileSync('npm', CI_ARGS, { cwd: root, stdio: 'inherit' })
172
+ execFileSync('npm', CI_ARGS, {
173
+ cwd: join(root, 'src', 'plugins', 'tui'),
174
+ stdio: 'inherit',
175
+ })
176
+ }
177
+
178
+ function sha256(path) {
179
+ return createHash('sha256').update(readFileSync(path)).digest('hex')
180
+ }
181
+
182
+ export function createPackageEvidence(root, { outputDir, targetSha } = {}) {
183
+ const inventory = validateInventory(root)
184
+ const sha = resolveTargetSha(root, targetSha)
185
+ const output = createOutputDirectory(outputDir)
186
+ let workDir
187
+ try {
188
+ const tarball = packOnce(root, output.directory)
189
+ workDir = mkdtempSync(join(tmpdir(), 'pantheon-package-evidence-check-'))
190
+ const entries = validateArchiveEntries(tarball)
191
+ const packageRoot = extractSafely(tarball, workDir)
192
+ validatePayload(packageRoot, inventory)
193
+ installProductionDependencies(root)
194
+ const digest = sha256(tarball)
195
+ if (!/^[0-9a-f]{64}$/.test(digest)) fail('tarball SHA-256 is not lowercase 64-hex')
196
+ const metadata = {
197
+ version: inventory.sourceVersion,
198
+ targetSha: sha,
199
+ tarballSha256: digest,
200
+ tarball: tarball.split('/').at(-1),
201
+ lockfilePolicy: {
202
+ rootPackageLockfile: entries.has('package/package-lock.json')
203
+ ? 'published-by-npm-pack'
204
+ : 'omitted-by-npm-pack',
205
+ note: entries.has('package/package-lock.json')
206
+ ? 'npm pack published the root package-lock.json; lockfile parity is validated and recorded as source evidence, while tarball validation covers only the payload npm pack publishes.'
207
+ : 'npm pack omits the package root package-lock.json by policy; lockfile parity is validated and recorded as source evidence, while tarball validation covers only the payload npm pack publishes.',
208
+ },
209
+ lockfileEvidence: collectLockfileEvidence(inventory, entries, packageRoot),
210
+ }
211
+ writeFileSync(join(output.directory, 'metadata.json'), `${JSON.stringify(metadata, null, 2)}\n`)
212
+ writeFileSync(join(output.directory, 'version'), `${metadata.version}\n`)
213
+ writeFileSync(join(output.directory, 'target-sha'), `${metadata.targetSha}\n`)
214
+ writeFileSync(join(output.directory, 'tarball-sha256'), `${metadata.tarballSha256}\n`)
215
+ return { ...metadata, outputDir: output.directory, tarball }
216
+ } catch (error) {
217
+ rmSync(output.directory, { recursive: true, force: true })
218
+ throw error
219
+ } finally {
220
+ if (workDir) rmSync(workDir, { recursive: true, force: true })
221
+ }
222
+ }
223
+
224
+ function parseOptions(args) {
225
+ const options = {}
226
+ for (const arg of args) {
227
+ const match = /^--(output-dir|target-sha)=(.*)$/.exec(arg)
228
+ if (!match) fail(`unsupported package evidence option: ${arg}`)
229
+ options[match[1] === 'output-dir' ? 'outputDir' : 'targetSha'] = match[2]
230
+ }
231
+ return options
232
+ }
233
+
234
+ if (process.argv[1]?.endsWith('package-evidence.mjs')) {
235
+ try {
236
+ const evidence = createPackageEvidence(process.cwd(), parseOptions(process.argv.slice(2)))
237
+ console.log(JSON.stringify(evidence))
238
+ } catch (error) {
239
+ console.error(`package-evidence: ${error.message}`)
240
+ process.exit(1)
241
+ }
242
+ }