Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .github/ci-paths.toml
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,11 @@ patterns = [
]
suites = ["tests", "dify", "hermes", "dsh", "pi", "opencode", "openclaw", "zcode", "kimi"]

# The TypeScript lifecycle source is copied into these plugins; ZCode and Cindy run the Pi and DSH plugins.
[shared.lifecycle_typescript]
patterns = ["integrations/lifecycle/**", "scripts/generate_integration_lifecycle.py"]
suites = ["tests", "dsh", "cindy", "pi", "opencode", "openclaw", "zcode"]

# Shared Python changes still exercise all runtime consumers. Diagnostic source
# capture and lock probes have their own inputs rather than joining every build.
[shared.runtime]
Expand Down
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ Use [REVIEW.md](REVIEW.md) when reviewing changes.

## Generated Integration Helpers

`src/powercontext_integration_lifecycle/` is the source of the helpers that copy-installed Python plugins ship. The helpers may import only the standard library and must run on Python 3.9, because Claude Code runs its hooks with the `python3` on `PATH`. Their copies under `integrations/` are checked in; do not edit them by hand. After changing the source, run `make integration-lifecycle`; `make check` rejects a stale copy.
`src/powercontext_integration_lifecycle/` is the source of the helpers that copy-installed Python plugins ship. The helpers may import only the standard library and must run on Python 3.9, because Claude Code runs its hooks with the `python3` on `PATH`. `integrations/lifecycle/` is the source of the TypeScript helpers that the DSH, OpenClaw, OpenCode, and Pi plugins ship. They may import only Node.js built-in modules, because the plugins do not share their dependencies. Their copies under `integrations/` are checked in; do not edit them by hand. After changing the source, run `make integration-lifecycle`; `make check` rejects a stale copy.

## Testing Guidelines

Expand Down
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ integration-guidance-check: ## Check native Skill copies without modifying files
@uv run python scripts/integration_guidance_skills.py --check

.PHONY: integration-lifecycle integration-lifecycle-check
integration-lifecycle: ## Write the lifecycle helper copies that copy-installed Python plugins ship.
integration-lifecycle: ## Write the lifecycle helper copies that Python and TypeScript plugins ship.
@uv run python scripts/generate_integration_lifecycle.py

integration-lifecycle-check: ## Reject a lifecycle helper copy that has drifted from its source.
Expand Down
1 change: 1 addition & 0 deletions integrations/capabilities.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ schema_version = 2
cindy = "Scoped Ghost recall and will-user-message hooks plus native MCP under evaluation with Cindy 0.1.115; opt-in Codex app-server acceptance does not qualify Electron installation, credential UI, or complete Desktop harness routing. See integrations/cindy/README.md."
agent-plugin = "Portable Agent Plugin client package, not a qualified host or framework adapter; host support is tracked by the individual host declarations. See integrations/agent-plugin/README.md."
opendal = "Independently deployed evaluation Connector worker, not a complete standard Source integration or host adapter. See integrations/opendal/README.md."
lifecycle = "Source of the TypeScript lifecycle helpers that scripts/generate_integration_lifecycle.py copies into the TypeScript host plugins, not a host or framework adapter."

# These kinds have a different documentation contract; declared evidence is still checked.
[documentation_waivers]
Expand Down
3 changes: 3 additions & 0 deletions integrations/dsh/plugins/powercontext/src/transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
* limitations under the License.
*/

// Generated from integrations/lifecycle/transport.ts; do not edit.
// Edit the source and run `make integration-lifecycle` instead.

import { readFileSync } from 'node:fs'
import { homedir } from 'node:os'
import { join } from 'node:path'
Expand Down
143 changes: 143 additions & 0 deletions integrations/lifecycle/transport.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
/*
* Copyright (c) 2026 OceanBase.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { readFileSync } from 'node:fs'
import { homedir } from 'node:os'
import { join } from 'node:path'

// Each host is an independently distributed package; keep the shared client config
// contract and policy aligned with powercontext.client.transport_policy and powercontext.transport.
type SavedClient = { server_url?: string; allow_insecure_http?: boolean }

function optionalText(value: unknown): string | undefined {
return typeof value === 'string' ? value.trim() || undefined : undefined
}

function optionalBoolean(value: unknown, name: string): boolean | undefined {
if (value === undefined) return undefined
if (typeof value !== 'boolean') throw new Error(`${name} must be a boolean`)
return value
}

function environmentBoolean(env: NodeJS.ProcessEnv, name: string): boolean | undefined {
if (env[name] === undefined) return undefined
const value = env[name]!.trim().toLowerCase()
if (['true', '1', 'yes', 'on'].includes(value)) return true
if (['false', '0', 'no', 'off'].includes(value)) return false
throw new Error(`${name} must be a boolean (true/false, 1/0, yes/no, on/off)`)
}

function readSavedClient(host: string, env: NodeJS.ProcessEnv): SavedClient {
const home = optionalText(env.HOME) ?? homedir()
const configuredPath = optionalText(env.POWERCONTEXT_CLIENT_CONFIG_FILE)
const path = configuredPath?.startsWith('~/')
? join(home, configuredPath.slice(2))
: configuredPath ?? join(home, '.config', 'powercontext', 'clients.json')
let contents: string
try {
contents = readFileSync(path, 'utf8')
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return {}
throw new Error('Unable to read PowerContext client configuration', { cause: error })
}
let document: unknown
try {
document = JSON.parse(contents)
} catch {
throw new Error('PowerContext client configuration must be valid JSON')
}
if (!document || typeof document !== 'object' || Array.isArray(document)
|| (document as { version?: unknown }).version !== 1) {
throw new Error('PowerContext client configuration must have version 1')
}
const hosts = (document as { hosts?: unknown }).hosts
if (!hosts || typeof hosts !== 'object' || Array.isArray(hosts)) {
throw new Error('PowerContext client configuration hosts must be an object')
}
const value = (hosts as Record<string, unknown>)[host]
if (value === undefined) return {}
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new Error('PowerContext saved host configuration must be an object')
}
const entry = value as Record<string, unknown>
if (entry.server_url !== undefined && !optionalText(entry.server_url)) {
throw new Error('PowerContext saved server_url must be a non-empty string')
}
return {
server_url: optionalText(entry.server_url),
allow_insecure_http: optionalBoolean(entry.allow_insecure_http, 'allow_insecure_http'),
}
}

export function normalizeServerUrl(value: string, allowInsecureHttp = false, name = 'PowerContext server URL'): string {
optionalBoolean(allowInsecureHttp, 'allowInsecureHttp')
let url: URL
try {
url = new URL(value)
} catch {
throw new Error(`${name} must be a valid HTTP(S) URL`)
}
if (!['http:', 'https:'].includes(url.protocol)) {
throw new Error(`${name} must use HTTP or HTTPS`)
}
if (url.username || url.password || url.search || url.hash) {
throw new Error(`${name} must not contain credentials, a query, or a fragment`)
}
const host = url.hostname.toLowerCase().replace(/^\[/, '').replace(/\]$/, '')
const octets = host.split('.')
const loopback = host === 'localhost' || host === '::1'
|| (octets.length === 4 && octets[0] === '127'
&& octets.every((octet) => /^\d{1,3}$/.test(octet) && Number(octet) <= 255))
if (url.protocol === 'http:' && !loopback && !allowInsecureHttp) {
throw new Error(`${name} must use HTTPS outside loopback; explicitly enable allow_insecure_http to permit plaintext HTTP`)
}
return url.toString().replace(/\/+$/, '').replace(/\/mcp$/, '').replace(/\/+$/, '')
}

export function resolveTransport(
host: string,
env: NodeJS.ProcessEnv,
nativeUrl?: unknown,
nativeConsent?: unknown,
defaultUrl?: string,
): { baseUrl: string | undefined; allowInsecureHttp: boolean; source: 'environment' | 'plugin' | 'saved' | 'default' } {
const prefix = `POWERCONTEXT_${host.toUpperCase()}`
const saved = readSavedClient(host, env)
const environmentUrl = optionalText(env[`${prefix}_BASE_URL`])
?? optionalText(env[`${prefix}_SERVER_URL`])
?? optionalText(env[`${prefix}_ENDPOINT`])
?? optionalText(env.POWERCONTEXT_CLIENT_SERVER_URL)
const pluginUrl = optionalText(nativeUrl)
const selectedUrl = environmentUrl ?? pluginUrl ?? saved.server_url ?? defaultUrl
const normalized = selectedUrl === undefined ? undefined : normalizeServerUrl(selectedUrl, true, `${prefix}_BASE_URL`)
const savedUrl = saved.server_url === undefined ? undefined : normalizeServerUrl(saved.server_url, true)
const hostConsent = environmentBoolean(env, `${prefix}_ALLOW_INSECURE_HTTP`)
const commonConsent = environmentBoolean(env, 'POWERCONTEXT_CLIENT_ALLOW_INSECURE_HTTP')
const pluginConsent = optionalBoolean(nativeConsent, 'allowInsecureHttp')
const nativeEndpoint = pluginUrl === undefined ? undefined : normalizeServerUrl(pluginUrl, true)
// Persisted native consent belongs to its endpoint, just like setup-saved consent.
// An explicit refusal remains effective even when the endpoint is overridden.
const matchingNativeConsent = pluginConsent === false
? false
: normalized !== undefined && normalized === nativeEndpoint ? pluginConsent : undefined
const allowInsecureHttp = hostConsent ?? commonConsent ?? matchingNativeConsent
?? (normalized !== undefined && normalized === savedUrl ? saved.allow_insecure_http : undefined) ?? false
return {
baseUrl: normalized === undefined ? undefined : normalizeServerUrl(normalized, allowInsecureHttp, `${prefix}_BASE_URL`),
allowInsecureHttp,
source: environmentUrl ? 'environment' : pluginUrl ? 'plugin' : saved.server_url ? 'saved' : 'default',
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
* limitations under the License.
*/

// Generated from integrations/lifecycle/transport.ts; do not edit.
// Edit the source and run `make integration-lifecycle` instead.

import { readFileSync } from 'node:fs'
import { homedir } from 'node:os'
import { join } from 'node:path'
Expand Down
3 changes: 3 additions & 0 deletions integrations/opencode/plugins/powercontext/src/transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
* limitations under the License.
*/

// Generated from integrations/lifecycle/transport.ts; do not edit.
// Edit the source and run `make integration-lifecycle` instead.

import { readFileSync } from 'node:fs'
import { homedir } from 'node:os'
import { join } from 'node:path'
Expand Down
3 changes: 3 additions & 0 deletions integrations/pi/plugins/powercontext/src/transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
* limitations under the License.
*/

// Generated from integrations/lifecycle/transport.ts; do not edit.
// Edit the source and run `make integration-lifecycle` instead.

import { readFileSync } from 'node:fs'
import { homedir } from 'node:os'
import { join } from 'node:path'
Expand Down
71 changes: 56 additions & 15 deletions scripts/generate_integration_lifecycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@
# See the License for the specific language governing permissions and
# limitations under the License.

"""Write the copies of the integration lifecycle helpers that copy-installed Python plugins ship."""
"""Write the copies of the integration lifecycle helpers that plugins ship.

Copy-installed Python plugins get the Python helpers. TypeScript host plugins get the TypeScript helpers, which their
bundlers inline or, for Pi, which the host loads as source.
"""

from __future__ import annotations

Expand All @@ -23,11 +27,16 @@

ROOT = Path(__file__).resolve().parents[1]
SOURCE = ROOT / "src" / "powercontext_integration_lifecycle"
TYPESCRIPT_SOURCE = ROOT / "integrations" / "lifecycle"
PLUGINS = "integrations/*/plugins/*"
_CLAUDE_CODE = "integrations/claude-code/plugins/powercontext"
_CODEX = "integrations/codex/plugins/powercontext"
_HERMES = "integrations/hermes/plugins/powercontext"
_WORKBUDDY = "integrations/workbuddy/plugins/powercontext"
_DSH = "integrations/dsh/plugins/powercontext"
_OPENCLAW = "integrations/openclaw/plugins/memory-powercontext"
_OPENCODE = "integrations/opencode/plugins/powercontext"
_PI = "integrations/pi/plugins/powercontext"
# Each copy stays where its host's hooks and installer already expect it.
COPIES = {
"client_config.py": (
Expand All @@ -51,33 +60,65 @@
f"{_CODEX}/hooks/bootstrap_context.py",
),
}
# A copy keeps the path its plugin imports, so bundled output still names the same module.
TYPESCRIPT_COPIES = {
"transport.ts": (
f"{_DSH}/src/transport.ts",
f"{_OPENCLAW}/src/transport.ts",
f"{_OPENCODE}/src/transport.ts",
f"{_PI}/src/transport.ts",
),
}
DRIFT_MESSAGE = (
"Generated integration lifecycle helpers drifted; edit src/powercontext_integration_lifecycle/, "
"run 'make integration-lifecycle', and review the result."
"Generated integration lifecycle helpers drifted; edit src/powercontext_integration_lifecycle/ or "
"integrations/lifecycle/, run 'make integration-lifecycle', and review the result."
)
UNLISTED_MESSAGE = (
"Plugin files share a name with a generated integration lifecycle helper; add each copy to COPIES in "
"scripts/generate_integration_lifecycle.py, or rename or delete the file."
"Plugin files share a name with a generated integration lifecycle helper; add each copy to COPIES or "
"TYPESCRIPT_COPIES in scripts/generate_integration_lifecycle.py, or rename or delete the file."
)


def render(module: str) -> str:
def render(source: Path) -> str:
"""Return a plugin's copy of one helper, marked as generated below its license header."""

source = SOURCE / module
lines = source.read_text(encoding="utf-8").splitlines(keepends=True)
header = next((index for index, line in enumerate(lines) if not line.startswith("#")), len(lines))
if source.suffix == ".py":
comment = "#"
header = next((index for index, line in enumerate(lines) if not line.startswith("#")), len(lines))
elif source.suffix in {".ts", ".mjs"}:
# The JavaScript and TypeScript license header is one leading block comment.
comment = "//"
header = 0
if lines and lines[0].startswith("/*"):
end = next((index for index, line in enumerate(lines) if line.rstrip().endswith("*/")), None)
if end is None:
raise SystemExit(f"{source.relative_to(ROOT)}: no license header line ends with '*/'") # noqa: TRY003
header = end + 1
else:
raise SystemExit(f"{source.relative_to(ROOT)}: no generated-file marker for this file type") # noqa: TRY003
marker = (
f"# Generated from {source.relative_to(ROOT).as_posix()}; do not edit.\n"
"# Edit the source and run `make integration-lifecycle` instead.\n"
f"{comment} Generated from {source.relative_to(ROOT).as_posix()}; do not edit.\n"
f"{comment} Edit the source and run `make integration-lifecycle` instead.\n"
)
return "".join([*lines[:header], "\n" if header else "", marker, *lines[header:]])


def unlisted_copies() -> list[Path]:
"""Return committable plugin files named like a generated copy that no entry in COPIES writes."""
def expected_copies() -> dict[Path, str]:
"""Return every copy the generator writes, keyed by its path."""

tables = ((SOURCE, COPIES), (TYPESCRIPT_SOURCE, TYPESCRIPT_COPIES))
return {
ROOT / target: render(source / module)
for source, copies in tables
for module, targets in copies.items()
for target in targets
}


def unlisted_copies(listed: set[Path]) -> list[Path]:
"""Return committable plugin files named like a generated copy that the generator does not write."""

listed = {ROOT / target for targets in COPIES.values() for target in targets}
pathspecs = sorted({f":(glob){PLUGINS}/**/{path.name}" for path in listed})
# Git leaves out ignored build output and installed dependencies, which are not plugin sources.
# Git writes its own errors, such as a missing checkout, to the terminal.
Expand All @@ -96,15 +137,15 @@ def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true", help="Fail when a copy is missing, stale, or kept by hand.")
args = parser.parse_args()
expected = {ROOT / target: render(module) for module, targets in COPIES.items() for target in targets}
expected = expected_copies()
if args.check:
stale = []
for path, text in expected.items():
if not path.is_file():
stale.append(f" {path.relative_to(ROOT)} is missing")
elif path.read_text(encoding="utf-8") != text:
stale.append(f" {path.relative_to(ROOT)} has drifted")
unlisted = [f" {path.relative_to(ROOT)}" for path in unlisted_copies()]
unlisted = [f" {path.relative_to(ROOT)}" for path in unlisted_copies(set(expected))]
problems = []
if stale:
problems += [DRIFT_MESSAGE, *stale]
Expand Down
6 changes: 5 additions & 1 deletion tests/test_ci_changes.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,11 @@
{"tests", "database", "harness", "oceanbase_acceptance", "upgrade", "candidate_replay", "release_schema"},
),
(["scripts/sync_dsh_plugin_tree.py"], {"tests", "dsh"}),
(["scripts/generate_integration_lifecycle.py"], {"tests", "hermes"}),
(
["scripts/generate_integration_lifecycle.py"],
{"tests", "hermes", "dsh", "cindy", "pi", "opencode", "openclaw", "zcode"},
),
(["integrations/lifecycle/transport.ts"], {"tests", "dsh", "cindy", "pi", "opencode", "openclaw", "zcode"}),
(["desktop/ui/src/app/App.tsx"], {"desktop"}),
(["release/upgrade-support.json"], {"upgrade", "packaging"}),
([".github/workflows/desktop.yml"], {"desktop"}),
Expand Down
Loading
Loading