create-principles-disciple 1.154.3 → 1.154.4

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 (109) hide show
  1. package/_release/product-identity.json +1 -1
  2. package/codex-adapter/dist/worker/workspace-worker.js +7 -1
  3. package/codex-adapter/package.json +1 -1
  4. package/core/dist/runtime/feature-flags/feature-flag-contract.d.ts.map +1 -1
  5. package/core/dist/runtime/feature-flags/feature-flag-contract.js +1 -0
  6. package/core/dist/runtime/feature-flags/feature-flag-contract.js.map +1 -1
  7. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.d.ts.map +1 -1
  8. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js +8 -0
  9. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js.map +1 -1
  10. package/core/dist/runtime/pain-ingress-payload.d.ts +13 -0
  11. package/core/dist/runtime/pain-ingress-payload.d.ts.map +1 -1
  12. package/core/dist/runtime/pain-ingress-payload.js +26 -0
  13. package/core/dist/runtime/pain-ingress-payload.js.map +1 -1
  14. package/core/dist/runtime/pain-ingress.d.ts +1 -1
  15. package/core/dist/runtime/pain-ingress.d.ts.map +1 -1
  16. package/core/dist/runtime/pain-ingress.js +15 -2
  17. package/core/dist/runtime/pain-ingress.js.map +1 -1
  18. package/core/dist/runtime/pain-signal-bridge.d.ts +18 -0
  19. package/core/dist/runtime/pain-signal-bridge.d.ts.map +1 -1
  20. package/core/dist/runtime/pain-signal-bridge.js +49 -1
  21. package/core/dist/runtime/pain-signal-bridge.js.map +1 -1
  22. package/core/dist/runtime/pain-signal-runtime-factory.d.ts +7 -0
  23. package/core/dist/runtime/pain-signal-runtime-factory.d.ts.map +1 -1
  24. package/core/dist/runtime/pain-signal-runtime-factory.js +2 -0
  25. package/core/dist/runtime/pain-signal-runtime-factory.js.map +1 -1
  26. package/core/dist/runtime/pain-to-principle-service.d.ts +8 -0
  27. package/core/dist/runtime/pain-to-principle-service.d.ts.map +1 -1
  28. package/core/dist/runtime/pain-to-principle-service.js +21 -1
  29. package/core/dist/runtime/pain-to-principle-service.js.map +1 -1
  30. package/core/package.json +1 -1
  31. package/host-runtime/dist/auto-pain-authorization.d.ts +29 -0
  32. package/host-runtime/dist/auto-pain-authorization.js +32 -0
  33. package/host-runtime/dist/diagnostician-auto-run.d.ts +1 -1
  34. package/host-runtime/dist/diagnostician-auto-run.js +41 -0
  35. package/host-runtime/dist/governance-signal-admission.js +16 -0
  36. package/host-runtime/dist/index.d.ts +1 -0
  37. package/host-runtime/dist/index.js +1 -0
  38. package/host-runtime/package.json +1 -1
  39. package/install-layout/dist/active-release.d.ts +41 -0
  40. package/install-layout/dist/active-release.js +131 -0
  41. package/install-layout/dist/index.d.ts +56 -5
  42. package/install-layout/dist/index.js +166 -1
  43. package/install-layout/dist/mcp-binding-contract.d.ts +76 -12
  44. package/install-layout/dist/mcp-binding-contract.js +183 -75
  45. package/install-layout/package.json +1 -1
  46. package/package.json +3 -3
  47. package/pd-cli/dist/commands/pain-record.d.ts.map +1 -1
  48. package/pd-cli/dist/commands/pain-record.js +4 -1
  49. package/pd-cli/dist/commands/pain-record.js.map +1 -1
  50. package/pd-cli/dist/commands/pain-retry.d.ts.map +1 -1
  51. package/pd-cli/dist/commands/pain-retry.js +19 -1
  52. package/pd-cli/dist/commands/pain-retry.js.map +1 -1
  53. package/pd-cli/dist/commands/service-run-once.d.ts +6 -0
  54. package/pd-cli/dist/commands/service-run-once.d.ts.map +1 -0
  55. package/pd-cli/dist/commands/service-run-once.js +139 -0
  56. package/pd-cli/dist/commands/service-run-once.js.map +1 -0
  57. package/pd-cli/dist/program.d.ts.map +1 -1
  58. package/pd-cli/dist/program.js +21 -0
  59. package/pd-cli/dist/program.js.map +1 -1
  60. package/pd-cli/dist/services/pain-flood-simulation-runner.d.ts.map +1 -1
  61. package/pd-cli/dist/services/pain-flood-simulation-runner.js +4 -0
  62. package/pd-cli/dist/services/pain-flood-simulation-runner.js.map +1 -1
  63. package/pd-cli/dist/services/service-host/index.d.ts +15 -0
  64. package/pd-cli/dist/services/service-host/index.d.ts.map +1 -0
  65. package/pd-cli/dist/services/service-host/index.js +15 -0
  66. package/pd-cli/dist/services/service-host/index.js.map +1 -0
  67. package/pd-cli/dist/services/service-host/install-identity.d.ts +79 -0
  68. package/pd-cli/dist/services/service-host/install-identity.d.ts.map +1 -0
  69. package/pd-cli/dist/services/service-host/install-identity.js +166 -0
  70. package/pd-cli/dist/services/service-host/install-identity.js.map +1 -0
  71. package/pd-cli/dist/services/service-host/locking/service-run-lock.d.ts +134 -0
  72. package/pd-cli/dist/services/service-host/locking/service-run-lock.d.ts.map +1 -0
  73. package/pd-cli/dist/services/service-host/locking/service-run-lock.js +659 -0
  74. package/pd-cli/dist/services/service-host/locking/service-run-lock.js.map +1 -0
  75. package/pd-cli/dist/services/service-host/owner-projection.d.ts +47 -0
  76. package/pd-cli/dist/services/service-host/owner-projection.d.ts.map +1 -0
  77. package/pd-cli/dist/services/service-host/owner-projection.js +121 -0
  78. package/pd-cli/dist/services/service-host/owner-projection.js.map +1 -0
  79. package/pd-cli/dist/services/service-host/run-once.d.ts +96 -0
  80. package/pd-cli/dist/services/service-host/run-once.d.ts.map +1 -0
  81. package/pd-cli/dist/services/service-host/run-once.js +440 -0
  82. package/pd-cli/dist/services/service-host/run-once.js.map +1 -0
  83. package/pd-cli/dist/services/service-host/status/service-run-status.d.ts +117 -0
  84. package/pd-cli/dist/services/service-host/status/service-run-status.d.ts.map +1 -0
  85. package/pd-cli/dist/services/service-host/status/service-run-status.js +150 -0
  86. package/pd-cli/dist/services/service-host/status/service-run-status.js.map +1 -0
  87. package/pd-cli/dist/services/service-host/workspace-discovery.d.ts +71 -0
  88. package/pd-cli/dist/services/service-host/workspace-discovery.d.ts.map +1 -0
  89. package/pd-cli/dist/services/service-host/workspace-discovery.js +288 -0
  90. package/pd-cli/dist/services/service-host/workspace-discovery.js.map +1 -0
  91. package/pd-cli/dist/services/synthetic-baseline-runner.d.ts.map +1 -1
  92. package/pd-cli/dist/services/synthetic-baseline-runner.js +4 -0
  93. package/pd-cli/dist/services/synthetic-baseline-runner.js.map +1 -1
  94. package/pd-cli/package.json +1 -1
  95. package/plugin/dist/bundle.js +420 -420
  96. package/plugin/dist/core/signal-collector-host.d.ts +12 -0
  97. package/plugin/dist/openclaw.plugin.json +1 -1
  98. package/plugin/dist/templates/langs/en/skills/pd-pain-signal/SKILL.md +10 -2
  99. package/plugin/dist/templates/langs/zh/skills/pd-pain-signal/SKILL.md +10 -2
  100. package/plugin/mcp/launcher.cjs +40 -4
  101. package/plugin/openclaw.plugin.json +1 -1
  102. package/plugin/package.json +1 -1
  103. package/plugin/templates/langs/en/skills/pd-pain-signal/SKILL.md +10 -2
  104. package/plugin/templates/langs/zh/skills/pd-pain-signal/SKILL.md +10 -2
  105. package/release-manager/package.json +1 -1
  106. package/workbuddy-adapter/dist/worker/workspace-worker.js +4 -1
  107. package/workbuddy-adapter/package.json +1 -1
  108. package/workbuddy-adapter/plugin/mcp/launcher.cjs +40 -4
  109. package/workbuddy-adapter/plugin/skills/pd-pain-signal/SKILL.md +10 -2
@@ -20,6 +20,7 @@
20
20
  import * as path from 'node:path';
21
21
  import { PrincipleTreeLedgerAdapter, createPainSignalBridge, createRuntimeStateHandle, pickDiagnosticianCandidate, resolveDiagnosticianCapability, } from '@principles/core/runtime';
22
22
  import { loadFeatureFlagFromConfig, loadPdConfigForPlugin } from './pd-config.js';
23
+ import { isAutomaticPainSubmissionAuthorized } from './auto-pain-authorization.js';
23
24
  import { createHostIntentDocReader } from './intent-doc-reader.js';
24
25
  import { createGovernanceTrajectoryTurnReader } from './governance-trajectory-turn-reader.js';
25
26
  /** Quiet flag that owns the L3 half of the ladder. */
@@ -27,6 +28,27 @@ export const DIAGNOSTICIAN_AUTO_RUN_FLAG = 'openclaw_diagnostician_consumer';
27
28
  /** Owner string used for the diagnostics this module starts. */
28
29
  export const DIAGNOSTICIAN_AUTO_RUN_OWNER = 'pd-auto-diagnostician';
29
30
  const DEFAULT_CANDIDATE_LIMIT = 1;
31
+ /**
32
+ * The persisted top-level provenance is the admission authority for both
33
+ * legacy and v1 payloads (pain-signal-bridge's persisted-facts validator
34
+ * requires the two namespaces to agree). A malformed/missing payload is not
35
+ * an automatic submission — it is left for the normal execution path, which
36
+ * owns its own payload validation.
37
+ */
38
+ function persistedCandidateProvenance(diagnosticJson) {
39
+ if (typeof diagnosticJson !== 'string' || diagnosticJson.length === 0)
40
+ return null;
41
+ try {
42
+ const parsed = JSON.parse(diagnosticJson);
43
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
44
+ return null;
45
+ const provenance = Reflect.get(parsed, 'provenance');
46
+ return typeof provenance === 'string' ? provenance : null;
47
+ }
48
+ catch {
49
+ return null;
50
+ }
51
+ }
30
52
  export async function runPendingDiagnosticianOnce(options) {
31
53
  if (options.serviceStarted === false) {
32
54
  return {
@@ -62,6 +84,22 @@ export async function runPendingDiagnosticianOnce(options) {
62
84
  if (candidate === null) {
63
85
  return { served: false, reason: 'no_candidate' };
64
86
  }
87
+ // B-class authorization (Pain Ingress SPEC §9.6): a persisted automatic
88
+ // submission may not execute after the Owner revoked (or never granted)
89
+ // the Workspace flag — background recovery cannot bypass the gate. The
90
+ // task stays pending, retryable once the flag is enabled. owner_manual /
91
+ // host_context_bound / agent_reported_owner_approved tasks are exempt:
92
+ // their Owner authorization is intrinsic.
93
+ if (persistedCandidateProvenance(candidate.diagnosticJson) === 'automatic_hook'
94
+ && !isAutomaticPainSubmissionAuthorized(options.workspaceDir)) {
95
+ return {
96
+ served: false,
97
+ reason: 'auto_pain_unauthorized',
98
+ taskId: candidate.taskId,
99
+ message: 'candidate is an automatic_hook submission and features.automatic_pain_submission is off',
100
+ nextAction: 'The task stays pending; enable features.automatic_pain_submission in .pd/config.yaml to allow automatic-Pain diagnosis.',
101
+ };
102
+ }
65
103
  const stateDir = path.join(options.workspaceDir, '.state');
66
104
  try {
67
105
  const bridge = await createPainSignalBridge({
@@ -79,6 +117,9 @@ export async function runPendingDiagnosticianOnce(options) {
79
117
  // PRI-1265: the auto-run path sees the bound session's ORIGINAL turns
80
118
  // like every other diagnosis entry.
81
119
  trajectoryTurnReader: createGovernanceTrajectoryTurnReader({ workspaceDir: options.workspaceDir }),
120
+ // SPEC §9.6: lazy probe — a flag revoked between candidate pick and
121
+ // execution still stops the run at the bridge boundary.
122
+ isAutoPainSubmissionAuthorized: () => isAutomaticPainSubmissionAuthorized(options.workspaceDir),
82
123
  });
83
124
  const executed = await bridge.executePendingDiagnosis({ taskId: candidate.taskId });
84
125
  if (executed.status === 'failed') {
@@ -39,6 +39,7 @@ import { collectSync, computeFeatureFlagsFromConfig, CORRECTION_SEED_KEYWORDS, P
39
39
  import { deriveProductionCorrectionPainIdentity, hasProductionPainSchema, } from './production-pain-evidence.js';
40
40
  import { promoteGovernanceEvidence, ensureGovernanceSchema } from './governance-observation-store.js';
41
41
  import { loadPdConfigForPlugin } from './pd-config.js';
42
+ import { isAutomaticPainSubmissionAuthorized } from './auto-pain-authorization.js';
42
43
  import { createHostIntentDocReader } from './intent-doc-reader.js';
43
44
  import { resolveTrajectoryDbPath } from '@principles/core/runtime/storage-paths';
44
45
  // ─── Shared detector constants (one truth for both hosts) ───────────────────
@@ -1836,6 +1837,18 @@ export async function ensureGovernanceDiagnosticianTask(input) {
1836
1837
  ...(ingressWarning !== undefined ? { ingressWarning } : {}),
1837
1838
  };
1838
1839
  }
1840
+ // B-class authorization (Pain Ingress SPEC §9.6): a governance marker
1841
+ // whose ingress facts classify as automatic_hook still requires the
1842
+ // Workspace's own automatic_pain_submission opt-in. An already-linked
1843
+ // task is untouched (recovery branch above); a NEW diagnosis task is
1844
+ // never created for an unauthorized automatic signal.
1845
+ if (provenance === 'automatic_hook' && !isAutomaticPainSubmissionAuthorized(workspaceDir)) {
1846
+ return {
1847
+ ok: false,
1848
+ reason: 'auto_pain_unauthorized',
1849
+ nextAction: 'Enable features.automatic_pain_submission in this workspace .pd/config.yaml to admit automatic Pain submissions.',
1850
+ };
1851
+ }
1839
1852
  const taskId = createDiagnosticianTaskId(input.canonicalPainId);
1840
1853
  // Cross-store crash recovery (SPEC §13): a task may already exist from a
1841
1854
  // crashed prior attempt (crash-after-create, before the link write).
@@ -1866,6 +1879,9 @@ export async function ensureGovernanceDiagnosticianTask(input) {
1866
1879
  // marker, canonical pain id, task id and idempotency semantics above
1867
1880
  // are untouched; a reader failure degrades inside Stage A only.
1868
1881
  intentDocReader: createHostIntentDocReader({ workspaceDir, effectiveConfig: config.effective }),
1882
+ // SPEC §9.6: lazy probe — revocation between this admission check
1883
+ // and the async persist still refuses the submission.
1884
+ isAutoPainSubmissionAuthorized: () => isAutomaticPainSubmissionAuthorized(workspaceDir),
1869
1885
  });
1870
1886
  const result = await service.recordPain({
1871
1887
  painId: input.canonicalPainId,
@@ -149,3 +149,4 @@ export { revalidateAdaptivePrinciple, createAdaptivePrincipleRevalidator, type A
149
149
  export * from './adaptive-journal-reconciliation.js';
150
150
  export * from './adaptive-behavior-linkage.js';
151
151
  export * from './intent-doc-reader.js';
152
+ export * from './auto-pain-authorization.js';
@@ -435,3 +435,4 @@ export * from './adaptive-behavior-linkage.js';
435
435
  // shared by PD CLI (pain record / diagnose / pain retry) and governance
436
436
  // admission. Business semantics stay in Core; this is the I/O adapter only.
437
437
  export * from './intent-doc-reader.js';
438
+ export * from './auto-pain-authorization.js';
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/host-runtime",
3
- "version": "4.5.0",
3
+ "version": "4.5.1",
4
4
  "description": "Shared host-neutral orchestration for Principles Disciple MVP-Core hook paths.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -0,0 +1,41 @@
1
+ /** The only schema generation this reader accepts. */
2
+ export declare const ACTIVE_RELEASE_SCHEMA_VERSION: 1;
3
+ /** The full record exactly as the installer's commit point writes it. */
4
+ export interface ActiveReleaseRecord {
5
+ readonly schemaVersion: typeof ACTIVE_RELEASE_SCHEMA_VERSION;
6
+ readonly generation: number;
7
+ readonly releaseId: string;
8
+ readonly releaseMetadataDigest: string;
9
+ readonly previousReleaseId: string | null;
10
+ readonly transactionId: string;
11
+ readonly productVersion: string;
12
+ /** Embedded provenance (stamped source commit); absent on legacy records. */
13
+ readonly sourceCommit?: string;
14
+ }
15
+ /**
16
+ * The distinct failure classes a read can end in. Field-level reasons name
17
+ * the field that failed so a corrupted install's repair message can say
18
+ * exactly what is wrong instead of "malformed".
19
+ */
20
+ export type ActiveReleaseFailureReason = 'active_record_absent' | 'active_record_read_failed' | 'active_record_json_invalid' | 'active_record_not_object' | 'active_record_schema_version_unsupported' | 'active_record_release_id_invalid' | 'active_record_generation_invalid' | 'active_record_digest_invalid' | 'active_record_previous_release_id_invalid' | 'active_record_transaction_id_invalid' | 'active_record_product_version_invalid' | 'active_record_source_commit_invalid';
21
+ export type ActiveReleaseVerdict = {
22
+ readonly ok: true;
23
+ readonly record: ActiveReleaseRecord;
24
+ } | {
25
+ readonly ok: false;
26
+ readonly reason: ActiveReleaseFailureReason;
27
+ readonly detail: string;
28
+ };
29
+ /**
30
+ * Validate an already-parsed JSON value against the authoritative record
31
+ * schema. Untrusted input: every field is checked by primitive guards
32
+ * (rc-1/rc-2), no `as` bypass.
33
+ */
34
+ export declare function parseActiveReleaseRecord(value: unknown): ActiveReleaseVerdict;
35
+ /**
36
+ * Read and validate `<pdHome>/active.json`. Missing vs unreadable vs corrupt
37
+ * vs schema-nonconforming are all distinguishable by `reason` (rc-3/rc-9).
38
+ */
39
+ export declare function readActiveReleaseRecord(recordPath: string): ActiveReleaseVerdict;
40
+ /** `<pdHome>/active.json` — the canonical record location. */
41
+ export declare function activeReleaseRecordPath(pdHome: string): string;
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Active release record — the ONE authoritative schema + reader for
3
+ * `<pdHome>/active.json` (the installation authority).
4
+ *
5
+ * The only production writer is the installer/update transaction's commit
6
+ * point (`writeActiveRecord` in create-principles-disciple's
7
+ * transaction-journal), which always serializes the full field set:
8
+ * `schemaVersion: 1`, `generation` (positive safe integer, monotonic),
9
+ * `releaseId`, `releaseMetadataDigest` (64-char hex), `previousReleaseId`
10
+ * (string | null), `transactionId`, `productVersion`, and an optional
11
+ * `sourceCommit` (40-char hex) embedded on records written after SPEC §12
12
+ * provenance stamping.
13
+ *
14
+ * This module is the single validation authority every reader shares:
15
+ * consumers that need the full record (the update chain's recovery, the
16
+ * run-once coordinator's install-identity check) must not carry a second,
17
+ * looser copy of the schema — a record that lost any of these fields is
18
+ * not the record the update chain writes, and treating it as one is how a
19
+ * corrupted install gets reported as a healthy release.
20
+ *
21
+ * Failure classes stay DISTINCT (rc-3/rc-9): absent file, unreadable file,
22
+ * non-JSON content, non-object JSON, unsupported schemaVersion and each
23
+ * malformed field are different situations an operator must tell apart —
24
+ * never collapse them into "no release".
25
+ */
26
+ import * as fs from 'node:fs';
27
+ import * as path from 'node:path';
28
+ /** The only schema generation this reader accepts. */
29
+ export const ACTIVE_RELEASE_SCHEMA_VERSION = 1;
30
+ function isPlainObject(value) {
31
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
32
+ }
33
+ /** Bounded, control-character-free error detail (rc-8). */
34
+ function brief(value, max = 160) {
35
+ const text = value instanceof Error ? value.message : String(value);
36
+ const clean = text.replace(/[^\x20-\x7E]+/g, ' ');
37
+ return clean.length > max ? `${clean.slice(0, max - 1)}…` : clean;
38
+ }
39
+ function fail(reason, detail) {
40
+ return { ok: false, reason, detail };
41
+ }
42
+ /**
43
+ * Validate an already-parsed JSON value against the authoritative record
44
+ * schema. Untrusted input: every field is checked by primitive guards
45
+ * (rc-1/rc-2), no `as` bypass.
46
+ */
47
+ export function parseActiveReleaseRecord(value) {
48
+ if (!isPlainObject(value)) {
49
+ return fail('active_record_not_object', 'active.json is not a JSON object');
50
+ }
51
+ if (value.schemaVersion !== ACTIVE_RELEASE_SCHEMA_VERSION) {
52
+ return fail('active_record_schema_version_unsupported', `active.json has unsupported schemaVersion: ${brief(JSON.stringify(value.schemaVersion))}`);
53
+ }
54
+ const { generation, releaseId } = value;
55
+ const digest = value.releaseMetadataDigest;
56
+ const { previousReleaseId, transactionId, productVersion, sourceCommit } = value;
57
+ if (typeof releaseId !== 'string' || releaseId.length === 0) {
58
+ return fail('active_record_release_id_invalid', 'active.json releaseId must be a non-empty string');
59
+ }
60
+ if (typeof generation !== 'number' || !Number.isSafeInteger(generation) || generation < 1) {
61
+ return fail('active_record_generation_invalid', 'active.json generation must be a positive safe integer');
62
+ }
63
+ if (typeof digest !== 'string' || !/^[a-f0-9]{64}$/.test(digest)) {
64
+ return fail('active_record_digest_invalid', 'active.json releaseMetadataDigest must be a 64-char hex string');
65
+ }
66
+ if (previousReleaseId !== null && (typeof previousReleaseId !== 'string' || previousReleaseId.length === 0)) {
67
+ return fail('active_record_previous_release_id_invalid', 'active.json previousReleaseId must be a non-empty string or null');
68
+ }
69
+ if (typeof transactionId !== 'string' || transactionId.length === 0) {
70
+ return fail('active_record_transaction_id_invalid', 'active.json transactionId must be a non-empty string');
71
+ }
72
+ if (typeof productVersion !== 'string' || productVersion.length === 0) {
73
+ return fail('active_record_product_version_invalid', 'active.json productVersion must be a non-empty string');
74
+ }
75
+ // Optional embedded provenance: strict WHEN present (rc-3); absence is the
76
+ // legacy shape and stays valid.
77
+ if (sourceCommit !== undefined && (typeof sourceCommit !== 'string' || !/^[a-f0-9]{40}$/.test(sourceCommit))) {
78
+ return fail('active_record_source_commit_invalid', 'active.json sourceCommit must be a 40-char git commit sha when present');
79
+ }
80
+ return {
81
+ ok: true,
82
+ record: {
83
+ schemaVersion: ACTIVE_RELEASE_SCHEMA_VERSION,
84
+ generation,
85
+ releaseId,
86
+ releaseMetadataDigest: digest,
87
+ previousReleaseId,
88
+ transactionId,
89
+ productVersion,
90
+ ...(sourceCommit !== undefined ? { sourceCommit } : {}),
91
+ },
92
+ };
93
+ }
94
+ /**
95
+ * Read and validate `<pdHome>/active.json`. Missing vs unreadable vs corrupt
96
+ * vs schema-nonconforming are all distinguishable by `reason` (rc-3/rc-9).
97
+ */
98
+ export function readActiveReleaseRecord(recordPath) {
99
+ // No existsSync pre-check (P2-2): the check-then-read pair is a TOCTOU —
100
+ // the file can appear or vanish between them, and existsSync answers a
101
+ // different question than "can we read the record". Read directly and
102
+ // classify by errno: ENOENT/ENOTDIR (including a dangling symlink, whose
103
+ // read fails ENOENT) is `absent`; every other read failure — EACCES,
104
+ // EPERM, EIO, EISDIR — is `read_failed`, fail-closed and never faked as
105
+ // "no release installed".
106
+ let text;
107
+ try {
108
+ text = fs.readFileSync(recordPath, 'utf8');
109
+ }
110
+ catch (error) {
111
+ const code = typeof error === 'object' && error !== null && Object.hasOwn(error, 'code')
112
+ ? String(Reflect.get(error, 'code'))
113
+ : '';
114
+ if (code === 'ENOENT' || code === 'ENOTDIR') {
115
+ return fail('active_record_absent', `active.json does not exist: ${recordPath}`);
116
+ }
117
+ return fail('active_record_read_failed', `active.json could not be read (${recordPath}): ${brief(error)}`);
118
+ }
119
+ let value;
120
+ try {
121
+ value = JSON.parse(text);
122
+ }
123
+ catch (error) {
124
+ return fail('active_record_json_invalid', `active.json is not valid JSON (${recordPath}): ${brief(error)}`);
125
+ }
126
+ return parseActiveReleaseRecord(value);
127
+ }
128
+ /** `<pdHome>/active.json` — the canonical record location. */
129
+ export function activeReleaseRecordPath(pdHome) {
130
+ return path.join(pdHome, 'active.json');
131
+ }
@@ -32,6 +32,50 @@ export interface InstallManifest {
32
32
  * from this list (SPEC §13 "canonical install manifest").
33
33
  */
34
34
  workspaces?: readonly string[];
35
+ /**
36
+ * Per-Workspace background-execution OWNERSHIP records (ADR-0020 §11.6
37
+ * narrow scope / SPEC-PD-SERVICE-HOST-001 §8.4), keyed by canonical
38
+ * absolute workspace path — the same identity `workspaces` carries.
39
+ * Optional so pre-record manifests stay valid; a Workspace with no entry
40
+ * means "legacy Companion owns background execution" for THAT Workspace
41
+ * only. Each Workspace migrates independently: one entry's transition
42
+ * never touches another key, so Workspace A can be `service_host_owned`
43
+ * while Workspace B is still `legacy_owned` or mid-`handover_preparing`.
44
+ *
45
+ * This is the CAS contract between the legacy consumer and the Service
46
+ * Host: only the state machine defined in the SPEC may advance an entry,
47
+ * every transition is a monotonic-generation compare-and-set, and PID /
48
+ * delays / startup order are NEVER ownership proof — this record is.
49
+ * The schema stores the record; the CAS write itself is NOT implemented
50
+ * yet (Phase 5 acceptance).
51
+ */
52
+ backgroundExecutions?: Readonly<Record<string, BackgroundExecutionRecord>>;
53
+ }
54
+ export declare const BACKGROUND_EXECUTION_OWNERS: readonly ['legacy', 'service_host'];
55
+ export type BackgroundExecutionOwner = (typeof BACKGROUND_EXECUTION_OWNERS)[number];
56
+ export declare const BACKGROUND_EXECUTION_STATES: readonly ['legacy_owned', 'handover_preparing', 'service_host_owned', 'rollback_pending'];
57
+ export type BackgroundExecutionState = (typeof BACKGROUND_EXECUTION_STATES)[number];
58
+ /**
59
+ * The persisted ownership fact for background execution (SPEC §8.4).
60
+ * - `state`/`effectiveOwner`: where the state machine currently stands and
61
+ * which consumer is allowed to execute work RIGHT NOW;
62
+ * - `generation`: strictly monotonic per accepted transition — the CAS key
63
+ * (a writer must observe `generation` then write `generation+1` under the
64
+ * manifest write lock; a stale observed generation loses);
65
+ * - `operationId`: idempotency key of the handover/rollback operation —
66
+ * replaying the same operationId must be a no-op;
67
+ * - `previousOwner`/`targetOwner`: the two parties of an in-flight
68
+ * transition (both null in a steady state);
69
+ * - `updatedAt`: ISO-8601 timestamp of the last accepted transition.
70
+ */
71
+ export interface BackgroundExecutionRecord {
72
+ state: BackgroundExecutionState;
73
+ effectiveOwner: BackgroundExecutionOwner;
74
+ generation: number;
75
+ operationId: string | null;
76
+ previousOwner: BackgroundExecutionOwner | null;
77
+ targetOwner: BackgroundExecutionOwner | null;
78
+ updatedAt: string;
35
79
  }
36
80
  /** Structured forward-compatibility observation from manifest parsing (rc-9). */
37
81
  export interface InstallManifestWarning {
@@ -113,10 +157,16 @@ export declare function mergeInstallManifestWorkspaces(current: InstallManifest
113
157
  */
114
158
  export declare function installManifestHostsForPersist(manifest: InstallManifest | undefined): string[];
115
159
  /**
116
- * Parse the install manifest. Structural damage fails closed with `error`;
117
- * a host string this reader version does not know is a `warnings` entry and
118
- * the manifest still parses (forward compatibility — see `InstallManifest.unknownHosts`).
160
+ * Set or clear ONE Workspace's ownership record, preserving every other
161
+ * Workspace's entry — the write-side half of "one migration never overwrites
162
+ * another Workspace's state". `record` must already satisfy the semantic
163
+ * contract (build it through the SPEC §8.4 state machine; absent record
164
+ * removes the entry and restores the legacy default for that Workspace).
119
165
  */
166
+ export declare function setInstallManifestBackgroundExecution(manifest: InstallManifest | undefined, target: {
167
+ workspaceDir: string;
168
+ platform?: string;
169
+ }, record: BackgroundExecutionRecord | undefined): Record<string, BackgroundExecutionRecord>;
120
170
  export declare function parseInstallManifest(value: unknown, platform?: string): {
121
171
  manifest?: InstallManifest;
122
172
  warnings?: readonly InstallManifestWarning[];
@@ -209,7 +259,8 @@ export declare function getPdCliEntry(paths: InstallLayoutPaths, mode: InstallLa
209
259
  * authority for "which PD home does this process own" — components must not
210
260
  * re-derive it locally.
211
261
  */
212
- export { PD_EXPERIMENT_ROOT_ENV, PD_OPENCLAW_HOME_ENV, PD_OPENCLAW_STATE_DIR_ENV, PD_CODEX_HOME_ENV, PD_WORKBUDDY_CONFIG_DIR_ENV, PD_HOST_WORKSPACE_DIR_NAME, PD_HOME_MODES, PD_HOME_FAILURE_REASONS, resolvePdHome, isPathWithinRoot, type PdHomeMode, type PdHomePaths, type PdHomeFailure, type PdHomeFailureReason, type PdHomeSuccess, type PdHomeResolution, type ResolvePdHomeOptions, } from './pd-home.js';
262
+ export { PD_EXPERIMENT_ROOT_ENV, PD_OPENCLAW_HOME_ENV, PD_OPENCLAW_STATE_DIR_ENV, PD_CODEX_HOME_ENV, PD_WORKBUDDY_CONFIG_DIR_ENV, PD_HOST_WORKSPACE_DIR_NAME, PD_HOME_MODES, PD_HOME_FAILURE_REASONS, resolvePdHome, resolveRealUserHome, isPathWithinRoot, type PdHomeMode, type PdHomePaths, type PdHomeFailure, type PdHomeFailureReason, type PdHomeSuccess, type PdHomeResolution, type ResolvePdHomeOptions, } from './pd-home.js';
263
+ export { ACTIVE_RELEASE_SCHEMA_VERSION, activeReleaseRecordPath, parseActiveReleaseRecord, readActiveReleaseRecord, type ActiveReleaseFailureReason, type ActiveReleaseRecord, type ActiveReleaseVerdict, } from './active-release.js';
213
264
  /**
214
265
  * Codex host-persistent binding location. The versioned payload directory is
215
266
  * REPLACED by a host cache refresh, taking any binding written inside it with
@@ -239,4 +290,4 @@ export declare function selectCodexMcpBindingPath(codexHome: string, pluginRoot:
239
290
  * against it by the parity test, and the installer / `pd health` import it
240
291
  * directly so neither can drift into a more permissive check.
241
292
  */
242
- export { MCP_BINDING_SCHEMA_VERSION, MCP_BINDING_HOSTS, MCP_BINDING_SERVER_ENTRY_SEGMENTS, MCP_BINDING_SHAPE_CODES, MCP_BINDING_LAUNCHER_ONLY_REASONS, MCP_BINDING_FIXTURES, getCanonicalMcpServerEntry, getHostDefaultWorkspaceDirs, findForeignWorkspaceHost, collectHostWorkspaceClaims, findForeignWorkspaceOwner, isSameMcpBindingPath, validateMcpBinding, buildMcpBindingFixture, isMcpBindingHost, isSupportedBindingSchemaVersion, isSemverVersion, type McpBindingHost, type McpHostWorkspaceOptions, type McpBindingRecord, type McpBindingVerdict, type McpBindingShapeCode, type McpBindingFixture, type McpBindingFixtureId, type McpBindingFixtureContext, type HostWorkspaceClaim, type HostWorkspaceClaimVia, type HostClaimReaders, type HostClaimOptions, type ForeignWorkspaceOwnerVerdict, } from './mcp-binding-contract.js';
293
+ export { MCP_BINDING_SCHEMA_VERSION, MCP_BINDING_HOSTS, MCP_BINDING_SERVER_ENTRY_SEGMENTS, MCP_BINDING_SHAPE_CODES, MCP_BINDING_LAUNCHER_ONLY_REASONS, MCP_BINDING_FIXTURES, getCanonicalMcpServerEntry, getHostDefaultWorkspaceDirs, findForeignWorkspaceHost, collectHostWorkspaceClaims, findForeignWorkspaceOwner, isSameMcpBindingPath, validateMcpBinding, buildMcpBindingFixture, isMcpBindingHost, isSupportedBindingSchemaVersion, isSemverVersion, type McpBindingHost, type McpHostWorkspaceOptions, type McpBindingRecord, type McpBindingVerdict, type McpBindingShapeCode, type McpBindingFixture, type McpBindingFixtureId, type McpBindingFixtureContext, type HostWorkspaceClaim, type HostWorkspaceClaimVia, type HostClaimReaders, type HostClaimOptions, type JsonFileReadStatus, type BindingReadDiagnostic, type DirReadStatus, type ForeignWorkspaceOwnerVerdict, } from './mcp-binding-contract.js';
@@ -4,6 +4,13 @@ import { resolvePdHome } from './pd-home.js';
4
4
  export const INSTALL_LAYOUT_VERSION = 1;
5
5
  export const INSTALL_LAYOUT_MODES = ['canonical', 'legacy'];
6
6
  export const INSTALL_HOSTS = ['codex', 'openclaw', 'workbuddy'];
7
+ export const BACKGROUND_EXECUTION_OWNERS = ['legacy', 'service_host'];
8
+ export const BACKGROUND_EXECUTION_STATES = [
9
+ 'legacy_owned',
10
+ 'handover_preparing',
11
+ 'service_host_owned',
12
+ 'rollback_pending',
13
+ ];
7
14
  function isRecord(value) {
8
15
  return typeof value === 'object' && value !== null && !Array.isArray(value);
9
16
  }
@@ -70,6 +77,158 @@ export function installManifestHostsForPersist(manifest) {
70
77
  * a host string this reader version does not know is a `warnings` entry and
71
78
  * the manifest still parses (forward compatibility — see `InstallManifest.unknownHosts`).
72
79
  */
80
+ function isBackgroundExecutionOwner(value) {
81
+ return typeof value === 'string'
82
+ && BACKGROUND_EXECUTION_OWNERS.includes(value);
83
+ }
84
+ function isBackgroundExecutionState(value) {
85
+ return typeof value === 'string'
86
+ && BACKGROUND_EXECUTION_STATES.includes(value);
87
+ }
88
+ function isNullableOwner(value) {
89
+ return value === null || isBackgroundExecutionOwner(value);
90
+ }
91
+ /**
92
+ * Fail-closed semantic check for one ownership record. Absent is fine
93
+ * (legacy default); present-but-malformed is structural damage — an
94
+ * ownership fact that cannot be trusted must not be honored.
95
+ *
96
+ * Field types alone are NOT enough: the legal combination of
97
+ * state/effectiveOwner/previousOwner/targetOwner/operationId/generation is
98
+ * part of the contract (SPEC §8.4). Illegal combinations are refused at
99
+ * parse time so a corrupt marker can never be honored as ownership proof:
100
+ * - legacy_owned: effectiveOwner=legacy, prev/target/operationId=null, generation>=0;
101
+ * - service_host_owned: effectiveOwner=service_host, prev/target/operationId=null, generation>=1;
102
+ * - handover_preparing: effectiveOwner=legacy (old consumer still owns until the CAS flips),
103
+ * prev=legacy, target=service_host, operationId set, generation>=1;
104
+ * - rollback_pending: effectiveOwner=service_host (still owned until the CAS restores),
105
+ * prev=service_host, target=legacy, operationId set, generation>=1.
106
+ * A transition state implies at least one accepted transition already
107
+ * happened, so generation 0 there is unreachable and rejected.
108
+ */
109
+ function parseBackgroundExecutionRecord(value) {
110
+ if (value === undefined)
111
+ return {};
112
+ const malformed = 'install_manifest_malformed: backgroundExecution must be a complete ownership record';
113
+ if (!isRecord(value))
114
+ return { error: malformed };
115
+ if (!isBackgroundExecutionState(value.state))
116
+ return { error: malformed };
117
+ if (!isBackgroundExecutionOwner(value.effectiveOwner))
118
+ return { error: malformed };
119
+ if (typeof value.generation !== 'number' || !Number.isInteger(value.generation) || value.generation < 0) {
120
+ return { error: malformed };
121
+ }
122
+ if (value.operationId !== null && !isNonEmptyString(value.operationId))
123
+ return { error: malformed };
124
+ if (!isNullableOwner(value.previousOwner))
125
+ return { error: malformed };
126
+ if (!isNullableOwner(value.targetOwner))
127
+ return { error: malformed };
128
+ if (typeof value.updatedAt !== 'string' || value.updatedAt.length === 0)
129
+ return { error: malformed };
130
+ const combination = `install_manifest_malformed: backgroundExecution ${value.state} has an illegal ` +
131
+ 'effectiveOwner/previousOwner/targetOwner/operationId/generation combination';
132
+ switch (value.state) {
133
+ case 'legacy_owned':
134
+ if (value.effectiveOwner !== 'legacy' || value.previousOwner !== null
135
+ || value.targetOwner !== null || value.operationId !== null) {
136
+ return { error: combination };
137
+ }
138
+ break;
139
+ case 'service_host_owned':
140
+ if (value.effectiveOwner !== 'service_host' || value.previousOwner !== null
141
+ || value.targetOwner !== null || value.operationId !== null || value.generation < 1) {
142
+ return { error: combination };
143
+ }
144
+ break;
145
+ case 'handover_preparing':
146
+ if (value.effectiveOwner !== 'legacy' || value.previousOwner !== 'legacy'
147
+ || value.targetOwner !== 'service_host' || value.operationId === null || value.generation < 1) {
148
+ return { error: combination };
149
+ }
150
+ break;
151
+ case 'rollback_pending':
152
+ if (value.effectiveOwner !== 'service_host' || value.previousOwner !== 'service_host'
153
+ || value.targetOwner !== 'legacy' || value.operationId === null || value.generation < 1) {
154
+ return { error: combination };
155
+ }
156
+ break;
157
+ }
158
+ return {
159
+ record: {
160
+ state: value.state,
161
+ effectiveOwner: value.effectiveOwner,
162
+ generation: value.generation,
163
+ operationId: value.operationId,
164
+ previousOwner: value.previousOwner,
165
+ targetOwner: value.targetOwner,
166
+ updatedAt: value.updatedAt,
167
+ },
168
+ };
169
+ }
170
+ /**
171
+ * Parse the per-Workspace ownership map. Every key must be the canonical
172
+ * absolute path of a Workspace declared in `workspaces` — a record keyed to
173
+ * an undeclared identity is ambiguous ownership and fails closed rather
174
+ * than being silently honored or dropped.
175
+ *
176
+ * Backward compatibility: the pre-per-Workspace field `backgroundExecution`
177
+ * (a single record, no workspace identity) is migrated ONLY when the
178
+ * manifest declares exactly one Workspace — the only case where the owner
179
+ * is unambiguous. With zero or several Workspaces it is refuse-to-guess
180
+ * structural damage; both spellings present is a conflict and also fails.
181
+ */
182
+ function parseBackgroundExecutions(value, workspaces, platform) {
183
+ const mapMalformed = 'install_manifest_malformed: backgroundExecutions must be keyed by canonical paths of declared workspaces';
184
+ const api = workspacePathApi(platform);
185
+ const legacy = parseBackgroundExecutionRecord(value.backgroundExecution);
186
+ if (legacy.error)
187
+ return { error: legacy.error };
188
+ if (value.backgroundExecutions !== undefined && !isRecord(value.backgroundExecutions)) {
189
+ return { error: mapMalformed };
190
+ }
191
+ const records = {};
192
+ for (const [key, raw] of Object.entries(value.backgroundExecutions ?? {})) {
193
+ if (!api.isAbsolute(key) || api.resolve(key) !== key || !workspaces.includes(key)) {
194
+ return { error: mapMalformed };
195
+ }
196
+ const parsed = parseBackgroundExecutionRecord(raw);
197
+ if (parsed.error || !parsed.record)
198
+ return { error: parsed.error ?? mapMalformed };
199
+ records[key] = parsed.record;
200
+ }
201
+ if (legacy.record !== undefined) {
202
+ if (Object.keys(records).length > 0) {
203
+ return { error: 'install_manifest_malformed: backgroundExecution conflicts with backgroundExecutions' };
204
+ }
205
+ const only = workspaces.length === 1 ? workspaces[0] : undefined;
206
+ if (only === undefined) {
207
+ return {
208
+ error: 'install_manifest_malformed: legacy backgroundExecution cannot be attributed to a unique workspace',
209
+ };
210
+ }
211
+ records[only] = legacy.record;
212
+ }
213
+ return { records };
214
+ }
215
+ /**
216
+ * Set or clear ONE Workspace's ownership record, preserving every other
217
+ * Workspace's entry — the write-side half of "one migration never overwrites
218
+ * another Workspace's state". `record` must already satisfy the semantic
219
+ * contract (build it through the SPEC §8.4 state machine; absent record
220
+ * removes the entry and restores the legacy default for that Workspace).
221
+ */
222
+ export function setInstallManifestBackgroundExecution(manifest, target, record) {
223
+ const api = workspacePathApi(target.platform ?? process.platform);
224
+ const canonical = api.resolve(target.workspaceDir);
225
+ const next = { ...(manifest?.backgroundExecutions ?? {}) };
226
+ if (record === undefined)
227
+ delete next[canonical];
228
+ else
229
+ next[canonical] = record;
230
+ return next;
231
+ }
73
232
  export function parseInstallManifest(value, platform = process.platform) {
74
233
  if (!isRecord(value))
75
234
  return { error: 'install_manifest_malformed: expected an object' };
@@ -118,6 +277,9 @@ export function parseInstallManifest(value, platform = process.platform) {
118
277
  const workspaces = parseWorkspaceList(value.workspaces, platform);
119
278
  if (workspaces.error)
120
279
  return { error: workspaces.error };
280
+ const backgroundExecutions = parseBackgroundExecutions({ backgroundExecution: value.backgroundExecution, backgroundExecutions: value.backgroundExecutions }, workspaces.workspaces ?? [], platform);
281
+ if (backgroundExecutions.error)
282
+ return { error: backgroundExecutions.error };
121
283
  return {
122
284
  manifest: {
123
285
  layoutVersion: INSTALL_LAYOUT_VERSION,
@@ -125,6 +287,8 @@ export function parseInstallManifest(value, platform = process.platform) {
125
287
  hosts,
126
288
  ...(unknownHosts.length > 0 ? { unknownHosts } : {}),
127
289
  workspaces: workspaces.workspaces,
290
+ ...(Object.keys(backgroundExecutions.records ?? {}).length > 0
291
+ ? { backgroundExecutions: backgroundExecutions.records } : {}),
128
292
  },
129
293
  ...(warnings.length > 0 ? { warnings } : {}),
130
294
  };
@@ -320,7 +484,8 @@ export function getPdCliEntry(paths, mode) {
320
484
  * authority for "which PD home does this process own" — components must not
321
485
  * re-derive it locally.
322
486
  */
323
- export { PD_EXPERIMENT_ROOT_ENV, PD_OPENCLAW_HOME_ENV, PD_OPENCLAW_STATE_DIR_ENV, PD_CODEX_HOME_ENV, PD_WORKBUDDY_CONFIG_DIR_ENV, PD_HOST_WORKSPACE_DIR_NAME, PD_HOME_MODES, PD_HOME_FAILURE_REASONS, resolvePdHome, isPathWithinRoot, } from './pd-home.js';
487
+ export { PD_EXPERIMENT_ROOT_ENV, PD_OPENCLAW_HOME_ENV, PD_OPENCLAW_STATE_DIR_ENV, PD_CODEX_HOME_ENV, PD_WORKBUDDY_CONFIG_DIR_ENV, PD_HOST_WORKSPACE_DIR_NAME, PD_HOME_MODES, PD_HOME_FAILURE_REASONS, resolvePdHome, resolveRealUserHome, isPathWithinRoot, } from './pd-home.js';
488
+ export { ACTIVE_RELEASE_SCHEMA_VERSION, activeReleaseRecordPath, parseActiveReleaseRecord, readActiveReleaseRecord, } from './active-release.js';
324
489
  /**
325
490
  * Codex host-persistent binding location. The versioned payload directory is
326
491
  * REPLACED by a host cache refresh, taking any binding written inside it with