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 .changeset/structured-plan-semantics.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
"@openagentpack/sdk": patch
---

Classify Agent readiness from structured plan impact and changed paths instead of parsing display text.
1 change: 1 addition & 0 deletions .github/workflows/release.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -121,6 +121,7 @@ jobs:
registry-ready:
needs: [preflight, publish]
runs-on: ubuntu-latest
timeout-minutes: 20
permissions:
contents: read
steps:
Expand Down
10 changes: 10 additions & 0 deletions apps/server/openapi.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -803,6 +803,16 @@
"type": "string",
"enum": ["none", "local", "remote", "both"]
},
"readinessImpact": {
"type": "string",
"enum": ["none", "non_blocking", "blocking"]
},
"changedPaths": {
"type": "array",
"items": {
"type": "string"
}
},
"before": {
"type": "object",
"additionalProperties": {
Expand Down
3 changes: 3 additions & 0 deletions apps/webui/src/lib/api/generated/schema.d.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -298,6 +298,9 @@ export interface paths {
reason: string;
/** @enum {string} */
driftKind?: "none" | "local" | "remote" | "both";
/** @enum {string} */
readinessImpact?: "none" | "non_blocking" | "blocking";
changedPaths?: string[];
before?: {
[key: string]: unknown;
};
Expand Down
2 changes: 2 additions & 0 deletions packages/sdk/src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -192,6 +192,7 @@ export {
ListSessionsRequestSchema,
ListSessionsResponseSchema,
PlannedActionSchema,
PlanReadinessImpactSchema,
ResourceAddressSchema,
ResourceTypeSchema,
SendEventRequestSchema,
Expand DownExpand Up@@ -232,6 +233,7 @@ export type {
ListSessionsRequest,
ListSessionsResponse,
PlannedAction,
PlanReadinessImpact,
ResourceAddress,
ResourceType,
SendEventRequest,
Expand Down
4 changes: 1 addition & 3 deletions packages/sdk/src/internal/core/agent-runtime.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -474,9 +474,7 @@ function actionKey(action: PlannedAction): string {

function isNonBlockingAgentDrift(action: PlannedAction): boolean {
if (action.action === "no-op") return true;
if (action.action !== "update") return false;
const reason = action.reason.toLowerCase();
return reason.includes("metadata") || reason.includes("description");
return action.readinessImpact === "non_blocking";
}

export function collectAgentAddresses(config: ProjectConfig, agentName: string, provider?: string): ResourceAddress[] {
Expand Down
3 changes: 3 additions & 0 deletions packages/sdk/src/internal/core/resource-runtime.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
import { UserError } from "../errors.ts";
import { type ExecutionResult, executePlan } from "../executor/executor.ts";
import { getResourceDeclaration } from "../planner/declaration.ts";
import { buildReadinessBaseline } from "../planner/plan-semantics.ts";
import { buildPlan } from "../planner/planner.ts";
import { type RefreshResult, refreshState } from "../planner/refresh.ts";
import type { ExecutionPlan, PlannedAction } from "../types/plan.ts";
Expand DownExpand Up@@ -126,6 +128,7 @@ export async function importResource(
version: options.resourceVersion,
content_hash: contentHash,
desired_hash: contentHash,
desired_readiness_baseline: buildReadinessBaseline(getResourceDeclaration(address, ctx.config)),
};
ctx.state.setResource(resource);
await ctx.state.save();
Expand Down
4 changes: 4 additions & 0 deletions packages/sdk/src/internal/executor/executor.ts
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
import { dirname, resolve } from "node:path";
import { UserError } from "../errors.ts";
import { computeComparableDesiredHash } from "../planner/comparable.ts";
import { getResourceDeclaration } from "../planner/declaration.ts";
import { computeResourceHash } from "../planner/hasher.ts";
import { buildReadinessBaseline } from "../planner/plan-semantics.ts";
import { ApiError, ConflictError } from "../providers/base-client.ts";
import { readComparableIfSupported } from "../providers/drift-support.ts";
import type { RemoteResource } from "../providers/interface.ts";
Expand DownExpand Up@@ -454,8 +456,10 @@ async function executeAction(action: PlannedAction, provider: ResourceExecAdapte
content_hash: hash,
desired_hash: hash,
desired_comparable_hash: remoteHash,
desired_readiness_baseline: buildReadinessBaseline(getResourceDeclaration(address, ctx.config)),
remote_hash: remoteHash,
remote_snapshot: remoteSnapshot,
drift_paths: [],
drift_status: remoteHash ? "in_sync" : undefined,
});
return adopted;
Expand Down
72 changes: 72 additions & 0 deletions packages/sdk/src/internal/planner/plan-semantics.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
import type { ActionType, PlanReadinessImpact } from "../types/dto.ts";
import type { ResourceReadinessBaseline } from "../types/state.ts";
import { contentHash } from "../utils/hash.ts";

const NON_BLOCKING_ROOT_FIELDS = new Set(["description", "metadata"]);

/**
* Return stable, leaf-oriented paths whose values differ between two JSON-like
* resource snapshots. Arrays are treated atomically because their ordering is
* part of the declared resource semantics.
*/
export function diffChangedPaths(before: unknown, after: unknown, prefix = ""): string[] {
if (Object.is(before, after)) return [];
if (Array.isArray(before) || Array.isArray(after)) {
return structurallyEqual(before, after) ? [] : [prefix || "$root"];
}
if (isRecord(before) && isRecord(after)) {
const paths: string[] = [];
const keys = new Set([...Object.keys(before), ...Object.keys(after)]);
for (const key of [...keys].sort()) {
const path = prefix ? `${prefix}.${key}` : key;
paths.push(...diffChangedPaths(before[key], after[key], path));
}
return paths;
}
return [prefix || "$root"];
}

/**
* Classify whether an already-provisioned Agent Harness can keep running while
* a planned action is pending. Unknown changes are deliberately blocking.
*/
export function classifyReadinessImpact(
action: ActionType,
changedPaths: readonly string[] | undefined,
): PlanReadinessImpact {
if (action === "no-op") return "none";
if (action !== "update" || !changedPaths || changedPaths.length === 0) return "blocking";
return changedPaths.every(isNonBlockingPath) ? "non_blocking" : "blocking";
}

/** Store only irreversible hashes in state; declarations may contain secrets. */
export function buildReadinessBaseline(declaration: unknown): ResourceReadinessBaseline {
const record = isRecord(declaration) ? declaration : {};
const { description: _description, metadata: _metadata, ...operational } = record;
return {
operational_hash: contentHash(operational),
description_hash: contentHash(record.description ?? null),
metadata_hash: contentHash(record.metadata ?? null),
};
}

export function diffReadinessBaseline(before: ResourceReadinessBaseline, after: ResourceReadinessBaseline): string[] {
const paths: string[] = [];
if (before.operational_hash !== after.operational_hash) paths.push("$operational");
if (before.description_hash !== after.description_hash) paths.push("description");
if (before.metadata_hash !== after.metadata_hash) paths.push("metadata");
return paths;
}

function isNonBlockingPath(path: string): boolean {
const root = path.split(".", 1)[0];
return root !== undefined && NON_BLOCKING_ROOT_FIELDS.has(root);
}

function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}

function structurallyEqual(left: unknown, right: unknown): boolean {
return contentHash(left) === contentHash(right);
}
29 changes: 29 additions & 0 deletions packages/sdk/src/internal/planner/planner.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,9 @@ import type { ProjectConfig } from "../types/config.ts";
import type { ExecutionPlan, PlannedAction } from "../types/plan.ts";
import type { ResourceAddress, StateFile } from "../types/state.ts";
import { addressKey } from "../types/state.ts";
import { getResourceDeclaration } from "./declaration.ts";
import { computeResourceHash } from "./hasher.ts";
import { buildReadinessBaseline, classifyReadinessImpact, diffReadinessBaseline } from "./plan-semantics.ts";

export interface PlanOptions {
providers?: string[];
Expand DownExpand Up@@ -48,6 +50,7 @@ export async function buildPlan(
action: "create",
address,
driftKind: "none",
readinessImpact: "blocking",
reason: "Resource does not exist in state",
after: { content_hash: desiredHash },
dependencies: deps,
Expand All@@ -56,10 +59,13 @@ export async function buildPlan(
(existing.desired_hash ?? existing.content_hash) !== desiredHash &&
existing.drift_status === "drifted"
) {
const changedPaths = collectChangedPaths(address, config, existing, true);
actions.push({
action: "update",
address,
driftKind: "both",
readinessImpact: classifyReadinessImpact("update", changedPaths),
changedPaths,
reason: "Local config changed and remote drift detected",
before: {
content_hash: existing.desired_hash ?? existing.content_hash,
Expand All@@ -70,20 +76,26 @@ export async function buildPlan(
dependencies: deps,
});
} else if ((existing.desired_hash ?? existing.content_hash) !== desiredHash) {
const changedPaths = collectChangedPaths(address, config, existing, false);
actions.push({
action: "update",
address,
driftKind: "local",
readinessImpact: classifyReadinessImpact("update", changedPaths),
changedPaths,
reason: "Local config changed",
before: { content_hash: existing.desired_hash ?? existing.content_hash },
after: { content_hash: desiredHash },
dependencies: deps,
});
} else if (existing.drift_status === "drifted") {
const changedPaths = existing.drift_paths;
actions.push({
action: "update",
address,
driftKind: "remote",
readinessImpact: classifyReadinessImpact("update", changedPaths),
changedPaths,
reason: "Remote drift detected",
before: {
content_hash: existing.desired_hash ?? existing.content_hash,
Expand All@@ -98,6 +110,7 @@ export async function buildPlan(
action: "no-op",
address,
driftKind: "none",
readinessImpact: "none",
reason:
existing.drift_status === "unchecked"
? "No changes detected (remote content drift unchecked)"
Expand All@@ -116,6 +129,7 @@ export async function buildPlan(
action: "delete",
address: res.address,
driftKind: "none",
readinessImpact: "blocking",
reason: "Resource removed from configuration",
before: { content_hash: res.desired_hash ?? res.content_hash },
dependencies: [],
Expand All@@ -125,6 +139,21 @@ export async function buildPlan(
return { actions, diagnostics: diagnostics.getAll() };
}

function collectChangedPaths(
address: ResourceAddress,
config: ProjectConfig,
existing: StateFile["resources"][number],
includeRemote: boolean,
): string[] | undefined {
const current = buildReadinessBaseline(getResourceDeclaration(address, config));
const localPaths = existing.desired_readiness_baseline
? diffReadinessBaseline(existing.desired_readiness_baseline, current)
: undefined;
if (!includeRemote) return localPaths;
if (!localPaths && !existing.drift_paths) return undefined;
return [...new Set([...(localPaths ?? []), ...(existing.drift_paths ?? [])])].sort();
}

function getDependencies(address: ResourceAddress, graph: ReturnType<typeof buildDependencyGraph>): ResourceAddress[] {
const key = addressKey(address);
const depKeys = graph.edges.get(key) ?? new Set();
Expand Down
6 changes: 6 additions & 0 deletions packages/sdk/src/internal/planner/refresh.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,7 @@ import { emitRuntimeFeedback, type RuntimeFeedbackSink } from "../types/runtime-
import type { ResourceState } from "../types/state.ts";
import { contentHash } from "../utils/hash.ts";
import { getResourceDeclaration } from "./declaration.ts";
import { diffChangedPaths } from "./plan-semantics.ts";

export interface RefreshResult {
removed: ResourceState[];
Expand DownExpand Up@@ -75,6 +76,10 @@ export async function refreshState(
const desiredComparableHash = desiredComparable === null ? undefined : contentHash(desiredComparable);
const baselineHash = res.desired_comparable_hash ?? desiredComparableHash;
const driftStatus = baselineHash && remoteHash !== baselineHash ? "drifted" : "in_sync";
const driftPaths =
driftStatus === "drifted" && desiredComparable !== null
? diffChangedPaths(desiredComparable, remote.comparable)
: [];

state.setResource({
...res,
Expand All@@ -84,6 +89,7 @@ export async function refreshState(
desired_comparable_hash: res.desired_comparable_hash ?? desiredComparableHash,
remote_hash: remoteHash,
remote_snapshot: remote.snapshot ?? remote.comparable,
drift_paths: driftPaths,
drift_status: driftStatus,
});
dirty = true;
Expand Down
2 changes: 2 additions & 0 deletions packages/sdk/src/internal/state/state-manager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,8 +43,10 @@ export class StateManager implements IStateManager {
content_hash: ((r.content_hash ?? r.desired_hash) as string) ?? "",
desired_hash: ((r.desired_hash ?? r.content_hash) as string) ?? "",
desired_comparable_hash: r.desired_comparable_hash as string | undefined,
desired_readiness_baseline: r.desired_readiness_baseline as ResourceState["desired_readiness_baseline"],
remote_hash: r.remote_hash as string | undefined,
remote_snapshot: r.remote_snapshot,
drift_paths: r.drift_paths as string[] | undefined,
drift_status: r.drift_status as ResourceState["drift_status"],
}));
return new StateManager({ resources }, path);
Expand Down
5 changes: 5 additions & 0 deletions packages/sdk/src/internal/types/dto.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,11 +35,16 @@ export type ActionType = z.infer<typeof ActionTypeSchema>;
export const DriftKindSchema = z.enum(["none", "local", "remote", "both"]);
export type DriftKind = z.infer<typeof DriftKindSchema>;

export const PlanReadinessImpactSchema = z.enum(["none", "non_blocking", "blocking"]);
export type PlanReadinessImpact = z.infer<typeof PlanReadinessImpactSchema>;

export const PlannedActionSchema = z.object({
action: ActionTypeSchema,
address: ResourceAddressSchema,
reason: z.string(),
driftKind: DriftKindSchema.optional(),
readinessImpact: PlanReadinessImpactSchema.optional(),
changedPaths: z.array(z.string()).optional(),
before: z.record(z.string(), z.unknown()).optional(),
after: z.record(z.string(), z.unknown()).optional(),
dependencies: z.array(ResourceAddressSchema),
Expand Down
8 changes: 8 additions & 0 deletions packages/sdk/src/internal/types/state.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,11 +13,19 @@ export interface ResourceState {
content_hash: string;
desired_hash?: string;
desired_comparable_hash?: string;
desired_readiness_baseline?: ResourceReadinessBaseline;
remote_hash?: string;
remote_snapshot?: unknown;
drift_paths?: string[];
drift_status?: "in_sync" | "drifted" | "missing" | "unchecked";
}

export interface ResourceReadinessBaseline {
operational_hash: string;
description_hash: string;
metadata_hash: string;
}

export interface StateFile {
resources: ResourceState[];
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
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 .changeset/structured-plan-semantics.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
"@openagentpack/sdk": patch
---

Classify Agent readiness from structured plan impact and changed paths instead of parsing display text.
1 change: 1 addition & 0 deletions .github/workflows/release.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -121,6 +121,7 @@ jobs:
registry-ready:
needs: [preflight, publish]
runs-on: ubuntu-latest
timeout-minutes: 20
permissions:
contents: read
steps:
Expand Down
10 changes: 10 additions & 0 deletions apps/server/openapi.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -803,6 +803,16 @@
"type": "string",
"enum": ["none", "local", "remote", "both"]
},
"readinessImpact": {
"type": "string",
"enum": ["none", "non_blocking", "blocking"]
},
"changedPaths": {
"type": "array",
"items": {
"type": "string"
}
},
"before": {
"type": "object",
"additionalProperties": {
Expand Down
3 changes: 3 additions & 0 deletions apps/webui/src/lib/api/generated/schema.d.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -298,6 +298,9 @@ export interface paths {
reason: string;
/** @enum {string} */
driftKind?: "none" | "local" | "remote" | "both";
/** @enum {string} */
readinessImpact?: "none" | "non_blocking" | "blocking";
changedPaths?: string[];
before?: {
[key: string]: unknown;
};
Expand Down
2 changes: 2 additions & 0 deletions packages/sdk/src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -192,6 +192,7 @@ export {
ListSessionsRequestSchema,
ListSessionsResponseSchema,
PlannedActionSchema,
PlanReadinessImpactSchema,
ResourceAddressSchema,
ResourceTypeSchema,
SendEventRequestSchema,
Expand DownExpand Up@@ -232,6 +233,7 @@ export type {
ListSessionsRequest,
ListSessionsResponse,
PlannedAction,
PlanReadinessImpact,
ResourceAddress,
ResourceType,
SendEventRequest,
Expand Down
4 changes: 1 addition & 3 deletions packages/sdk/src/internal/core/agent-runtime.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -474,9 +474,7 @@ function actionKey(action: PlannedAction): string {

function isNonBlockingAgentDrift(action: PlannedAction): boolean {
if (action.action === "no-op") return true;
if (action.action !== "update") return false;
const reason = action.reason.toLowerCase();
return reason.includes("metadata") || reason.includes("description");
return action.readinessImpact === "non_blocking";
}

export function collectAgentAddresses(config: ProjectConfig, agentName: string, provider?: string): ResourceAddress[] {
Expand Down
3 changes: 3 additions & 0 deletions packages/sdk/src/internal/core/resource-runtime.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
import { UserError } from "../errors.ts";
import { type ExecutionResult, executePlan } from "../executor/executor.ts";
import { getResourceDeclaration } from "../planner/declaration.ts";
import { buildReadinessBaseline } from "../planner/plan-semantics.ts";
import { buildPlan } from "../planner/planner.ts";
import { type RefreshResult, refreshState } from "../planner/refresh.ts";
import type { ExecutionPlan, PlannedAction } from "../types/plan.ts";
Expand DownExpand Up@@ -126,6 +128,7 @@ export async function importResource(
version: options.resourceVersion,
content_hash: contentHash,
desired_hash: contentHash,
desired_readiness_baseline: buildReadinessBaseline(getResourceDeclaration(address, ctx.config)),
};
ctx.state.setResource(resource);
await ctx.state.save();
Expand Down
4 changes: 4 additions & 0 deletions packages/sdk/src/internal/executor/executor.ts
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
import { dirname, resolve } from "node:path";
import { UserError } from "../errors.ts";
import { computeComparableDesiredHash } from "../planner/comparable.ts";
import { getResourceDeclaration } from "../planner/declaration.ts";
import { computeResourceHash } from "../planner/hasher.ts";
import { buildReadinessBaseline } from "../planner/plan-semantics.ts";
import { ApiError, ConflictError } from "../providers/base-client.ts";
import { readComparableIfSupported } from "../providers/drift-support.ts";
import type { RemoteResource } from "../providers/interface.ts";
Expand DownExpand Up@@ -454,8 +456,10 @@ async function executeAction(action: PlannedAction, provider: ResourceExecAdapte
content_hash: hash,
desired_hash: hash,
desired_comparable_hash: remoteHash,
desired_readiness_baseline: buildReadinessBaseline(getResourceDeclaration(address, ctx.config)),
remote_hash: remoteHash,
remote_snapshot: remoteSnapshot,
drift_paths: [],
drift_status: remoteHash ? "in_sync" : undefined,
});
return adopted;
Expand Down
72 changes: 72 additions & 0 deletions packages/sdk/src/internal/planner/plan-semantics.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
import type { ActionType, PlanReadinessImpact } from "../types/dto.ts";
import type { ResourceReadinessBaseline } from "../types/state.ts";
import { contentHash } from "../utils/hash.ts";

const NON_BLOCKING_ROOT_FIELDS = new Set(["description", "metadata"]);

/**
* Return stable, leaf-oriented paths whose values differ between two JSON-like
* resource snapshots. Arrays are treated atomically because their ordering is
* part of the declared resource semantics.
*/
export function diffChangedPaths(before: unknown, after: unknown, prefix = ""): string[] {
if (Object.is(before, after)) return [];
if (Array.isArray(before) || Array.isArray(after)) {
return structurallyEqual(before, after) ? [] : [prefix || "$root"];
}
if (isRecord(before) && isRecord(after)) {
const paths: string[] = [];
const keys = new Set([...Object.keys(before), ...Object.keys(after)]);
for (const key of [...keys].sort()) {
const path = prefix ? `${prefix}.${key}` : key;
paths.push(...diffChangedPaths(before[key], after[key], path));
}
return paths;
}
return [prefix || "$root"];
}

/**
* Classify whether an already-provisioned Agent Harness can keep running while
* a planned action is pending. Unknown changes are deliberately blocking.
*/
export function classifyReadinessImpact(
action: ActionType,
changedPaths: readonly string[] | undefined,
): PlanReadinessImpact {
if (action === "no-op") return "none";
if (action !== "update" || !changedPaths || changedPaths.length === 0) return "blocking";
return changedPaths.every(isNonBlockingPath) ? "non_blocking" : "blocking";
}

/** Store only irreversible hashes in state; declarations may contain secrets. */
export function buildReadinessBaseline(declaration: unknown): ResourceReadinessBaseline {
const record = isRecord(declaration) ? declaration : {};
const { description: _description, metadata: _metadata, ...operational } = record;
return {
operational_hash: contentHash(operational),
description_hash: contentHash(record.description ?? null),
metadata_hash: contentHash(record.metadata ?? null),
};
}

export function diffReadinessBaseline(before: ResourceReadinessBaseline, after: ResourceReadinessBaseline): string[] {
const paths: string[] = [];
if (before.operational_hash !== after.operational_hash) paths.push("$operational");
if (before.description_hash !== after.description_hash) paths.push("description");
if (before.metadata_hash !== after.metadata_hash) paths.push("metadata");
return paths;
}

function isNonBlockingPath(path: string): boolean {
const root = path.split(".", 1)[0];
return root !== undefined && NON_BLOCKING_ROOT_FIELDS.has(root);
}

function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}

function structurallyEqual(left: unknown, right: unknown): boolean {
return contentHash(left) === contentHash(right);
}
29 changes: 29 additions & 0 deletions packages/sdk/src/internal/planner/planner.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,9 @@ import type { ProjectConfig } from "../types/config.ts";
import type { ExecutionPlan, PlannedAction } from "../types/plan.ts";
import type { ResourceAddress, StateFile } from "../types/state.ts";
import { addressKey } from "../types/state.ts";
import { getResourceDeclaration } from "./declaration.ts";
import { computeResourceHash } from "./hasher.ts";
import { buildReadinessBaseline, classifyReadinessImpact, diffReadinessBaseline } from "./plan-semantics.ts";

export interface PlanOptions {
providers?: string[];
Expand DownExpand Up@@ -48,6 +50,7 @@ export async function buildPlan(
action: "create",
address,
driftKind: "none",
readinessImpact: "blocking",
reason: "Resource does not exist in state",
after: { content_hash: desiredHash },
dependencies: deps,
Expand All@@ -56,10 +59,13 @@ export async function buildPlan(
(existing.desired_hash ?? existing.content_hash) !== desiredHash &&
existing.drift_status === "drifted"
) {
const changedPaths = collectChangedPaths(address, config, existing, true);
actions.push({
action: "update",
address,
driftKind: "both",
readinessImpact: classifyReadinessImpact("update", changedPaths),
changedPaths,
reason: "Local config changed and remote drift detected",
before: {
content_hash: existing.desired_hash ?? existing.content_hash,
Expand All@@ -70,20 +76,26 @@ export async function buildPlan(
dependencies: deps,
});
} else if ((existing.desired_hash ?? existing.content_hash) !== desiredHash) {
const changedPaths = collectChangedPaths(address, config, existing, false);
actions.push({
action: "update",
address,
driftKind: "local",
readinessImpact: classifyReadinessImpact("update", changedPaths),
changedPaths,
reason: "Local config changed",
before: { content_hash: existing.desired_hash ?? existing.content_hash },
after: { content_hash: desiredHash },
dependencies: deps,
});
} else if (existing.drift_status === "drifted") {
const changedPaths = existing.drift_paths;
actions.push({
action: "update",
address,
driftKind: "remote",
readinessImpact: classifyReadinessImpact("update", changedPaths),
changedPaths,
reason: "Remote drift detected",
before: {
content_hash: existing.desired_hash ?? existing.content_hash,
Expand All@@ -98,6 +110,7 @@ export async function buildPlan(
action: "no-op",
address,
driftKind: "none",
readinessImpact: "none",
reason:
existing.drift_status === "unchecked"
? "No changes detected (remote content drift unchecked)"
Expand All@@ -116,6 +129,7 @@ export async function buildPlan(
action: "delete",
address: res.address,
driftKind: "none",
readinessImpact: "blocking",
reason: "Resource removed from configuration",
before: { content_hash: res.desired_hash ?? res.content_hash },
dependencies: [],
Expand All@@ -125,6 +139,21 @@ export async function buildPlan(
return { actions, diagnostics: diagnostics.getAll() };
}

function collectChangedPaths(
address: ResourceAddress,
config: ProjectConfig,
existing: StateFile["resources"][number],
includeRemote: boolean,
): string[] | undefined {
const current = buildReadinessBaseline(getResourceDeclaration(address, config));
const localPaths = existing.desired_readiness_baseline
? diffReadinessBaseline(existing.desired_readiness_baseline, current)
: undefined;
if (!includeRemote) return localPaths;
if (!localPaths && !existing.drift_paths) return undefined;
return [...new Set([...(localPaths ?? []), ...(existing.drift_paths ?? [])])].sort();
}

function getDependencies(address: ResourceAddress, graph: ReturnType<typeof buildDependencyGraph>): ResourceAddress[] {
const key = addressKey(address);
const depKeys = graph.edges.get(key) ?? new Set();
Expand Down
6 changes: 6 additions & 0 deletions packages/sdk/src/internal/planner/refresh.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,7 @@ import { emitRuntimeFeedback, type RuntimeFeedbackSink } from "../types/runtime-
import type { ResourceState } from "../types/state.ts";
import { contentHash } from "../utils/hash.ts";
import { getResourceDeclaration } from "./declaration.ts";
import { diffChangedPaths } from "./plan-semantics.ts";

export interface RefreshResult {
removed: ResourceState[];
Expand DownExpand Up@@ -75,6 +76,10 @@ export async function refreshState(
const desiredComparableHash = desiredComparable === null ? undefined : contentHash(desiredComparable);
const baselineHash = res.desired_comparable_hash ?? desiredComparableHash;
const driftStatus = baselineHash && remoteHash !== baselineHash ? "drifted" : "in_sync";
const driftPaths =
driftStatus === "drifted" && desiredComparable !== null
? diffChangedPaths(desiredComparable, remote.comparable)
: [];

state.setResource({
...res,
Expand All@@ -84,6 +89,7 @@ export async function refreshState(
desired_comparable_hash: res.desired_comparable_hash ?? desiredComparableHash,
remote_hash: remoteHash,
remote_snapshot: remote.snapshot ?? remote.comparable,
drift_paths: driftPaths,
drift_status: driftStatus,
});
dirty = true;
Expand Down
2 changes: 2 additions & 0 deletions packages/sdk/src/internal/state/state-manager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,8 +43,10 @@ export class StateManager implements IStateManager {
content_hash: ((r.content_hash ?? r.desired_hash) as string) ?? "",
desired_hash: ((r.desired_hash ?? r.content_hash) as string) ?? "",
desired_comparable_hash: r.desired_comparable_hash as string | undefined,
desired_readiness_baseline: r.desired_readiness_baseline as ResourceState["desired_readiness_baseline"],
remote_hash: r.remote_hash as string | undefined,
remote_snapshot: r.remote_snapshot,
drift_paths: r.drift_paths as string[] | undefined,
drift_status: r.drift_status as ResourceState["drift_status"],
}));
return new StateManager({ resources }, path);
Expand Down
5 changes: 5 additions & 0 deletions packages/sdk/src/internal/types/dto.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,11 +35,16 @@ export type ActionType = z.infer<typeof ActionTypeSchema>;
export const DriftKindSchema = z.enum(["none", "local", "remote", "both"]);
export type DriftKind = z.infer<typeof DriftKindSchema>;

export const PlanReadinessImpactSchema = z.enum(["none", "non_blocking", "blocking"]);
export type PlanReadinessImpact = z.infer<typeof PlanReadinessImpactSchema>;

export const PlannedActionSchema = z.object({
action: ActionTypeSchema,
address: ResourceAddressSchema,
reason: z.string(),
driftKind: DriftKindSchema.optional(),
readinessImpact: PlanReadinessImpactSchema.optional(),
changedPaths: z.array(z.string()).optional(),
before: z.record(z.string(), z.unknown()).optional(),
after: z.record(z.string(), z.unknown()).optional(),
dependencies: z.array(ResourceAddressSchema),
Expand Down
8 changes: 8 additions & 0 deletions packages/sdk/src/internal/types/state.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,11 +13,19 @@ export interface ResourceState {
content_hash: string;
desired_hash?: string;
desired_comparable_hash?: string;
desired_readiness_baseline?: ResourceReadinessBaseline;
remote_hash?: string;
remote_snapshot?: unknown;
drift_paths?: string[];
drift_status?: "in_sync" | "drifted" | "missing" | "unchecked";
}

export interface ResourceReadinessBaseline {
operational_hash: string;
description_hash: string;
metadata_hash: string;
}

export interface StateFile {
resources: ResourceState[];
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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 .changeset/structured-plan-semantics.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
"@openagentpack/sdk": patch
---

Classify Agent readiness from structured plan impact and changed paths instead of parsing display text.
1 change: 1 addition & 0 deletions .github/workflows/release.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -121,6 +121,7 @@ jobs:
registry-ready:
needs: [preflight, publish]
runs-on: ubuntu-latest
timeout-minutes: 20
permissions:
contents: read
steps:
Expand Down
10 changes: 10 additions & 0 deletions apps/server/openapi.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -803,6 +803,16 @@
"type": "string",
"enum": ["none", "local", "remote", "both"]
},
"readinessImpact": {
"type": "string",
"enum": ["none", "non_blocking", "blocking"]
},
"changedPaths": {
"type": "array",
"items": {
"type": "string"
}
},
"before": {
"type": "object",
"additionalProperties": {
Expand Down
3 changes: 3 additions & 0 deletions apps/webui/src/lib/api/generated/schema.d.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -298,6 +298,9 @@ export interface paths {
reason: string;
/** @enum {string} */
driftKind?: "none" | "local" | "remote" | "both";
/** @enum {string} */
readinessImpact?: "none" | "non_blocking" | "blocking";
changedPaths?: string[];
before?: {
[key: string]: unknown;
};
Expand Down
2 changes: 2 additions & 0 deletions packages/sdk/src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -192,6 +192,7 @@ export {
ListSessionsRequestSchema,
ListSessionsResponseSchema,
PlannedActionSchema,
PlanReadinessImpactSchema,
ResourceAddressSchema,
ResourceTypeSchema,
SendEventRequestSchema,
Expand DownExpand Up@@ -232,6 +233,7 @@ export type {
ListSessionsRequest,
ListSessionsResponse,
PlannedAction,
PlanReadinessImpact,
ResourceAddress,
ResourceType,
SendEventRequest,
Expand Down
4 changes: 1 addition & 3 deletions packages/sdk/src/internal/core/agent-runtime.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -474,9 +474,7 @@ function actionKey(action: PlannedAction): string {

function isNonBlockingAgentDrift(action: PlannedAction): boolean {
if (action.action === "no-op") return true;
if (action.action !== "update") return false;
const reason = action.reason.toLowerCase();
return reason.includes("metadata") || reason.includes("description");
return action.readinessImpact === "non_blocking";
}

export function collectAgentAddresses(config: ProjectConfig, agentName: string, provider?: string): ResourceAddress[] {
Expand Down
3 changes: 3 additions & 0 deletions packages/sdk/src/internal/core/resource-runtime.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
import { UserError } from "../errors.ts";
import { type ExecutionResult, executePlan } from "../executor/executor.ts";
import { getResourceDeclaration } from "../planner/declaration.ts";
import { buildReadinessBaseline } from "../planner/plan-semantics.ts";
import { buildPlan } from "../planner/planner.ts";
import { type RefreshResult, refreshState } from "../planner/refresh.ts";
import type { ExecutionPlan, PlannedAction } from "../types/plan.ts";
Expand DownExpand Up@@ -126,6 +128,7 @@ export async function importResource(
version: options.resourceVersion,
content_hash: contentHash,
desired_hash: contentHash,
desired_readiness_baseline: buildReadinessBaseline(getResourceDeclaration(address, ctx.config)),
};
ctx.state.setResource(resource);
await ctx.state.save();
Expand Down
4 changes: 4 additions & 0 deletions packages/sdk/src/internal/executor/executor.ts
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
import { dirname, resolve } from "node:path";
import { UserError } from "../errors.ts";
import { computeComparableDesiredHash } from "../planner/comparable.ts";
import { getResourceDeclaration } from "../planner/declaration.ts";
import { computeResourceHash } from "../planner/hasher.ts";
import { buildReadinessBaseline } from "../planner/plan-semantics.ts";
import { ApiError, ConflictError } from "../providers/base-client.ts";
import { readComparableIfSupported } from "../providers/drift-support.ts";
import type { RemoteResource } from "../providers/interface.ts";
Expand DownExpand Up@@ -454,8 +456,10 @@ async function executeAction(action: PlannedAction, provider: ResourceExecAdapte
content_hash: hash,
desired_hash: hash,
desired_comparable_hash: remoteHash,
desired_readiness_baseline: buildReadinessBaseline(getResourceDeclaration(address, ctx.config)),
remote_hash: remoteHash,
remote_snapshot: remoteSnapshot,
drift_paths: [],
drift_status: remoteHash ? "in_sync" : undefined,
});
return adopted;
Expand Down
72 changes: 72 additions & 0 deletions packages/sdk/src/internal/planner/plan-semantics.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
import type { ActionType, PlanReadinessImpact } from "../types/dto.ts";
import type { ResourceReadinessBaseline } from "../types/state.ts";
import { contentHash } from "../utils/hash.ts";

const NON_BLOCKING_ROOT_FIELDS = new Set(["description", "metadata"]);

/**
* Return stable, leaf-oriented paths whose values differ between two JSON-like
* resource snapshots. Arrays are treated atomically because their ordering is
* part of the declared resource semantics.
*/
export function diffChangedPaths(before: unknown, after: unknown, prefix = ""): string[] {
if (Object.is(before, after)) return [];
if (Array.isArray(before) || Array.isArray(after)) {
return structurallyEqual(before, after) ? [] : [prefix || "$root"];
}
if (isRecord(before) && isRecord(after)) {
const paths: string[] = [];
const keys = new Set([...Object.keys(before), ...Object.keys(after)]);
for (const key of [...keys].sort()) {
const path = prefix ? `${prefix}.${key}` : key;
paths.push(...diffChangedPaths(before[key], after[key], path));
}
return paths;
}
return [prefix || "$root"];
}

/**
* Classify whether an already-provisioned Agent Harness can keep running while
* a planned action is pending. Unknown changes are deliberately blocking.
*/
export function classifyReadinessImpact(
action: ActionType,
changedPaths: readonly string[] | undefined,
): PlanReadinessImpact {
if (action === "no-op") return "none";
if (action !== "update" || !changedPaths || changedPaths.length === 0) return "blocking";
return changedPaths.every(isNonBlockingPath) ? "non_blocking" : "blocking";
}

/** Store only irreversible hashes in state; declarations may contain secrets. */
export function buildReadinessBaseline(declaration: unknown): ResourceReadinessBaseline {
const record = isRecord(declaration) ? declaration : {};
const { description: _description, metadata: _metadata, ...operational } = record;
return {
operational_hash: contentHash(operational),
description_hash: contentHash(record.description ?? null),
metadata_hash: contentHash(record.metadata ?? null),
};
}

export function diffReadinessBaseline(before: ResourceReadinessBaseline, after: ResourceReadinessBaseline): string[] {
const paths: string[] = [];
if (before.operational_hash !== after.operational_hash) paths.push("$operational");
if (before.description_hash !== after.description_hash) paths.push("description");
if (before.metadata_hash !== after.metadata_hash) paths.push("metadata");
return paths;
}

function isNonBlockingPath(path: string): boolean {
const root = path.split(".", 1)[0];
return root !== undefined && NON_BLOCKING_ROOT_FIELDS.has(root);
}

function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}

function structurallyEqual(left: unknown, right: unknown): boolean {
return contentHash(left) === contentHash(right);
}
29 changes: 29 additions & 0 deletions packages/sdk/src/internal/planner/planner.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,9 @@ import type { ProjectConfig } from "../types/config.ts";
import type { ExecutionPlan, PlannedAction } from "../types/plan.ts";
import type { ResourceAddress, StateFile } from "../types/state.ts";
import { addressKey } from "../types/state.ts";
import { getResourceDeclaration } from "./declaration.ts";
import { computeResourceHash } from "./hasher.ts";
import { buildReadinessBaseline, classifyReadinessImpact, diffReadinessBaseline } from "./plan-semantics.ts";

export interface PlanOptions {
providers?: string[];
Expand DownExpand Up@@ -48,6 +50,7 @@ export async function buildPlan(
action: "create",
address,
driftKind: "none",
readinessImpact: "blocking",
reason: "Resource does not exist in state",
after: { content_hash: desiredHash },
dependencies: deps,
Expand All@@ -56,10 +59,13 @@ export async function buildPlan(
(existing.desired_hash ?? existing.content_hash) !== desiredHash &&
existing.drift_status === "drifted"
) {
const changedPaths = collectChangedPaths(address, config, existing, true);
actions.push({
action: "update",
address,
driftKind: "both",
readinessImpact: classifyReadinessImpact("update", changedPaths),
changedPaths,
reason: "Local config changed and remote drift detected",
before: {
content_hash: existing.desired_hash ?? existing.content_hash,
Expand All@@ -70,20 +76,26 @@ export async function buildPlan(
dependencies: deps,
});
} else if ((existing.desired_hash ?? existing.content_hash) !== desiredHash) {
const changedPaths = collectChangedPaths(address, config, existing, false);
actions.push({
action: "update",
address,
driftKind: "local",
readinessImpact: classifyReadinessImpact("update", changedPaths),
changedPaths,
reason: "Local config changed",
before: { content_hash: existing.desired_hash ?? existing.content_hash },
after: { content_hash: desiredHash },
dependencies: deps,
});
} else if (existing.drift_status === "drifted") {
const changedPaths = existing.drift_paths;
actions.push({
action: "update",
address,
driftKind: "remote",
readinessImpact: classifyReadinessImpact("update", changedPaths),
changedPaths,
reason: "Remote drift detected",
before: {
content_hash: existing.desired_hash ?? existing.content_hash,
Expand All@@ -98,6 +110,7 @@ export async function buildPlan(
action: "no-op",
address,
driftKind: "none",
readinessImpact: "none",
reason:
existing.drift_status === "unchecked"
? "No changes detected (remote content drift unchecked)"
Expand All@@ -116,6 +129,7 @@ export async function buildPlan(
action: "delete",
address: res.address,
driftKind: "none",
readinessImpact: "blocking",
reason: "Resource removed from configuration",
before: { content_hash: res.desired_hash ?? res.content_hash },
dependencies: [],
Expand All@@ -125,6 +139,21 @@ export async function buildPlan(
return { actions, diagnostics: diagnostics.getAll() };
}

function collectChangedPaths(
address: ResourceAddress,
config: ProjectConfig,
existing: StateFile["resources"][number],
includeRemote: boolean,
): string[] | undefined {
const current = buildReadinessBaseline(getResourceDeclaration(address, config));
const localPaths = existing.desired_readiness_baseline
? diffReadinessBaseline(existing.desired_readiness_baseline, current)
: undefined;
if (!includeRemote) return localPaths;
if (!localPaths && !existing.drift_paths) return undefined;
return [...new Set([...(localPaths ?? []), ...(existing.drift_paths ?? [])])].sort();
}

function getDependencies(address: ResourceAddress, graph: ReturnType<typeof buildDependencyGraph>): ResourceAddress[] {
const key = addressKey(address);
const depKeys = graph.edges.get(key) ?? new Set();
Expand Down
6 changes: 6 additions & 0 deletions packages/sdk/src/internal/planner/refresh.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,7 @@ import { emitRuntimeFeedback, type RuntimeFeedbackSink } from "../types/runtime-
import type { ResourceState } from "../types/state.ts";
import { contentHash } from "../utils/hash.ts";
import { getResourceDeclaration } from "./declaration.ts";
import { diffChangedPaths } from "./plan-semantics.ts";

export interface RefreshResult {
removed: ResourceState[];
Expand DownExpand Up@@ -75,6 +76,10 @@ export async function refreshState(
const desiredComparableHash = desiredComparable === null ? undefined : contentHash(desiredComparable);
const baselineHash = res.desired_comparable_hash ?? desiredComparableHash;
const driftStatus = baselineHash && remoteHash !== baselineHash ? "drifted" : "in_sync";
const driftPaths =
driftStatus === "drifted" && desiredComparable !== null
? diffChangedPaths(desiredComparable, remote.comparable)
: [];

state.setResource({
...res,
Expand All@@ -84,6 +89,7 @@ export async function refreshState(
desired_comparable_hash: res.desired_comparable_hash ?? desiredComparableHash,
remote_hash: remoteHash,
remote_snapshot: remote.snapshot ?? remote.comparable,
drift_paths: driftPaths,
drift_status: driftStatus,
});
dirty = true;
Expand Down
2 changes: 2 additions & 0 deletions packages/sdk/src/internal/state/state-manager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,8 +43,10 @@ export class StateManager implements IStateManager {
content_hash: ((r.content_hash ?? r.desired_hash) as string) ?? "",
desired_hash: ((r.desired_hash ?? r.content_hash) as string) ?? "",
desired_comparable_hash: r.desired_comparable_hash as string | undefined,
desired_readiness_baseline: r.desired_readiness_baseline as ResourceState["desired_readiness_baseline"],
remote_hash: r.remote_hash as string | undefined,
remote_snapshot: r.remote_snapshot,
drift_paths: r.drift_paths as string[] | undefined,
drift_status: r.drift_status as ResourceState["drift_status"],
}));
return new StateManager({ resources }, path);
Expand Down
5 changes: 5 additions & 0 deletions packages/sdk/src/internal/types/dto.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,11 +35,16 @@ export type ActionType = z.infer<typeof ActionTypeSchema>;
export const DriftKindSchema = z.enum(["none", "local", "remote", "both"]);
export type DriftKind = z.infer<typeof DriftKindSchema>;

export const PlanReadinessImpactSchema = z.enum(["none", "non_blocking", "blocking"]);
export type PlanReadinessImpact = z.infer<typeof PlanReadinessImpactSchema>;

export const PlannedActionSchema = z.object({
action: ActionTypeSchema,
address: ResourceAddressSchema,
reason: z.string(),
driftKind: DriftKindSchema.optional(),
readinessImpact: PlanReadinessImpactSchema.optional(),
changedPaths: z.array(z.string()).optional(),
before: z.record(z.string(), z.unknown()).optional(),
after: z.record(z.string(), z.unknown()).optional(),
dependencies: z.array(ResourceAddressSchema),
Expand Down
8 changes: 8 additions & 0 deletions packages/sdk/src/internal/types/state.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,11 +13,19 @@ export interface ResourceState {
content_hash: string;
desired_hash?: string;
desired_comparable_hash?: string;
desired_readiness_baseline?: ResourceReadinessBaseline;
remote_hash?: string;
remote_snapshot?: unknown;
drift_paths?: string[];
drift_status?: "in_sync" | "drifted" | "missing" | "unchecked";
}

export interface ResourceReadinessBaseline {
operational_hash: string;
description_hash: string;
metadata_hash: string;
}

export interface StateFile {
resources: ResourceState[];
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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 .changeset/structured-plan-semantics.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
"@openagentpack/sdk": patch
---

Classify Agent readiness from structured plan impact and changed paths instead of parsing display text.
1 change: 1 addition & 0 deletions .github/workflows/release.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -121,6 +121,7 @@ jobs:
registry-ready:
needs: [preflight, publish]
runs-on: ubuntu-latest
timeout-minutes: 20
permissions:
contents: read
steps:
Expand Down
10 changes: 10 additions & 0 deletions apps/server/openapi.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -803,6 +803,16 @@
"type": "string",
"enum": ["none", "local", "remote", "both"]
},
"readinessImpact": {
"type": "string",
"enum": ["none", "non_blocking", "blocking"]
},
"changedPaths": {
"type": "array",
"items": {
"type": "string"
}
},
"before": {
"type": "object",
"additionalProperties": {
Expand Down
3 changes: 3 additions & 0 deletions apps/webui/src/lib/api/generated/schema.d.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -298,6 +298,9 @@ export interface paths {
reason: string;
/** @enum {string} */
driftKind?: "none" | "local" | "remote" | "both";
/** @enum {string} */
readinessImpact?: "none" | "non_blocking" | "blocking";
changedPaths?: string[];
before?: {
[key: string]: unknown;
};
Expand Down
2 changes: 2 additions & 0 deletions packages/sdk/src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -192,6 +192,7 @@ export {
ListSessionsRequestSchema,
ListSessionsResponseSchema,
PlannedActionSchema,
PlanReadinessImpactSchema,
ResourceAddressSchema,
ResourceTypeSchema,
SendEventRequestSchema,
Expand DownExpand Up@@ -232,6 +233,7 @@ export type {
ListSessionsRequest,
ListSessionsResponse,
PlannedAction,
PlanReadinessImpact,
ResourceAddress,
ResourceType,
SendEventRequest,
Expand Down
4 changes: 1 addition & 3 deletions packages/sdk/src/internal/core/agent-runtime.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -474,9 +474,7 @@ function actionKey(action: PlannedAction): string {

function isNonBlockingAgentDrift(action: PlannedAction): boolean {
if (action.action === "no-op") return true;
if (action.action !== "update") return false;
const reason = action.reason.toLowerCase();
return reason.includes("metadata") || reason.includes("description");
return action.readinessImpact === "non_blocking";
}

export function collectAgentAddresses(config: ProjectConfig, agentName: string, provider?: string): ResourceAddress[] {
Expand Down
3 changes: 3 additions & 0 deletions packages/sdk/src/internal/core/resource-runtime.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
import { UserError } from "../errors.ts";
import { type ExecutionResult, executePlan } from "../executor/executor.ts";
import { getResourceDeclaration } from "../planner/declaration.ts";
import { buildReadinessBaseline } from "../planner/plan-semantics.ts";
import { buildPlan } from "../planner/planner.ts";
import { type RefreshResult, refreshState } from "../planner/refresh.ts";
import type { ExecutionPlan, PlannedAction } from "../types/plan.ts";
Expand DownExpand Up@@ -126,6 +128,7 @@ export async function importResource(
version: options.resourceVersion,
content_hash: contentHash,
desired_hash: contentHash,
desired_readiness_baseline: buildReadinessBaseline(getResourceDeclaration(address, ctx.config)),
};
ctx.state.setResource(resource);
await ctx.state.save();
Expand Down
4 changes: 4 additions & 0 deletions packages/sdk/src/internal/executor/executor.ts
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
import { dirname, resolve } from "node:path";
import { UserError } from "../errors.ts";
import { computeComparableDesiredHash } from "../planner/comparable.ts";
import { getResourceDeclaration } from "../planner/declaration.ts";
import { computeResourceHash } from "../planner/hasher.ts";
import { buildReadinessBaseline } from "../planner/plan-semantics.ts";
import { ApiError, ConflictError } from "../providers/base-client.ts";
import { readComparableIfSupported } from "../providers/drift-support.ts";
import type { RemoteResource } from "../providers/interface.ts";
Expand DownExpand Up@@ -454,8 +456,10 @@ async function executeAction(action: PlannedAction, provider: ResourceExecAdapte
content_hash: hash,
desired_hash: hash,
desired_comparable_hash: remoteHash,
desired_readiness_baseline: buildReadinessBaseline(getResourceDeclaration(address, ctx.config)),
remote_hash: remoteHash,
remote_snapshot: remoteSnapshot,
drift_paths: [],
drift_status: remoteHash ? "in_sync" : undefined,
});
return adopted;
Expand Down
72 changes: 72 additions & 0 deletions packages/sdk/src/internal/planner/plan-semantics.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
import type { ActionType, PlanReadinessImpact } from "../types/dto.ts";
import type { ResourceReadinessBaseline } from "../types/state.ts";
import { contentHash } from "../utils/hash.ts";

const NON_BLOCKING_ROOT_FIELDS = new Set(["description", "metadata"]);

/**
* Return stable, leaf-oriented paths whose values differ between two JSON-like
* resource snapshots. Arrays are treated atomically because their ordering is
* part of the declared resource semantics.
*/
export function diffChangedPaths(before: unknown, after: unknown, prefix = ""): string[] {
if (Object.is(before, after)) return [];
if (Array.isArray(before) || Array.isArray(after)) {
return structurallyEqual(before, after) ? [] : [prefix || "$root"];
}
if (isRecord(before) && isRecord(after)) {
const paths: string[] = [];
const keys = new Set([...Object.keys(before), ...Object.keys(after)]);
for (const key of [...keys].sort()) {
const path = prefix ? `${prefix}.${key}` : key;
paths.push(...diffChangedPaths(before[key], after[key], path));
}
return paths;
}
return [prefix || "$root"];
}

/**
* Classify whether an already-provisioned Agent Harness can keep running while
* a planned action is pending. Unknown changes are deliberately blocking.
*/
export function classifyReadinessImpact(
action: ActionType,
changedPaths: readonly string[] | undefined,
): PlanReadinessImpact {
if (action === "no-op") return "none";
if (action !== "update" || !changedPaths || changedPaths.length === 0) return "blocking";
return changedPaths.every(isNonBlockingPath) ? "non_blocking" : "blocking";
}

/** Store only irreversible hashes in state; declarations may contain secrets. */
export function buildReadinessBaseline(declaration: unknown): ResourceReadinessBaseline {
const record = isRecord(declaration) ? declaration : {};
const { description: _description, metadata: _metadata, ...operational } = record;
return {
operational_hash: contentHash(operational),
description_hash: contentHash(record.description ?? null),
metadata_hash: contentHash(record.metadata ?? null),
};
}

export function diffReadinessBaseline(before: ResourceReadinessBaseline, after: ResourceReadinessBaseline): string[] {
const paths: string[] = [];
if (before.operational_hash !== after.operational_hash) paths.push("$operational");
if (before.description_hash !== after.description_hash) paths.push("description");
if (before.metadata_hash !== after.metadata_hash) paths.push("metadata");
return paths;
}

function isNonBlockingPath(path: string): boolean {
const root = path.split(".", 1)[0];
return root !== undefined && NON_BLOCKING_ROOT_FIELDS.has(root);
}

function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}

function structurallyEqual(left: unknown, right: unknown): boolean {
return contentHash(left) === contentHash(right);
}
29 changes: 29 additions & 0 deletions packages/sdk/src/internal/planner/planner.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,9 @@ import type { ProjectConfig } from "../types/config.ts";
import type { ExecutionPlan, PlannedAction } from "../types/plan.ts";
import type { ResourceAddress, StateFile } from "../types/state.ts";
import { addressKey } from "../types/state.ts";
import { getResourceDeclaration } from "./declaration.ts";
import { computeResourceHash } from "./hasher.ts";
import { buildReadinessBaseline, classifyReadinessImpact, diffReadinessBaseline } from "./plan-semantics.ts";

export interface PlanOptions {
providers?: string[];
Expand DownExpand Up@@ -48,6 +50,7 @@ export async function buildPlan(
action: "create",
address,
driftKind: "none",
readinessImpact: "blocking",
reason: "Resource does not exist in state",
after: { content_hash: desiredHash },
dependencies: deps,
Expand All@@ -56,10 +59,13 @@ export async function buildPlan(
(existing.desired_hash ?? existing.content_hash) !== desiredHash &&
existing.drift_status === "drifted"
) {
const changedPaths = collectChangedPaths(address, config, existing, true);
actions.push({
action: "update",
address,
driftKind: "both",
readinessImpact: classifyReadinessImpact("update", changedPaths),
changedPaths,
reason: "Local config changed and remote drift detected",
before: {
content_hash: existing.desired_hash ?? existing.content_hash,
Expand All@@ -70,20 +76,26 @@ export async function buildPlan(
dependencies: deps,
});
} else if ((existing.desired_hash ?? existing.content_hash) !== desiredHash) {
const changedPaths = collectChangedPaths(address, config, existing, false);
actions.push({
action: "update",
address,
driftKind: "local",
readinessImpact: classifyReadinessImpact("update", changedPaths),
changedPaths,
reason: "Local config changed",
before: { content_hash: existing.desired_hash ?? existing.content_hash },
after: { content_hash: desiredHash },
dependencies: deps,
});
} else if (existing.drift_status === "drifted") {
const changedPaths = existing.drift_paths;
actions.push({
action: "update",
address,
driftKind: "remote",
readinessImpact: classifyReadinessImpact("update", changedPaths),
changedPaths,
reason: "Remote drift detected",
before: {
content_hash: existing.desired_hash ?? existing.content_hash,
Expand All@@ -98,6 +110,7 @@ export async function buildPlan(
action: "no-op",
address,
driftKind: "none",
readinessImpact: "none",
reason:
existing.drift_status === "unchecked"
? "No changes detected (remote content drift unchecked)"
Expand All@@ -116,6 +129,7 @@ export async function buildPlan(
action: "delete",
address: res.address,
driftKind: "none",
readinessImpact: "blocking",
reason: "Resource removed from configuration",
before: { content_hash: res.desired_hash ?? res.content_hash },
dependencies: [],
Expand All@@ -125,6 +139,21 @@ export async function buildPlan(
return { actions, diagnostics: diagnostics.getAll() };
}

function collectChangedPaths(
address: ResourceAddress,
config: ProjectConfig,
existing: StateFile["resources"][number],
includeRemote: boolean,
): string[] | undefined {
const current = buildReadinessBaseline(getResourceDeclaration(address, config));
const localPaths = existing.desired_readiness_baseline
? diffReadinessBaseline(existing.desired_readiness_baseline, current)
: undefined;
if (!includeRemote) return localPaths;
if (!localPaths && !existing.drift_paths) return undefined;
return [...new Set([...(localPaths ?? []), ...(existing.drift_paths ?? [])])].sort();
}

function getDependencies(address: ResourceAddress, graph: ReturnType<typeof buildDependencyGraph>): ResourceAddress[] {
const key = addressKey(address);
const depKeys = graph.edges.get(key) ?? new Set();
Expand Down
6 changes: 6 additions & 0 deletions packages/sdk/src/internal/planner/refresh.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,7 @@ import { emitRuntimeFeedback, type RuntimeFeedbackSink } from "../types/runtime-
import type { ResourceState } from "../types/state.ts";
import { contentHash } from "../utils/hash.ts";
import { getResourceDeclaration } from "./declaration.ts";
import { diffChangedPaths } from "./plan-semantics.ts";

export interface RefreshResult {
removed: ResourceState[];
Expand DownExpand Up@@ -75,6 +76,10 @@ export async function refreshState(
const desiredComparableHash = desiredComparable === null ? undefined : contentHash(desiredComparable);
const baselineHash = res.desired_comparable_hash ?? desiredComparableHash;
const driftStatus = baselineHash && remoteHash !== baselineHash ? "drifted" : "in_sync";
const driftPaths =
driftStatus === "drifted" && desiredComparable !== null
? diffChangedPaths(desiredComparable, remote.comparable)
: [];

state.setResource({
...res,
Expand All@@ -84,6 +89,7 @@ export async function refreshState(
desired_comparable_hash: res.desired_comparable_hash ?? desiredComparableHash,
remote_hash: remoteHash,
remote_snapshot: remote.snapshot ?? remote.comparable,
drift_paths: driftPaths,
drift_status: driftStatus,
});
dirty = true;
Expand Down
2 changes: 2 additions & 0 deletions packages/sdk/src/internal/state/state-manager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,8 +43,10 @@ export class StateManager implements IStateManager {
content_hash: ((r.content_hash ?? r.desired_hash) as string) ?? "",
desired_hash: ((r.desired_hash ?? r.content_hash) as string) ?? "",
desired_comparable_hash: r.desired_comparable_hash as string | undefined,
desired_readiness_baseline: r.desired_readiness_baseline as ResourceState["desired_readiness_baseline"],
remote_hash: r.remote_hash as string | undefined,
remote_snapshot: r.remote_snapshot,
drift_paths: r.drift_paths as string[] | undefined,
drift_status: r.drift_status as ResourceState["drift_status"],
}));
return new StateManager({ resources }, path);
Expand Down
5 changes: 5 additions & 0 deletions packages/sdk/src/internal/types/dto.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,11 +35,16 @@ export type ActionType = z.infer<typeof ActionTypeSchema>;
export const DriftKindSchema = z.enum(["none", "local", "remote", "both"]);
export type DriftKind = z.infer<typeof DriftKindSchema>;

export const PlanReadinessImpactSchema = z.enum(["none", "non_blocking", "blocking"]);
export type PlanReadinessImpact = z.infer<typeof PlanReadinessImpactSchema>;

export const PlannedActionSchema = z.object({
action: ActionTypeSchema,
address: ResourceAddressSchema,
reason: z.string(),
driftKind: DriftKindSchema.optional(),
readinessImpact: PlanReadinessImpactSchema.optional(),
changedPaths: z.array(z.string()).optional(),
before: z.record(z.string(), z.unknown()).optional(),
after: z.record(z.string(), z.unknown()).optional(),
dependencies: z.array(ResourceAddressSchema),
Expand Down
8 changes: 8 additions & 0 deletions packages/sdk/src/internal/types/state.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,11 +13,19 @@ export interface ResourceState {
content_hash: string;
desired_hash?: string;
desired_comparable_hash?: string;
desired_readiness_baseline?: ResourceReadinessBaseline;
remote_hash?: string;
remote_snapshot?: unknown;
drift_paths?: string[];
drift_status?: "in_sync" | "drifted" | "missing" | "unchecked";
}

export interface ResourceReadinessBaseline {
operational_hash: string;
description_hash: string;
metadata_hash: string;
}

export interface StateFile {
resources: ResourceState[];
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
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 .changeset/structured-plan-semantics.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
"@openagentpack/sdk": patch
---

Classify Agent readiness from structured plan impact and changed paths instead of parsing display text.
1 change: 1 addition & 0 deletions .github/workflows/release.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -121,6 +121,7 @@ jobs:
registry-ready:
needs: [preflight, publish]
runs-on: ubuntu-latest
timeout-minutes: 20
permissions:
contents: read
steps:
Expand Down
10 changes: 10 additions & 0 deletions apps/server/openapi.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -803,6 +803,16 @@
"type": "string",
"enum": ["none", "local", "remote", "both"]
},
"readinessImpact": {
"type": "string",
"enum": ["none", "non_blocking", "blocking"]
},
"changedPaths": {
"type": "array",
"items": {
"type": "string"
}
},
"before": {
"type": "object",
"additionalProperties": {
Expand Down
3 changes: 3 additions & 0 deletions apps/webui/src/lib/api/generated/schema.d.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -298,6 +298,9 @@ export interface paths {
reason: string;
/** @enum {string} */
driftKind?: "none" | "local" | "remote" | "both";
/** @enum {string} */
readinessImpact?: "none" | "non_blocking" | "blocking";
changedPaths?: string[];
before?: {
[key: string]: unknown;
};
Expand Down
2 changes: 2 additions & 0 deletions packages/sdk/src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -192,6 +192,7 @@ export {
ListSessionsRequestSchema,
ListSessionsResponseSchema,
PlannedActionSchema,
PlanReadinessImpactSchema,
ResourceAddressSchema,
ResourceTypeSchema,
SendEventRequestSchema,
Expand DownExpand Up@@ -232,6 +233,7 @@ export type {
ListSessionsRequest,
ListSessionsResponse,
PlannedAction,
PlanReadinessImpact,
ResourceAddress,
ResourceType,
SendEventRequest,
Expand Down
4 changes: 1 addition & 3 deletions packages/sdk/src/internal/core/agent-runtime.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -474,9 +474,7 @@ function actionKey(action: PlannedAction): string {

function isNonBlockingAgentDrift(action: PlannedAction): boolean {
if (action.action === "no-op") return true;
if (action.action !== "update") return false;
const reason = action.reason.toLowerCase();
return reason.includes("metadata") || reason.includes("description");
return action.readinessImpact === "non_blocking";
}

export function collectAgentAddresses(config: ProjectConfig, agentName: string, provider?: string): ResourceAddress[] {
Expand Down
3 changes: 3 additions & 0 deletions packages/sdk/src/internal/core/resource-runtime.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
import { UserError } from "../errors.ts";
import { type ExecutionResult, executePlan } from "../executor/executor.ts";
import { getResourceDeclaration } from "../planner/declaration.ts";
import { buildReadinessBaseline } from "../planner/plan-semantics.ts";
import { buildPlan } from "../planner/planner.ts";
import { type RefreshResult, refreshState } from "../planner/refresh.ts";
import type { ExecutionPlan, PlannedAction } from "../types/plan.ts";
Expand DownExpand Up@@ -126,6 +128,7 @@ export async function importResource(
version: options.resourceVersion,
content_hash: contentHash,
desired_hash: contentHash,
desired_readiness_baseline: buildReadinessBaseline(getResourceDeclaration(address, ctx.config)),
};
ctx.state.setResource(resource);
await ctx.state.save();
Expand Down
4 changes: 4 additions & 0 deletions packages/sdk/src/internal/executor/executor.ts
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
import { dirname, resolve } from "node:path";
import { UserError } from "../errors.ts";
import { computeComparableDesiredHash } from "../planner/comparable.ts";
import { getResourceDeclaration } from "../planner/declaration.ts";
import { computeResourceHash } from "../planner/hasher.ts";
import { buildReadinessBaseline } from "../planner/plan-semantics.ts";
import { ApiError, ConflictError } from "../providers/base-client.ts";
import { readComparableIfSupported } from "../providers/drift-support.ts";
import type { RemoteResource } from "../providers/interface.ts";
Expand DownExpand Up@@ -454,8 +456,10 @@ async function executeAction(action: PlannedAction, provider: ResourceExecAdapte
content_hash: hash,
desired_hash: hash,
desired_comparable_hash: remoteHash,
desired_readiness_baseline: buildReadinessBaseline(getResourceDeclaration(address, ctx.config)),
remote_hash: remoteHash,
remote_snapshot: remoteSnapshot,
drift_paths: [],
drift_status: remoteHash ? "in_sync" : undefined,
});
return adopted;
Expand Down
72 changes: 72 additions & 0 deletions packages/sdk/src/internal/planner/plan-semantics.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
import type { ActionType, PlanReadinessImpact } from "../types/dto.ts";
import type { ResourceReadinessBaseline } from "../types/state.ts";
import { contentHash } from "../utils/hash.ts";

const NON_BLOCKING_ROOT_FIELDS = new Set(["description", "metadata"]);

/**
* Return stable, leaf-oriented paths whose values differ between two JSON-like
* resource snapshots. Arrays are treated atomically because their ordering is
* part of the declared resource semantics.
*/
export function diffChangedPaths(before: unknown, after: unknown, prefix = ""): string[] {
if (Object.is(before, after)) return [];
if (Array.isArray(before) || Array.isArray(after)) {
return structurallyEqual(before, after) ? [] : [prefix || "$root"];
}
if (isRecord(before) && isRecord(after)) {
const paths: string[] = [];
const keys = new Set([...Object.keys(before), ...Object.keys(after)]);
for (const key of [...keys].sort()) {
const path = prefix ? `${prefix}.${key}` : key;
paths.push(...diffChangedPaths(before[key], after[key], path));
}
return paths;
}
return [prefix || "$root"];
}

/**
* Classify whether an already-provisioned Agent Harness can keep running while
* a planned action is pending. Unknown changes are deliberately blocking.
*/
export function classifyReadinessImpact(
action: ActionType,
changedPaths: readonly string[] | undefined,
): PlanReadinessImpact {
if (action === "no-op") return "none";
if (action !== "update" || !changedPaths || changedPaths.length === 0) return "blocking";
return changedPaths.every(isNonBlockingPath) ? "non_blocking" : "blocking";
}

/** Store only irreversible hashes in state; declarations may contain secrets. */
export function buildReadinessBaseline(declaration: unknown): ResourceReadinessBaseline {
const record = isRecord(declaration) ? declaration : {};
const { description: _description, metadata: _metadata, ...operational } = record;
return {
operational_hash: contentHash(operational),
description_hash: contentHash(record.description ?? null),
metadata_hash: contentHash(record.metadata ?? null),
};
}

export function diffReadinessBaseline(before: ResourceReadinessBaseline, after: ResourceReadinessBaseline): string[] {
const paths: string[] = [];
if (before.operational_hash !== after.operational_hash) paths.push("$operational");
if (before.description_hash !== after.description_hash) paths.push("description");
if (before.metadata_hash !== after.metadata_hash) paths.push("metadata");
return paths;
}

function isNonBlockingPath(path: string): boolean {
const root = path.split(".", 1)[0];
return root !== undefined && NON_BLOCKING_ROOT_FIELDS.has(root);
}

function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}

function structurallyEqual(left: unknown, right: unknown): boolean {
return contentHash(left) === contentHash(right);
}
29 changes: 29 additions & 0 deletions packages/sdk/src/internal/planner/planner.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,9 @@ import type { ProjectConfig } from "../types/config.ts";
import type { ExecutionPlan, PlannedAction } from "../types/plan.ts";
import type { ResourceAddress, StateFile } from "../types/state.ts";
import { addressKey } from "../types/state.ts";
import { getResourceDeclaration } from "./declaration.ts";
import { computeResourceHash } from "./hasher.ts";
import { buildReadinessBaseline, classifyReadinessImpact, diffReadinessBaseline } from "./plan-semantics.ts";

export interface PlanOptions {
providers?: string[];
Expand DownExpand Up@@ -48,6 +50,7 @@ export async function buildPlan(
action: "create",
address,
driftKind: "none",
readinessImpact: "blocking",
reason: "Resource does not exist in state",
after: { content_hash: desiredHash },
dependencies: deps,
Expand All@@ -56,10 +59,13 @@ export async function buildPlan(
(existing.desired_hash ?? existing.content_hash) !== desiredHash &&
existing.drift_status === "drifted"
) {
const changedPaths = collectChangedPaths(address, config, existing, true);
actions.push({
action: "update",
address,
driftKind: "both",
readinessImpact: classifyReadinessImpact("update", changedPaths),
changedPaths,
reason: "Local config changed and remote drift detected",
before: {
content_hash: existing.desired_hash ?? existing.content_hash,
Expand All@@ -70,20 +76,26 @@ export async function buildPlan(
dependencies: deps,
});
} else if ((existing.desired_hash ?? existing.content_hash) !== desiredHash) {
const changedPaths = collectChangedPaths(address, config, existing, false);
actions.push({
action: "update",
address,
driftKind: "local",
readinessImpact: classifyReadinessImpact("update", changedPaths),
changedPaths,
reason: "Local config changed",
before: { content_hash: existing.desired_hash ?? existing.content_hash },
after: { content_hash: desiredHash },
dependencies: deps,
});
} else if (existing.drift_status === "drifted") {
const changedPaths = existing.drift_paths;
actions.push({
action: "update",
address,
driftKind: "remote",
readinessImpact: classifyReadinessImpact("update", changedPaths),
changedPaths,
reason: "Remote drift detected",
before: {
content_hash: existing.desired_hash ?? existing.content_hash,
Expand All@@ -98,6 +110,7 @@ export async function buildPlan(
action: "no-op",
address,
driftKind: "none",
readinessImpact: "none",
reason:
existing.drift_status === "unchecked"
? "No changes detected (remote content drift unchecked)"
Expand All@@ -116,6 +129,7 @@ export async function buildPlan(
action: "delete",
address: res.address,
driftKind: "none",
readinessImpact: "blocking",
reason: "Resource removed from configuration",
before: { content_hash: res.desired_hash ?? res.content_hash },
dependencies: [],
Expand All@@ -125,6 +139,21 @@ export async function buildPlan(
return { actions, diagnostics: diagnostics.getAll() };
}

function collectChangedPaths(
address: ResourceAddress,
config: ProjectConfig,
existing: StateFile["resources"][number],
includeRemote: boolean,
): string[] | undefined {
const current = buildReadinessBaseline(getResourceDeclaration(address, config));
const localPaths = existing.desired_readiness_baseline
? diffReadinessBaseline(existing.desired_readiness_baseline, current)
: undefined;
if (!includeRemote) return localPaths;
if (!localPaths && !existing.drift_paths) return undefined;
return [...new Set([...(localPaths ?? []), ...(existing.drift_paths ?? [])])].sort();
}

function getDependencies(address: ResourceAddress, graph: ReturnType<typeof buildDependencyGraph>): ResourceAddress[] {
const key = addressKey(address);
const depKeys = graph.edges.get(key) ?? new Set();
Expand Down
6 changes: 6 additions & 0 deletions packages/sdk/src/internal/planner/refresh.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,7 @@ import { emitRuntimeFeedback, type RuntimeFeedbackSink } from "../types/runtime-
import type { ResourceState } from "../types/state.ts";
import { contentHash } from "../utils/hash.ts";
import { getResourceDeclaration } from "./declaration.ts";
import { diffChangedPaths } from "./plan-semantics.ts";

export interface RefreshResult {
removed: ResourceState[];
Expand DownExpand Up@@ -75,6 +76,10 @@ export async function refreshState(
const desiredComparableHash = desiredComparable === null ? undefined : contentHash(desiredComparable);
const baselineHash = res.desired_comparable_hash ?? desiredComparableHash;
const driftStatus = baselineHash && remoteHash !== baselineHash ? "drifted" : "in_sync";
const driftPaths =
driftStatus === "drifted" && desiredComparable !== null
? diffChangedPaths(desiredComparable, remote.comparable)
: [];

state.setResource({
...res,
Expand All@@ -84,6 +89,7 @@ export async function refreshState(
desired_comparable_hash: res.desired_comparable_hash ?? desiredComparableHash,
remote_hash: remoteHash,
remote_snapshot: remote.snapshot ?? remote.comparable,
drift_paths: driftPaths,
drift_status: driftStatus,
});
dirty = true;
Expand Down
2 changes: 2 additions & 0 deletions packages/sdk/src/internal/state/state-manager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,8 +43,10 @@ export class StateManager implements IStateManager {
content_hash: ((r.content_hash ?? r.desired_hash) as string) ?? "",
desired_hash: ((r.desired_hash ?? r.content_hash) as string) ?? "",
desired_comparable_hash: r.desired_comparable_hash as string | undefined,
desired_readiness_baseline: r.desired_readiness_baseline as ResourceState["desired_readiness_baseline"],
remote_hash: r.remote_hash as string | undefined,
remote_snapshot: r.remote_snapshot,
drift_paths: r.drift_paths as string[] | undefined,
drift_status: r.drift_status as ResourceState["drift_status"],
}));
return new StateManager({ resources }, path);
Expand Down
5 changes: 5 additions & 0 deletions packages/sdk/src/internal/types/dto.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,11 +35,16 @@ export type ActionType = z.infer<typeof ActionTypeSchema>;
export const DriftKindSchema = z.enum(["none", "local", "remote", "both"]);
export type DriftKind = z.infer<typeof DriftKindSchema>;

export const PlanReadinessImpactSchema = z.enum(["none", "non_blocking", "blocking"]);
export type PlanReadinessImpact = z.infer<typeof PlanReadinessImpactSchema>;

export const PlannedActionSchema = z.object({
action: ActionTypeSchema,
address: ResourceAddressSchema,
reason: z.string(),
driftKind: DriftKindSchema.optional(),
readinessImpact: PlanReadinessImpactSchema.optional(),
changedPaths: z.array(z.string()).optional(),
before: z.record(z.string(), z.unknown()).optional(),
after: z.record(z.string(), z.unknown()).optional(),
dependencies: z.array(ResourceAddressSchema),
Expand Down
8 changes: 8 additions & 0 deletions packages/sdk/src/internal/types/state.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,11 +13,19 @@ export interface ResourceState {
content_hash: string;
desired_hash?: string;
desired_comparable_hash?: string;
desired_readiness_baseline?: ResourceReadinessBaseline;
remote_hash?: string;
remote_snapshot?: unknown;
drift_paths?: string[];
drift_status?: "in_sync" | "drifted" | "missing" | "unchecked";
}

export interface ResourceReadinessBaseline {
operational_hash: string;
description_hash: string;
metadata_hash: string;
}

export interface StateFile {
resources: ResourceState[];
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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 .changeset/structured-plan-semantics.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
"@openagentpack/sdk": patch
---

Classify Agent readiness from structured plan impact and changed paths instead of parsing display text.
1 change: 1 addition & 0 deletions .github/workflows/release.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -121,6 +121,7 @@ jobs:
registry-ready:
needs: [preflight, publish]
runs-on: ubuntu-latest
timeout-minutes: 20
permissions:
contents: read
steps:
Expand Down
10 changes: 10 additions & 0 deletions apps/server/openapi.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -803,6 +803,16 @@
"type": "string",
"enum": ["none", "local", "remote", "both"]
},
"readinessImpact": {
"type": "string",
"enum": ["none", "non_blocking", "blocking"]
},
"changedPaths": {
"type": "array",
"items": {
"type": "string"
}
},
"before": {
"type": "object",
"additionalProperties": {
Expand Down
3 changes: 3 additions & 0 deletions apps/webui/src/lib/api/generated/schema.d.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -298,6 +298,9 @@ export interface paths {
reason: string;
/** @enum {string} */
driftKind?: "none" | "local" | "remote" | "both";
/** @enum {string} */
readinessImpact?: "none" | "non_blocking" | "blocking";
changedPaths?: string[];
before?: {
[key: string]: unknown;
};
Expand Down
2 changes: 2 additions & 0 deletions packages/sdk/src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -192,6 +192,7 @@ export {
ListSessionsRequestSchema,
ListSessionsResponseSchema,
PlannedActionSchema,
PlanReadinessImpactSchema,
ResourceAddressSchema,
ResourceTypeSchema,
SendEventRequestSchema,
Expand DownExpand Up@@ -232,6 +233,7 @@ export type {
ListSessionsRequest,
ListSessionsResponse,
PlannedAction,
PlanReadinessImpact,
ResourceAddress,
ResourceType,
SendEventRequest,
Expand Down
4 changes: 1 addition & 3 deletions packages/sdk/src/internal/core/agent-runtime.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -474,9 +474,7 @@ function actionKey(action: PlannedAction): string {

function isNonBlockingAgentDrift(action: PlannedAction): boolean {
if (action.action === "no-op") return true;
if (action.action !== "update") return false;
const reason = action.reason.toLowerCase();
return reason.includes("metadata") || reason.includes("description");
return action.readinessImpact === "non_blocking";
}

export function collectAgentAddresses(config: ProjectConfig, agentName: string, provider?: string): ResourceAddress[] {
Expand Down
3 changes: 3 additions & 0 deletions packages/sdk/src/internal/core/resource-runtime.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
import { UserError } from "../errors.ts";
import { type ExecutionResult, executePlan } from "../executor/executor.ts";
import { getResourceDeclaration } from "../planner/declaration.ts";
import { buildReadinessBaseline } from "../planner/plan-semantics.ts";
import { buildPlan } from "../planner/planner.ts";
import { type RefreshResult, refreshState } from "../planner/refresh.ts";
import type { ExecutionPlan, PlannedAction } from "../types/plan.ts";
Expand DownExpand Up@@ -126,6 +128,7 @@ export async function importResource(
version: options.resourceVersion,
content_hash: contentHash,
desired_hash: contentHash,
desired_readiness_baseline: buildReadinessBaseline(getResourceDeclaration(address, ctx.config)),
};
ctx.state.setResource(resource);
await ctx.state.save();
Expand Down
4 changes: 4 additions & 0 deletions packages/sdk/src/internal/executor/executor.ts
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
import { dirname, resolve } from "node:path";
import { UserError } from "../errors.ts";
import { computeComparableDesiredHash } from "../planner/comparable.ts";
import { getResourceDeclaration } from "../planner/declaration.ts";
import { computeResourceHash } from "../planner/hasher.ts";
import { buildReadinessBaseline } from "../planner/plan-semantics.ts";
import { ApiError, ConflictError } from "../providers/base-client.ts";
import { readComparableIfSupported } from "../providers/drift-support.ts";
import type { RemoteResource } from "../providers/interface.ts";
Expand DownExpand Up@@ -454,8 +456,10 @@ async function executeAction(action: PlannedAction, provider: ResourceExecAdapte
content_hash: hash,
desired_hash: hash,
desired_comparable_hash: remoteHash,
desired_readiness_baseline: buildReadinessBaseline(getResourceDeclaration(address, ctx.config)),
remote_hash: remoteHash,
remote_snapshot: remoteSnapshot,
drift_paths: [],
drift_status: remoteHash ? "in_sync" : undefined,
});
return adopted;
Expand Down
72 changes: 72 additions & 0 deletions packages/sdk/src/internal/planner/plan-semantics.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
import type { ActionType, PlanReadinessImpact } from "../types/dto.ts";
import type { ResourceReadinessBaseline } from "../types/state.ts";
import { contentHash } from "../utils/hash.ts";

const NON_BLOCKING_ROOT_FIELDS = new Set(["description", "metadata"]);

/**
* Return stable, leaf-oriented paths whose values differ between two JSON-like
* resource snapshots. Arrays are treated atomically because their ordering is
* part of the declared resource semantics.
*/
export function diffChangedPaths(before: unknown, after: unknown, prefix = ""): string[] {
if (Object.is(before, after)) return [];
if (Array.isArray(before) || Array.isArray(after)) {
return structurallyEqual(before, after) ? [] : [prefix || "$root"];
}
if (isRecord(before) && isRecord(after)) {
const paths: string[] = [];
const keys = new Set([...Object.keys(before), ...Object.keys(after)]);
for (const key of [...keys].sort()) {
const path = prefix ? `${prefix}.${key}` : key;
paths.push(...diffChangedPaths(before[key], after[key], path));
}
return paths;
}
return [prefix || "$root"];
}

/**
* Classify whether an already-provisioned Agent Harness can keep running while
* a planned action is pending. Unknown changes are deliberately blocking.
*/
export function classifyReadinessImpact(
action: ActionType,
changedPaths: readonly string[] | undefined,
): PlanReadinessImpact {
if (action === "no-op") return "none";
if (action !== "update" || !changedPaths || changedPaths.length === 0) return "blocking";
return changedPaths.every(isNonBlockingPath) ? "non_blocking" : "blocking";
}

/** Store only irreversible hashes in state; declarations may contain secrets. */
export function buildReadinessBaseline(declaration: unknown): ResourceReadinessBaseline {
const record = isRecord(declaration) ? declaration : {};
const { description: _description, metadata: _metadata, ...operational } = record;
return {
operational_hash: contentHash(operational),
description_hash: contentHash(record.description ?? null),
metadata_hash: contentHash(record.metadata ?? null),
};
}

export function diffReadinessBaseline(before: ResourceReadinessBaseline, after: ResourceReadinessBaseline): string[] {
const paths: string[] = [];
if (before.operational_hash !== after.operational_hash) paths.push("$operational");
if (before.description_hash !== after.description_hash) paths.push("description");
if (before.metadata_hash !== after.metadata_hash) paths.push("metadata");
return paths;
}

function isNonBlockingPath(path: string): boolean {
const root = path.split(".", 1)[0];
return root !== undefined && NON_BLOCKING_ROOT_FIELDS.has(root);
}

function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}

function structurallyEqual(left: unknown, right: unknown): boolean {
return contentHash(left) === contentHash(right);
}
29 changes: 29 additions & 0 deletions packages/sdk/src/internal/planner/planner.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,9 @@ import type { ProjectConfig } from "../types/config.ts";
import type { ExecutionPlan, PlannedAction } from "../types/plan.ts";
import type { ResourceAddress, StateFile } from "../types/state.ts";
import { addressKey } from "../types/state.ts";
import { getResourceDeclaration } from "./declaration.ts";
import { computeResourceHash } from "./hasher.ts";
import { buildReadinessBaseline, classifyReadinessImpact, diffReadinessBaseline } from "./plan-semantics.ts";

export interface PlanOptions {
providers?: string[];
Expand DownExpand Up@@ -48,6 +50,7 @@ export async function buildPlan(
action: "create",
address,
driftKind: "none",
readinessImpact: "blocking",
reason: "Resource does not exist in state",
after: { content_hash: desiredHash },
dependencies: deps,
Expand All@@ -56,10 +59,13 @@ export async function buildPlan(
(existing.desired_hash ?? existing.content_hash) !== desiredHash &&
existing.drift_status === "drifted"
) {
const changedPaths = collectChangedPaths(address, config, existing, true);
actions.push({
action: "update",
address,
driftKind: "both",
readinessImpact: classifyReadinessImpact("update", changedPaths),
changedPaths,
reason: "Local config changed and remote drift detected",
before: {
content_hash: existing.desired_hash ?? existing.content_hash,
Expand All@@ -70,20 +76,26 @@ export async function buildPlan(
dependencies: deps,
});
} else if ((existing.desired_hash ?? existing.content_hash) !== desiredHash) {
const changedPaths = collectChangedPaths(address, config, existing, false);
actions.push({
action: "update",
address,
driftKind: "local",
readinessImpact: classifyReadinessImpact("update", changedPaths),
changedPaths,
reason: "Local config changed",
before: { content_hash: existing.desired_hash ?? existing.content_hash },
after: { content_hash: desiredHash },
dependencies: deps,
});
} else if (existing.drift_status === "drifted") {
const changedPaths = existing.drift_paths;
actions.push({
action: "update",
address,
driftKind: "remote",
readinessImpact: classifyReadinessImpact("update", changedPaths),
changedPaths,
reason: "Remote drift detected",
before: {
content_hash: existing.desired_hash ?? existing.content_hash,
Expand All@@ -98,6 +110,7 @@ export async function buildPlan(
action: "no-op",
address,
driftKind: "none",
readinessImpact: "none",
reason:
existing.drift_status === "unchecked"
? "No changes detected (remote content drift unchecked)"
Expand All@@ -116,6 +129,7 @@ export async function buildPlan(
action: "delete",
address: res.address,
driftKind: "none",
readinessImpact: "blocking",
reason: "Resource removed from configuration",
before: { content_hash: res.desired_hash ?? res.content_hash },
dependencies: [],
Expand All@@ -125,6 +139,21 @@ export async function buildPlan(
return { actions, diagnostics: diagnostics.getAll() };
}

function collectChangedPaths(
address: ResourceAddress,
config: ProjectConfig,
existing: StateFile["resources"][number],
includeRemote: boolean,
): string[] | undefined {
const current = buildReadinessBaseline(getResourceDeclaration(address, config));
const localPaths = existing.desired_readiness_baseline
? diffReadinessBaseline(existing.desired_readiness_baseline, current)
: undefined;
if (!includeRemote) return localPaths;
if (!localPaths && !existing.drift_paths) return undefined;
return [...new Set([...(localPaths ?? []), ...(existing.drift_paths ?? [])])].sort();
}

function getDependencies(address: ResourceAddress, graph: ReturnType<typeof buildDependencyGraph>): ResourceAddress[] {
const key = addressKey(address);
const depKeys = graph.edges.get(key) ?? new Set();
Expand Down
6 changes: 6 additions & 0 deletions packages/sdk/src/internal/planner/refresh.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,7 @@ import { emitRuntimeFeedback, type RuntimeFeedbackSink } from "../types/runtime-
import type { ResourceState } from "../types/state.ts";
import { contentHash } from "../utils/hash.ts";
import { getResourceDeclaration } from "./declaration.ts";
import { diffChangedPaths } from "./plan-semantics.ts";

export interface RefreshResult {
removed: ResourceState[];
Expand DownExpand Up@@ -75,6 +76,10 @@ export async function refreshState(
const desiredComparableHash = desiredComparable === null ? undefined : contentHash(desiredComparable);
const baselineHash = res.desired_comparable_hash ?? desiredComparableHash;
const driftStatus = baselineHash && remoteHash !== baselineHash ? "drifted" : "in_sync";
const driftPaths =
driftStatus === "drifted" && desiredComparable !== null
? diffChangedPaths(desiredComparable, remote.comparable)
: [];

state.setResource({
...res,
Expand All@@ -84,6 +89,7 @@ export async function refreshState(
desired_comparable_hash: res.desired_comparable_hash ?? desiredComparableHash,
remote_hash: remoteHash,
remote_snapshot: remote.snapshot ?? remote.comparable,
drift_paths: driftPaths,
drift_status: driftStatus,
});
dirty = true;
Expand Down
2 changes: 2 additions & 0 deletions packages/sdk/src/internal/state/state-manager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,8 +43,10 @@ export class StateManager implements IStateManager {
content_hash: ((r.content_hash ?? r.desired_hash) as string) ?? "",
desired_hash: ((r.desired_hash ?? r.content_hash) as string) ?? "",
desired_comparable_hash: r.desired_comparable_hash as string | undefined,
desired_readiness_baseline: r.desired_readiness_baseline as ResourceState["desired_readiness_baseline"],
remote_hash: r.remote_hash as string | undefined,
remote_snapshot: r.remote_snapshot,
drift_paths: r.drift_paths as string[] | undefined,
drift_status: r.drift_status as ResourceState["drift_status"],
}));
return new StateManager({ resources }, path);
Expand Down
5 changes: 5 additions & 0 deletions packages/sdk/src/internal/types/dto.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,11 +35,16 @@ export type ActionType = z.infer<typeof ActionTypeSchema>;
export const DriftKindSchema = z.enum(["none", "local", "remote", "both"]);
export type DriftKind = z.infer<typeof DriftKindSchema>;

export const PlanReadinessImpactSchema = z.enum(["none", "non_blocking", "blocking"]);
export type PlanReadinessImpact = z.infer<typeof PlanReadinessImpactSchema>;

export const PlannedActionSchema = z.object({
action: ActionTypeSchema,
address: ResourceAddressSchema,
reason: z.string(),
driftKind: DriftKindSchema.optional(),
readinessImpact: PlanReadinessImpactSchema.optional(),
changedPaths: z.array(z.string()).optional(),
before: z.record(z.string(), z.unknown()).optional(),
after: z.record(z.string(), z.unknown()).optional(),
dependencies: z.array(ResourceAddressSchema),
Expand Down
8 changes: 8 additions & 0 deletions packages/sdk/src/internal/types/state.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,11 +13,19 @@ export interface ResourceState {
content_hash: string;
desired_hash?: string;
desired_comparable_hash?: string;
desired_readiness_baseline?: ResourceReadinessBaseline;
remote_hash?: string;
remote_snapshot?: unknown;
drift_paths?: string[];
drift_status?: "in_sync" | "drifted" | "missing" | "unchecked";
}

export interface ResourceReadinessBaseline {
operational_hash: string;
description_hash: string;
metadata_hash: string;
}

export interface StateFile {
resources: ResourceState[];
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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 .changeset/structured-plan-semantics.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
"@openagentpack/sdk": patch
---

Classify Agent readiness from structured plan impact and changed paths instead of parsing display text.
1 change: 1 addition & 0 deletions .github/workflows/release.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -121,6 +121,7 @@ jobs:
registry-ready:
needs: [preflight, publish]
runs-on: ubuntu-latest
timeout-minutes: 20
permissions:
contents: read
steps:
Expand Down
10 changes: 10 additions & 0 deletions apps/server/openapi.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -803,6 +803,16 @@
"type": "string",
"enum": ["none", "local", "remote", "both"]
},
"readinessImpact": {
"type": "string",
"enum": ["none", "non_blocking", "blocking"]
},
"changedPaths": {
"type": "array",
"items": {
"type": "string"
}
},
"before": {
"type": "object",
"additionalProperties": {
Expand Down
3 changes: 3 additions & 0 deletions apps/webui/src/lib/api/generated/schema.d.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -298,6 +298,9 @@ export interface paths {
reason: string;
/** @enum {string} */
driftKind?: "none" | "local" | "remote" | "both";
/** @enum {string} */
readinessImpact?: "none" | "non_blocking" | "blocking";
changedPaths?: string[];
before?: {
[key: string]: unknown;
};
Expand Down
2 changes: 2 additions & 0 deletions packages/sdk/src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -192,6 +192,7 @@ export {
ListSessionsRequestSchema,
ListSessionsResponseSchema,
PlannedActionSchema,
PlanReadinessImpactSchema,
ResourceAddressSchema,
ResourceTypeSchema,
SendEventRequestSchema,
Expand DownExpand Up@@ -232,6 +233,7 @@ export type {
ListSessionsRequest,
ListSessionsResponse,
PlannedAction,
PlanReadinessImpact,
ResourceAddress,
ResourceType,
SendEventRequest,
Expand Down
4 changes: 1 addition & 3 deletions packages/sdk/src/internal/core/agent-runtime.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -474,9 +474,7 @@ function actionKey(action: PlannedAction): string {

function isNonBlockingAgentDrift(action: PlannedAction): boolean {
if (action.action === "no-op") return true;
if (action.action !== "update") return false;
const reason = action.reason.toLowerCase();
return reason.includes("metadata") || reason.includes("description");
return action.readinessImpact === "non_blocking";
}

export function collectAgentAddresses(config: ProjectConfig, agentName: string, provider?: string): ResourceAddress[] {
Expand Down
3 changes: 3 additions & 0 deletions packages/sdk/src/internal/core/resource-runtime.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
import { UserError } from "../errors.ts";
import { type ExecutionResult, executePlan } from "../executor/executor.ts";
import { getResourceDeclaration } from "../planner/declaration.ts";
import { buildReadinessBaseline } from "../planner/plan-semantics.ts";
import { buildPlan } from "../planner/planner.ts";
import { type RefreshResult, refreshState } from "../planner/refresh.ts";
import type { ExecutionPlan, PlannedAction } from "../types/plan.ts";
Expand DownExpand Up@@ -126,6 +128,7 @@ export async function importResource(
version: options.resourceVersion,
content_hash: contentHash,
desired_hash: contentHash,
desired_readiness_baseline: buildReadinessBaseline(getResourceDeclaration(address, ctx.config)),
};
ctx.state.setResource(resource);
await ctx.state.save();
Expand Down
4 changes: 4 additions & 0 deletions packages/sdk/src/internal/executor/executor.ts
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
import { dirname, resolve } from "node:path";
import { UserError } from "../errors.ts";
import { computeComparableDesiredHash } from "../planner/comparable.ts";
import { getResourceDeclaration } from "../planner/declaration.ts";
import { computeResourceHash } from "../planner/hasher.ts";
import { buildReadinessBaseline } from "../planner/plan-semantics.ts";
import { ApiError, ConflictError } from "../providers/base-client.ts";
import { readComparableIfSupported } from "../providers/drift-support.ts";
import type { RemoteResource } from "../providers/interface.ts";
Expand DownExpand Up@@ -454,8 +456,10 @@ async function executeAction(action: PlannedAction, provider: ResourceExecAdapte
content_hash: hash,
desired_hash: hash,
desired_comparable_hash: remoteHash,
desired_readiness_baseline: buildReadinessBaseline(getResourceDeclaration(address, ctx.config)),
remote_hash: remoteHash,
remote_snapshot: remoteSnapshot,
drift_paths: [],
drift_status: remoteHash ? "in_sync" : undefined,
});
return adopted;
Expand Down
72 changes: 72 additions & 0 deletions packages/sdk/src/internal/planner/plan-semantics.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
import type { ActionType, PlanReadinessImpact } from "../types/dto.ts";
import type { ResourceReadinessBaseline } from "../types/state.ts";
import { contentHash } from "../utils/hash.ts";

const NON_BLOCKING_ROOT_FIELDS = new Set(["description", "metadata"]);

/**
* Return stable, leaf-oriented paths whose values differ between two JSON-like
* resource snapshots. Arrays are treated atomically because their ordering is
* part of the declared resource semantics.
*/
export function diffChangedPaths(before: unknown, after: unknown, prefix = ""): string[] {
if (Object.is(before, after)) return [];
if (Array.isArray(before) || Array.isArray(after)) {
return structurallyEqual(before, after) ? [] : [prefix || "$root"];
}
if (isRecord(before) && isRecord(after)) {
const paths: string[] = [];
const keys = new Set([...Object.keys(before), ...Object.keys(after)]);
for (const key of [...keys].sort()) {
const path = prefix ? `${prefix}.${key}` : key;
paths.push(...diffChangedPaths(before[key], after[key], path));
}
return paths;
}
return [prefix || "$root"];
}

/**
* Classify whether an already-provisioned Agent Harness can keep running while
* a planned action is pending. Unknown changes are deliberately blocking.
*/
export function classifyReadinessImpact(
action: ActionType,
changedPaths: readonly string[] | undefined,
): PlanReadinessImpact {
if (action === "no-op") return "none";
if (action !== "update" || !changedPaths || changedPaths.length === 0) return "blocking";
return changedPaths.every(isNonBlockingPath) ? "non_blocking" : "blocking";
}

/** Store only irreversible hashes in state; declarations may contain secrets. */
export function buildReadinessBaseline(declaration: unknown): ResourceReadinessBaseline {
const record = isRecord(declaration) ? declaration : {};
const { description: _description, metadata: _metadata, ...operational } = record;
return {
operational_hash: contentHash(operational),
description_hash: contentHash(record.description ?? null),
metadata_hash: contentHash(record.metadata ?? null),
};
}

export function diffReadinessBaseline(before: ResourceReadinessBaseline, after: ResourceReadinessBaseline): string[] {
const paths: string[] = [];
if (before.operational_hash !== after.operational_hash) paths.push("$operational");
if (before.description_hash !== after.description_hash) paths.push("description");
if (before.metadata_hash !== after.metadata_hash) paths.push("metadata");
return paths;
}

function isNonBlockingPath(path: string): boolean {
const root = path.split(".", 1)[0];
return root !== undefined && NON_BLOCKING_ROOT_FIELDS.has(root);
}

function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}

function structurallyEqual(left: unknown, right: unknown): boolean {
return contentHash(left) === contentHash(right);
}
29 changes: 29 additions & 0 deletions packages/sdk/src/internal/planner/planner.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,9 @@ import type { ProjectConfig } from "../types/config.ts";
import type { ExecutionPlan, PlannedAction } from "../types/plan.ts";
import type { ResourceAddress, StateFile } from "../types/state.ts";
import { addressKey } from "../types/state.ts";
import { getResourceDeclaration } from "./declaration.ts";
import { computeResourceHash } from "./hasher.ts";
import { buildReadinessBaseline, classifyReadinessImpact, diffReadinessBaseline } from "./plan-semantics.ts";

export interface PlanOptions {
providers?: string[];
Expand DownExpand Up@@ -48,6 +50,7 @@ export async function buildPlan(
action: "create",
address,
driftKind: "none",
readinessImpact: "blocking",
reason: "Resource does not exist in state",
after: { content_hash: desiredHash },
dependencies: deps,
Expand All@@ -56,10 +59,13 @@ export async function buildPlan(
(existing.desired_hash ?? existing.content_hash) !== desiredHash &&
existing.drift_status === "drifted"
) {
const changedPaths = collectChangedPaths(address, config, existing, true);
actions.push({
action: "update",
address,
driftKind: "both",
readinessImpact: classifyReadinessImpact("update", changedPaths),
changedPaths,
reason: "Local config changed and remote drift detected",
before: {
content_hash: existing.desired_hash ?? existing.content_hash,
Expand All@@ -70,20 +76,26 @@ export async function buildPlan(
dependencies: deps,
});
} else if ((existing.desired_hash ?? existing.content_hash) !== desiredHash) {
const changedPaths = collectChangedPaths(address, config, existing, false);
actions.push({
action: "update",
address,
driftKind: "local",
readinessImpact: classifyReadinessImpact("update", changedPaths),
changedPaths,
reason: "Local config changed",
before: { content_hash: existing.desired_hash ?? existing.content_hash },
after: { content_hash: desiredHash },
dependencies: deps,
});
} else if (existing.drift_status === "drifted") {
const changedPaths = existing.drift_paths;
actions.push({
action: "update",
address,
driftKind: "remote",
readinessImpact: classifyReadinessImpact("update", changedPaths),
changedPaths,
reason: "Remote drift detected",
before: {
content_hash: existing.desired_hash ?? existing.content_hash,
Expand All@@ -98,6 +110,7 @@ export async function buildPlan(
action: "no-op",
address,
driftKind: "none",
readinessImpact: "none",
reason:
existing.drift_status === "unchecked"
? "No changes detected (remote content drift unchecked)"
Expand All@@ -116,6 +129,7 @@ export async function buildPlan(
action: "delete",
address: res.address,
driftKind: "none",
readinessImpact: "blocking",
reason: "Resource removed from configuration",
before: { content_hash: res.desired_hash ?? res.content_hash },
dependencies: [],
Expand All@@ -125,6 +139,21 @@ export async function buildPlan(
return { actions, diagnostics: diagnostics.getAll() };
}

function collectChangedPaths(
address: ResourceAddress,
config: ProjectConfig,
existing: StateFile["resources"][number],
includeRemote: boolean,
): string[] | undefined {
const current = buildReadinessBaseline(getResourceDeclaration(address, config));
const localPaths = existing.desired_readiness_baseline
? diffReadinessBaseline(existing.desired_readiness_baseline, current)
: undefined;
if (!includeRemote) return localPaths;
if (!localPaths && !existing.drift_paths) return undefined;
return [...new Set([...(localPaths ?? []), ...(existing.drift_paths ?? [])])].sort();
}

function getDependencies(address: ResourceAddress, graph: ReturnType<typeof buildDependencyGraph>): ResourceAddress[] {
const key = addressKey(address);
const depKeys = graph.edges.get(key) ?? new Set();
Expand Down
6 changes: 6 additions & 0 deletions packages/sdk/src/internal/planner/refresh.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,7 @@ import { emitRuntimeFeedback, type RuntimeFeedbackSink } from "../types/runtime-
import type { ResourceState } from "../types/state.ts";
import { contentHash } from "../utils/hash.ts";
import { getResourceDeclaration } from "./declaration.ts";
import { diffChangedPaths } from "./plan-semantics.ts";

export interface RefreshResult {
removed: ResourceState[];
Expand DownExpand Up@@ -75,6 +76,10 @@ export async function refreshState(
const desiredComparableHash = desiredComparable === null ? undefined : contentHash(desiredComparable);
const baselineHash = res.desired_comparable_hash ?? desiredComparableHash;
const driftStatus = baselineHash && remoteHash !== baselineHash ? "drifted" : "in_sync";
const driftPaths =
driftStatus === "drifted" && desiredComparable !== null
? diffChangedPaths(desiredComparable, remote.comparable)
: [];

state.setResource({
...res,
Expand All@@ -84,6 +89,7 @@ export async function refreshState(
desired_comparable_hash: res.desired_comparable_hash ?? desiredComparableHash,
remote_hash: remoteHash,
remote_snapshot: remote.snapshot ?? remote.comparable,
drift_paths: driftPaths,
drift_status: driftStatus,
});
dirty = true;
Expand Down
2 changes: 2 additions & 0 deletions packages/sdk/src/internal/state/state-manager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,8 +43,10 @@ export class StateManager implements IStateManager {
content_hash: ((r.content_hash ?? r.desired_hash) as string) ?? "",
desired_hash: ((r.desired_hash ?? r.content_hash) as string) ?? "",
desired_comparable_hash: r.desired_comparable_hash as string | undefined,
desired_readiness_baseline: r.desired_readiness_baseline as ResourceState["desired_readiness_baseline"],
remote_hash: r.remote_hash as string | undefined,
remote_snapshot: r.remote_snapshot,
drift_paths: r.drift_paths as string[] | undefined,
drift_status: r.drift_status as ResourceState["drift_status"],
}));
return new StateManager({ resources }, path);
Expand Down
5 changes: 5 additions & 0 deletions packages/sdk/src/internal/types/dto.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,11 +35,16 @@ export type ActionType = z.infer<typeof ActionTypeSchema>;
export const DriftKindSchema = z.enum(["none", "local", "remote", "both"]);
export type DriftKind = z.infer<typeof DriftKindSchema>;

export const PlanReadinessImpactSchema = z.enum(["none", "non_blocking", "blocking"]);
export type PlanReadinessImpact = z.infer<typeof PlanReadinessImpactSchema>;

export const PlannedActionSchema = z.object({
action: ActionTypeSchema,
address: ResourceAddressSchema,
reason: z.string(),
driftKind: DriftKindSchema.optional(),
readinessImpact: PlanReadinessImpactSchema.optional(),
changedPaths: z.array(z.string()).optional(),
before: z.record(z.string(), z.unknown()).optional(),
after: z.record(z.string(), z.unknown()).optional(),
dependencies: z.array(ResourceAddressSchema),
Expand Down
8 changes: 8 additions & 0 deletions packages/sdk/src/internal/types/state.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,11 +13,19 @@ export interface ResourceState {
content_hash: string;
desired_hash?: string;
desired_comparable_hash?: string;
desired_readiness_baseline?: ResourceReadinessBaseline;
remote_hash?: string;
remote_snapshot?: unknown;
drift_paths?: string[];
drift_status?: "in_sync" | "drifted" | "missing" | "unchecked";
}

export interface ResourceReadinessBaseline {
operational_hash: string;
description_hash: string;
metadata_hash: string;
}

export interface StateFile {
resources: ResourceState[];
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
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 .changeset/structured-plan-semantics.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
"@openagentpack/sdk": patch
---

Classify Agent readiness from structured plan impact and changed paths instead of parsing display text.
1 change: 1 addition & 0 deletions .github/workflows/release.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -121,6 +121,7 @@ jobs:
registry-ready:
needs: [preflight, publish]
runs-on: ubuntu-latest
timeout-minutes: 20
permissions:
contents: read
steps:
Expand Down
10 changes: 10 additions & 0 deletions apps/server/openapi.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -803,6 +803,16 @@
"type": "string",
"enum": ["none", "local", "remote", "both"]
},
"readinessImpact": {
"type": "string",
"enum": ["none", "non_blocking", "blocking"]
},
"changedPaths": {
"type": "array",
"items": {
"type": "string"
}
},
"before": {
"type": "object",
"additionalProperties": {
Expand Down
3 changes: 3 additions & 0 deletions apps/webui/src/lib/api/generated/schema.d.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -298,6 +298,9 @@ export interface paths {
reason: string;
/** @enum {string} */
driftKind?: "none" | "local" | "remote" | "both";
/** @enum {string} */
readinessImpact?: "none" | "non_blocking" | "blocking";
changedPaths?: string[];
before?: {
[key: string]: unknown;
};
Expand Down
2 changes: 2 additions & 0 deletions packages/sdk/src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -192,6 +192,7 @@ export {
ListSessionsRequestSchema,
ListSessionsResponseSchema,
PlannedActionSchema,
PlanReadinessImpactSchema,
ResourceAddressSchema,
ResourceTypeSchema,
SendEventRequestSchema,
Expand DownExpand Up@@ -232,6 +233,7 @@ export type {
ListSessionsRequest,
ListSessionsResponse,
PlannedAction,
PlanReadinessImpact,
ResourceAddress,
ResourceType,
SendEventRequest,
Expand Down
4 changes: 1 addition & 3 deletions packages/sdk/src/internal/core/agent-runtime.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -474,9 +474,7 @@ function actionKey(action: PlannedAction): string {

function isNonBlockingAgentDrift(action: PlannedAction): boolean {
if (action.action === "no-op") return true;
if (action.action !== "update") return false;
const reason = action.reason.toLowerCase();
return reason.includes("metadata") || reason.includes("description");
return action.readinessImpact === "non_blocking";
}

export function collectAgentAddresses(config: ProjectConfig, agentName: string, provider?: string): ResourceAddress[] {
Expand Down
3 changes: 3 additions & 0 deletions packages/sdk/src/internal/core/resource-runtime.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
import { UserError } from "../errors.ts";
import { type ExecutionResult, executePlan } from "../executor/executor.ts";
import { getResourceDeclaration } from "../planner/declaration.ts";
import { buildReadinessBaseline } from "../planner/plan-semantics.ts";
import { buildPlan } from "../planner/planner.ts";
import { type RefreshResult, refreshState } from "../planner/refresh.ts";
import type { ExecutionPlan, PlannedAction } from "../types/plan.ts";
Expand DownExpand Up@@ -126,6 +128,7 @@ export async function importResource(
version: options.resourceVersion,
content_hash: contentHash,
desired_hash: contentHash,
desired_readiness_baseline: buildReadinessBaseline(getResourceDeclaration(address, ctx.config)),
};
ctx.state.setResource(resource);
await ctx.state.save();
Expand Down
4 changes: 4 additions & 0 deletions packages/sdk/src/internal/executor/executor.ts
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
import { dirname, resolve } from "node:path";
import { UserError } from "../errors.ts";
import { computeComparableDesiredHash } from "../planner/comparable.ts";
import { getResourceDeclaration } from "../planner/declaration.ts";
import { computeResourceHash } from "../planner/hasher.ts";
import { buildReadinessBaseline } from "../planner/plan-semantics.ts";
import { ApiError, ConflictError } from "../providers/base-client.ts";
import { readComparableIfSupported } from "../providers/drift-support.ts";
import type { RemoteResource } from "../providers/interface.ts";
Expand DownExpand Up@@ -454,8 +456,10 @@ async function executeAction(action: PlannedAction, provider: ResourceExecAdapte
content_hash: hash,
desired_hash: hash,
desired_comparable_hash: remoteHash,
desired_readiness_baseline: buildReadinessBaseline(getResourceDeclaration(address, ctx.config)),
remote_hash: remoteHash,
remote_snapshot: remoteSnapshot,
drift_paths: [],
drift_status: remoteHash ? "in_sync" : undefined,
});
return adopted;
Expand Down
72 changes: 72 additions & 0 deletions packages/sdk/src/internal/planner/plan-semantics.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
import type { ActionType, PlanReadinessImpact } from "../types/dto.ts";
import type { ResourceReadinessBaseline } from "../types/state.ts";
import { contentHash } from "../utils/hash.ts";

const NON_BLOCKING_ROOT_FIELDS = new Set(["description", "metadata"]);

/**
* Return stable, leaf-oriented paths whose values differ between two JSON-like
* resource snapshots. Arrays are treated atomically because their ordering is
* part of the declared resource semantics.
*/
export function diffChangedPaths(before: unknown, after: unknown, prefix = ""): string[] {
if (Object.is(before, after)) return [];
if (Array.isArray(before) || Array.isArray(after)) {
return structurallyEqual(before, after) ? [] : [prefix || "$root"];
}
if (isRecord(before) && isRecord(after)) {
const paths: string[] = [];
const keys = new Set([...Object.keys(before), ...Object.keys(after)]);
for (const key of [...keys].sort()) {
const path = prefix ? `${prefix}.${key}` : key;
paths.push(...diffChangedPaths(before[key], after[key], path));
}
return paths;
}
return [prefix || "$root"];
}

/**
* Classify whether an already-provisioned Agent Harness can keep running while
* a planned action is pending. Unknown changes are deliberately blocking.
*/
export function classifyReadinessImpact(
action: ActionType,
changedPaths: readonly string[] | undefined,
): PlanReadinessImpact {
if (action === "no-op") return "none";
if (action !== "update" || !changedPaths || changedPaths.length === 0) return "blocking";
return changedPaths.every(isNonBlockingPath) ? "non_blocking" : "blocking";
}

/** Store only irreversible hashes in state; declarations may contain secrets. */
export function buildReadinessBaseline(declaration: unknown): ResourceReadinessBaseline {
const record = isRecord(declaration) ? declaration : {};
const { description: _description, metadata: _metadata, ...operational } = record;
return {
operational_hash: contentHash(operational),
description_hash: contentHash(record.description ?? null),
metadata_hash: contentHash(record.metadata ?? null),
};
}

export function diffReadinessBaseline(before: ResourceReadinessBaseline, after: ResourceReadinessBaseline): string[] {
const paths: string[] = [];
if (before.operational_hash !== after.operational_hash) paths.push("$operational");
if (before.description_hash !== after.description_hash) paths.push("description");
if (before.metadata_hash !== after.metadata_hash) paths.push("metadata");
return paths;
}

function isNonBlockingPath(path: string): boolean {
const root = path.split(".", 1)[0];
return root !== undefined && NON_BLOCKING_ROOT_FIELDS.has(root);
}

function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}

function structurallyEqual(left: unknown, right: unknown): boolean {
return contentHash(left) === contentHash(right);
}
29 changes: 29 additions & 0 deletions packages/sdk/src/internal/planner/planner.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,9 @@ import type { ProjectConfig } from "../types/config.ts";
import type { ExecutionPlan, PlannedAction } from "../types/plan.ts";
import type { ResourceAddress, StateFile } from "../types/state.ts";
import { addressKey } from "../types/state.ts";
import { getResourceDeclaration } from "./declaration.ts";
import { computeResourceHash } from "./hasher.ts";
import { buildReadinessBaseline, classifyReadinessImpact, diffReadinessBaseline } from "./plan-semantics.ts";

export interface PlanOptions {
providers?: string[];
Expand DownExpand Up@@ -48,6 +50,7 @@ export async function buildPlan(
action: "create",
address,
driftKind: "none",
readinessImpact: "blocking",
reason: "Resource does not exist in state",
after: { content_hash: desiredHash },
dependencies: deps,
Expand All@@ -56,10 +59,13 @@ export async function buildPlan(
(existing.desired_hash ?? existing.content_hash) !== desiredHash &&
existing.drift_status === "drifted"
) {
const changedPaths = collectChangedPaths(address, config, existing, true);
actions.push({
action: "update",
address,
driftKind: "both",
readinessImpact: classifyReadinessImpact("update", changedPaths),
changedPaths,
reason: "Local config changed and remote drift detected",
before: {
content_hash: existing.desired_hash ?? existing.content_hash,
Expand All@@ -70,20 +76,26 @@ export async function buildPlan(
dependencies: deps,
});
} else if ((existing.desired_hash ?? existing.content_hash) !== desiredHash) {
const changedPaths = collectChangedPaths(address, config, existing, false);
actions.push({
action: "update",
address,
driftKind: "local",
readinessImpact: classifyReadinessImpact("update", changedPaths),
changedPaths,
reason: "Local config changed",
before: { content_hash: existing.desired_hash ?? existing.content_hash },
after: { content_hash: desiredHash },
dependencies: deps,
});
} else if (existing.drift_status === "drifted") {
const changedPaths = existing.drift_paths;
actions.push({
action: "update",
address,
driftKind: "remote",
readinessImpact: classifyReadinessImpact("update", changedPaths),
changedPaths,
reason: "Remote drift detected",
before: {
content_hash: existing.desired_hash ?? existing.content_hash,
Expand All@@ -98,6 +110,7 @@ export async function buildPlan(
action: "no-op",
address,
driftKind: "none",
readinessImpact: "none",
reason:
existing.drift_status === "unchecked"
? "No changes detected (remote content drift unchecked)"
Expand All@@ -116,6 +129,7 @@ export async function buildPlan(
action: "delete",
address: res.address,
driftKind: "none",
readinessImpact: "blocking",
reason: "Resource removed from configuration",
before: { content_hash: res.desired_hash ?? res.content_hash },
dependencies: [],
Expand All@@ -125,6 +139,21 @@ export async function buildPlan(
return { actions, diagnostics: diagnostics.getAll() };
}

function collectChangedPaths(
address: ResourceAddress,
config: ProjectConfig,
existing: StateFile["resources"][number],
includeRemote: boolean,
): string[] | undefined {
const current = buildReadinessBaseline(getResourceDeclaration(address, config));
const localPaths = existing.desired_readiness_baseline
? diffReadinessBaseline(existing.desired_readiness_baseline, current)
: undefined;
if (!includeRemote) return localPaths;
if (!localPaths && !existing.drift_paths) return undefined;
return [...new Set([...(localPaths ?? []), ...(existing.drift_paths ?? [])])].sort();
}

function getDependencies(address: ResourceAddress, graph: ReturnType<typeof buildDependencyGraph>): ResourceAddress[] {
const key = addressKey(address);
const depKeys = graph.edges.get(key) ?? new Set();
Expand Down
6 changes: 6 additions & 0 deletions packages/sdk/src/internal/planner/refresh.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,7 @@ import { emitRuntimeFeedback, type RuntimeFeedbackSink } from "../types/runtime-
import type { ResourceState } from "../types/state.ts";
import { contentHash } from "../utils/hash.ts";
import { getResourceDeclaration } from "./declaration.ts";
import { diffChangedPaths } from "./plan-semantics.ts";

export interface RefreshResult {
removed: ResourceState[];
Expand DownExpand Up@@ -75,6 +76,10 @@ export async function refreshState(
const desiredComparableHash = desiredComparable === null ? undefined : contentHash(desiredComparable);
const baselineHash = res.desired_comparable_hash ?? desiredComparableHash;
const driftStatus = baselineHash && remoteHash !== baselineHash ? "drifted" : "in_sync";
const driftPaths =
driftStatus === "drifted" && desiredComparable !== null
? diffChangedPaths(desiredComparable, remote.comparable)
: [];

state.setResource({
...res,
Expand All@@ -84,6 +89,7 @@ export async function refreshState(
desired_comparable_hash: res.desired_comparable_hash ?? desiredComparableHash,
remote_hash: remoteHash,
remote_snapshot: remote.snapshot ?? remote.comparable,
drift_paths: driftPaths,
drift_status: driftStatus,
});
dirty = true;
Expand Down
2 changes: 2 additions & 0 deletions packages/sdk/src/internal/state/state-manager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,8 +43,10 @@ export class StateManager implements IStateManager {
content_hash: ((r.content_hash ?? r.desired_hash) as string) ?? "",
desired_hash: ((r.desired_hash ?? r.content_hash) as string) ?? "",
desired_comparable_hash: r.desired_comparable_hash as string | undefined,
desired_readiness_baseline: r.desired_readiness_baseline as ResourceState["desired_readiness_baseline"],
remote_hash: r.remote_hash as string | undefined,
remote_snapshot: r.remote_snapshot,
drift_paths: r.drift_paths as string[] | undefined,
drift_status: r.drift_status as ResourceState["drift_status"],
}));
return new StateManager({ resources }, path);
Expand Down
5 changes: 5 additions & 0 deletions packages/sdk/src/internal/types/dto.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,11 +35,16 @@ export type ActionType = z.infer<typeof ActionTypeSchema>;
export const DriftKindSchema = z.enum(["none", "local", "remote", "both"]);
export type DriftKind = z.infer<typeof DriftKindSchema>;

export const PlanReadinessImpactSchema = z.enum(["none", "non_blocking", "blocking"]);
export type PlanReadinessImpact = z.infer<typeof PlanReadinessImpactSchema>;

export const PlannedActionSchema = z.object({
action: ActionTypeSchema,
address: ResourceAddressSchema,
reason: z.string(),
driftKind: DriftKindSchema.optional(),
readinessImpact: PlanReadinessImpactSchema.optional(),
changedPaths: z.array(z.string()).optional(),
before: z.record(z.string(), z.unknown()).optional(),
after: z.record(z.string(), z.unknown()).optional(),
dependencies: z.array(ResourceAddressSchema),
Expand Down
8 changes: 8 additions & 0 deletions packages/sdk/src/internal/types/state.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,11 +13,19 @@ export interface ResourceState {
content_hash: string;
desired_hash?: string;
desired_comparable_hash?: string;
desired_readiness_baseline?: ResourceReadinessBaseline;
remote_hash?: string;
remote_snapshot?: unknown;
drift_paths?: string[];
drift_status?: "in_sync" | "drifted" | "missing" | "unchecked";
}

export interface ResourceReadinessBaseline {
operational_hash: string;
description_hash: string;
metadata_hash: string;
}

export interface StateFile {
resources: ResourceState[];
}
Expand Down
Loading