UNPKG

@hasna/projects

Version:

High-level project management CLI, MCP server, SDK, and AI SDK agent loop for coding agents

14,558 lines • 572 kB
#!/usr/bin/env bun
// @bun
var __defProp = Object.defineProperty;
var __returnValue = (v) => v;
function __exportSetter(name, newValue) {
  this[name] = __returnValue.bind(null, newValue);
}
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, {
      get: all[name],
      enumerable: true,
      configurable: true,
      set: __exportSetter.bind(all, name)
    });
};

// src/serve/projection-http.ts
import { constants, openSync, fstatSync, readSync, closeSync } from "fs";

// ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/external.js
var exports_external = {};
__export(exports_external, {
  void: () => voidType,
  util: () => util,
  unknown: () => unknownType,
  union: () => unionType,
  undefined: () => undefinedType,
  tuple: () => tupleType,
  transformer: () => effectsType,
  symbol: () => symbolType,
  string: () => stringType,
  strictObject: () => strictObjectType,
  setErrorMap: () => setErrorMap,
  set: () => setType,
  record: () => recordType,
  quotelessJson: () => quotelessJson,
  promise: () => promiseType,
  preprocess: () => preprocessType,
  pipeline: () => pipelineType,
  ostring: () => ostring,
  optional: () => optionalType,
  onumber: () => onumber,
  oboolean: () => oboolean,
  objectUtil: () => objectUtil,
  object: () => objectType,
  number: () => numberType,
  nullable: () => nullableType,
  null: () => nullType,
  never: () => neverType,
  nativeEnum: () => nativeEnumType,
  nan: () => nanType,
  map: () => mapType,
  makeIssue: () => makeIssue,
  literal: () => literalType,
  lazy: () => lazyType,
  late: () => late,
  isValid: () => isValid,
  isDirty: () => isDirty,
  isAsync: () => isAsync,
  isAborted: () => isAborted,
  intersection: () => intersectionType,
  instanceof: () => instanceOfType,
  getParsedType: () => getParsedType,
  getErrorMap: () => getErrorMap,
  function: () => functionType,
  enum: () => enumType,
  effect: () => effectsType,
  discriminatedUnion: () => discriminatedUnionType,
  defaultErrorMap: () => en_default,
  datetimeRegex: () => datetimeRegex,
  date: () => dateType,
  custom: () => custom,
  coerce: () => coerce,
  boolean: () => booleanType,
  bigint: () => bigIntType,
  array: () => arrayType,
  any: () => anyType,
  addIssueToContext: () => addIssueToContext,
  ZodVoid: () => ZodVoid,
  ZodUnknown: () => ZodUnknown,
  ZodUnion: () => ZodUnion,
  ZodUndefined: () => ZodUndefined,
  ZodType: () => ZodType,
  ZodTuple: () => ZodTuple,
  ZodTransformer: () => ZodEffects,
  ZodSymbol: () => ZodSymbol,
  ZodString: () => ZodString,
  ZodSet: () => ZodSet,
  ZodSchema: () => ZodType,
  ZodRecord: () => ZodRecord,
  ZodReadonly: () => ZodReadonly,
  ZodPromise: () => ZodPromise,
  ZodPipeline: () => ZodPipeline,
  ZodParsedType: () => ZodParsedType,
  ZodOptional: () => ZodOptional,
  ZodObject: () => ZodObject,
  ZodNumber: () => ZodNumber,
  ZodNullable: () => ZodNullable,
  ZodNull: () => ZodNull,
  ZodNever: () => ZodNever,
  ZodNativeEnum: () => ZodNativeEnum,
  ZodNaN: () => ZodNaN,
  ZodMap: () => ZodMap,
  ZodLiteral: () => ZodLiteral,
  ZodLazy: () => ZodLazy,
  ZodIssueCode: () => ZodIssueCode,
  ZodIntersection: () => ZodIntersection,
  ZodFunction: () => ZodFunction,
  ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
  ZodError: () => ZodError,
  ZodEnum: () => ZodEnum,
  ZodEffects: () => ZodEffects,
  ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
  ZodDefault: () => ZodDefault,
  ZodDate: () => ZodDate,
  ZodCatch: () => ZodCatch,
  ZodBranded: () => ZodBranded,
  ZodBoolean: () => ZodBoolean,
  ZodBigInt: () => ZodBigInt,
  ZodArray: () => ZodArray,
  ZodAny: () => ZodAny,
  Schema: () => ZodType,
  ParseStatus: () => ParseStatus,
  OK: () => OK,
  NEVER: () => NEVER,
  INVALID: () => INVALID,
  EMPTY_PATH: () => EMPTY_PATH,
  DIRTY: () => DIRTY,
  BRAND: () => BRAND
});

// ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/helpers/util.js
var util;
(function(util2) {
  util2.assertEqual = (_) => {};
  function assertIs(_arg) {}
  util2.assertIs = assertIs;
  function assertNever(_x) {
    throw new Error;
  }
  util2.assertNever = assertNever;
  util2.arrayToEnum = (items) => {
    const obj = {};
    for (const item of items) {
      obj[item] = item;
    }
    return obj;
  };
  util2.getValidEnumValues = (obj) => {
    const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
    const filtered = {};
    for (const k of validKeys) {
      filtered[k] = obj[k];
    }
    return util2.objectValues(filtered);
  };
  util2.objectValues = (obj) => {
    return util2.objectKeys(obj).map(function(e) {
      return obj[e];
    });
  };
  util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
    const keys = [];
    for (const key in object) {
      if (Object.prototype.hasOwnProperty.call(object, key)) {
        keys.push(key);
      }
    }
    return keys;
  };
  util2.find = (arr, checker) => {
    for (const item of arr) {
      if (checker(item))
        return item;
    }
    return;
  };
  util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
  function joinValues(array, separator = " | ") {
    return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
  }
  util2.joinValues = joinValues;
  util2.jsonStringifyReplacer = (_, value) => {
    if (typeof value === "bigint") {
      return value.toString();
    }
    return value;
  };
})(util || (util = {}));
var objectUtil;
(function(objectUtil2) {
  objectUtil2.mergeShapes = (first, second) => {
    return {
      ...first,
      ...second
    };
  };
})(objectUtil || (objectUtil = {}));
var ZodParsedType = util.arrayToEnum([
  "string",
  "nan",
  "number",
  "integer",
  "float",
  "boolean",
  "date",
  "bigint",
  "symbol",
  "function",
  "undefined",
  "null",
  "array",
  "object",
  "unknown",
  "promise",
  "void",
  "never",
  "map",
  "set"
]);
var getParsedType = (data) => {
  const t = typeof data;
  switch (t) {
    case "undefined":
      return ZodParsedType.undefined;
    case "string":
      return ZodParsedType.string;
    case "number":
      return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
    case "boolean":
      return ZodParsedType.boolean;
    case "function":
      return ZodParsedType.function;
    case "bigint":
      return ZodParsedType.bigint;
    case "symbol":
      return ZodParsedType.symbol;
    case "object":
      if (Array.isArray(data)) {
        return ZodParsedType.array;
      }
      if (data === null) {
        return ZodParsedType.null;
      }
      if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
        return ZodParsedType.promise;
      }
      if (typeof Map !== "undefined" && data instanceof Map) {
        return ZodParsedType.map;
      }
      if (typeof Set !== "undefined" && data instanceof Set) {
        return ZodParsedType.set;
      }
      if (typeof Date !== "undefined" && data instanceof Date) {
        return ZodParsedType.date;
      }
      return ZodParsedType.object;
    default:
      return ZodParsedType.unknown;
  }
};

// ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/ZodError.js
var ZodIssueCode = util.arrayToEnum([
  "invalid_type",
  "invalid_literal",
  "custom",
  "invalid_union",
  "invalid_union_discriminator",
  "invalid_enum_value",
  "unrecognized_keys",
  "invalid_arguments",
  "invalid_return_type",
  "invalid_date",
  "invalid_string",
  "too_small",
  "too_big",
  "invalid_intersection_types",
  "not_multiple_of",
  "not_finite"
]);
var quotelessJson = (obj) => {
  const json = JSON.stringify(obj, null, 2);
  return json.replace(/"([^"]+)":/g, "$1:");
};

class ZodError extends Error {
  get errors() {
    return this.issues;
  }
  constructor(issues) {
    super();
    this.issues = [];
    this.addIssue = (sub) => {
      this.issues = [...this.issues, sub];
    };
    this.addIssues = (subs = []) => {
      this.issues = [...this.issues, ...subs];
    };
    const actualProto = new.target.prototype;
    if (Object.setPrototypeOf) {
      Object.setPrototypeOf(this, actualProto);
    } else {
      this.__proto__ = actualProto;
    }
    this.name = "ZodError";
    this.issues = issues;
  }
  format(_mapper) {
    const mapper = _mapper || function(issue) {
      return issue.message;
    };
    const fieldErrors = { _errors: [] };
    const processError = (error) => {
      for (const issue of error.issues) {
        if (issue.code === "invalid_union") {
          issue.unionErrors.map(processError);
        } else if (issue.code === "invalid_return_type") {
          processError(issue.returnTypeError);
        } else if (issue.code === "invalid_arguments") {
          processError(issue.argumentsError);
        } else if (issue.path.length === 0) {
          fieldErrors._errors.push(mapper(issue));
        } else {
          let curr = fieldErrors;
          let i = 0;
          while (i < issue.path.length) {
            const el = issue.path[i];
            const terminal = i === issue.path.length - 1;
            if (!terminal) {
              curr[el] = curr[el] || { _errors: [] };
            } else {
              curr[el] = curr[el] || { _errors: [] };
              curr[el]._errors.push(mapper(issue));
            }
            curr = curr[el];
            i++;
          }
        }
      }
    };
    processError(this);
    return fieldErrors;
  }
  static assert(value) {
    if (!(value instanceof ZodError)) {
      throw new Error(`Not a ZodError: ${value}`);
    }
  }
  toString() {
    return this.message;
  }
  get message() {
    return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
  }
  get isEmpty() {
    return this.issues.length === 0;
  }
  flatten(mapper = (issue) => issue.message) {
    const fieldErrors = {};
    const formErrors = [];
    for (const sub of this.issues) {
      if (sub.path.length > 0) {
        const firstEl = sub.path[0];
        fieldErrors[firstEl] = fieldErrors[firstEl] || [];
        fieldErrors[firstEl].push(mapper(sub));
      } else {
        formErrors.push(mapper(sub));
      }
    }
    return { formErrors, fieldErrors };
  }
  get formErrors() {
    return this.flatten();
  }
}
ZodError.create = (issues) => {
  const error = new ZodError(issues);
  return error;
};

// ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/locales/en.js
var errorMap = (issue, _ctx) => {
  let message;
  switch (issue.code) {
    case ZodIssueCode.invalid_type:
      if (issue.received === ZodParsedType.undefined) {
        message = "Required";
      } else {
        message = `Expected ${issue.expected}, received ${issue.received}`;
      }
      break;
    case ZodIssueCode.invalid_literal:
      message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
      break;
    case ZodIssueCode.unrecognized_keys:
      message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
      break;
    case ZodIssueCode.invalid_union:
      message = `Invalid input`;
      break;
    case ZodIssueCode.invalid_union_discriminator:
      message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
      break;
    case ZodIssueCode.invalid_enum_value:
      message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
      break;
    case ZodIssueCode.invalid_arguments:
      message = `Invalid function arguments`;
      break;
    case ZodIssueCode.invalid_return_type:
      message = `Invalid function return type`;
      break;
    case ZodIssueCode.invalid_date:
      message = `Invalid date`;
      break;
    case ZodIssueCode.invalid_string:
      if (typeof issue.validation === "object") {
        if ("includes" in issue.validation) {
          message = `Invalid input: must include "${issue.validation.includes}"`;
          if (typeof issue.validation.position === "number") {
            message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
          }
        } else if ("startsWith" in issue.validation) {
          message = `Invalid input: must start with "${issue.validation.startsWith}"`;
        } else if ("endsWith" in issue.validation) {
          message = `Invalid input: must end with "${issue.validation.endsWith}"`;
        } else {
          util.assertNever(issue.validation);
        }
      } else if (issue.validation !== "regex") {
        message = `Invalid ${issue.validation}`;
      } else {
        message = "Invalid";
      }
      break;
    case ZodIssueCode.too_small:
      if (issue.type === "array")
        message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
      else if (issue.type === "string")
        message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
      else if (issue.type === "number")
        message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
      else if (issue.type === "bigint")
        message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
      else if (issue.type === "date")
        message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
      else
        message = "Invalid input";
      break;
    case ZodIssueCode.too_big:
      if (issue.type === "array")
        message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
      else if (issue.type === "string")
        message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
      else if (issue.type === "number")
        message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
      else if (issue.type === "bigint")
        message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
      else if (issue.type === "date")
        message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
      else
        message = "Invalid input";
      break;
    case ZodIssueCode.custom:
      message = `Invalid input`;
      break;
    case ZodIssueCode.invalid_intersection_types:
      message = `Intersection results could not be merged`;
      break;
    case ZodIssueCode.not_multiple_of:
      message = `Number must be a multiple of ${issue.multipleOf}`;
      break;
    case ZodIssueCode.not_finite:
      message = "Number must be finite";
      break;
    default:
      message = _ctx.defaultError;
      util.assertNever(issue);
  }
  return { message };
};
var en_default = errorMap;

// ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/errors.js
var overrideErrorMap = en_default;
function setErrorMap(map) {
  overrideErrorMap = map;
}
function getErrorMap() {
  return overrideErrorMap;
}
// ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js
var makeIssue = (params) => {
  const { data, path, errorMaps, issueData } = params;
  const fullPath = [...path, ...issueData.path || []];
  const fullIssue = {
    ...issueData,
    path: fullPath
  };
  if (issueData.message !== undefined) {
    return {
      ...issueData,
      path: fullPath,
      message: issueData.message
    };
  }
  let errorMessage = "";
  const maps = errorMaps.filter((m) => !!m).slice().reverse();
  for (const map of maps) {
    errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
  }
  return {
    ...issueData,
    path: fullPath,
    message: errorMessage
  };
};
var EMPTY_PATH = [];
function addIssueToContext(ctx, issueData) {
  const overrideMap = getErrorMap();
  const issue = makeIssue({
    issueData,
    data: ctx.data,
    path: ctx.path,
    errorMaps: [
      ctx.common.contextualErrorMap,
      ctx.schemaErrorMap,
      overrideMap,
      overrideMap === en_default ? undefined : en_default
    ].filter((x) => !!x)
  });
  ctx.common.issues.push(issue);
}

class ParseStatus {
  constructor() {
    this.value = "valid";
  }
  dirty() {
    if (this.value === "valid")
      this.value = "dirty";
  }
  abort() {
    if (this.value !== "aborted")
      this.value = "aborted";
  }
  static mergeArray(status, results) {
    const arrayValue = [];
    for (const s of results) {
      if (s.status === "aborted")
        return INVALID;
      if (s.status === "dirty")
        status.dirty();
      arrayValue.push(s.value);
    }
    return { status: status.value, value: arrayValue };
  }
  static async mergeObjectAsync(status, pairs) {
    const syncPairs = [];
    for (const pair of pairs) {
      const key = await pair.key;
      const value = await pair.value;
      syncPairs.push({
        key,
        value
      });
    }
    return ParseStatus.mergeObjectSync(status, syncPairs);
  }
  static mergeObjectSync(status, pairs) {
    const finalObject = {};
    for (const pair of pairs) {
      const { key, value } = pair;
      if (key.status === "aborted")
        return INVALID;
      if (value.status === "aborted")
        return INVALID;
      if (key.status === "dirty")
        status.dirty();
      if (value.status === "dirty")
        status.dirty();
      if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
        finalObject[key.value] = value.value;
      }
    }
    return { status: status.value, value: finalObject };
  }
}
var INVALID = Object.freeze({
  status: "aborted"
});
var DIRTY = (value) => ({ status: "dirty", value });
var OK = (value) => ({ status: "valid", value });
var isAborted = (x) => x.status === "aborted";
var isDirty = (x) => x.status === "dirty";
var isValid = (x) => x.status === "valid";
var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
// ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js
var errorUtil;
(function(errorUtil2) {
  errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
  errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
})(errorUtil || (errorUtil = {}));

// ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/types.js
class ParseInputLazyPath {
  constructor(parent, value, path, key) {
    this._cachedPath = [];
    this.parent = parent;
    this.data = value;
    this._path = path;
    this._key = key;
  }
  get path() {
    if (!this._cachedPath.length) {
      if (Array.isArray(this._key)) {
        this._cachedPath.push(...this._path, ...this._key);
      } else {
        this._cachedPath.push(...this._path, this._key);
      }
    }
    return this._cachedPath;
  }
}
var handleResult = (ctx, result) => {
  if (isValid(result)) {
    return { success: true, data: result.value };
  } else {
    if (!ctx.common.issues.length) {
      throw new Error("Validation failed but no issues detected.");
    }
    return {
      success: false,
      get error() {
        if (this._error)
          return this._error;
        const error = new ZodError(ctx.common.issues);
        this._error = error;
        return this._error;
      }
    };
  }
};
function processCreateParams(params) {
  if (!params)
    return {};
  const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
  if (errorMap2 && (invalid_type_error || required_error)) {
    throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  }
  if (errorMap2)
    return { errorMap: errorMap2, description };
  const customMap = (iss, ctx) => {
    const { message } = params;
    if (iss.code === "invalid_enum_value") {
      return { message: message ?? ctx.defaultError };
    }
    if (typeof ctx.data === "undefined") {
      return { message: message ?? required_error ?? ctx.defaultError };
    }
    if (iss.code !== "invalid_type")
      return { message: ctx.defaultError };
    return { message: message ?? invalid_type_error ?? ctx.defaultError };
  };
  return { errorMap: customMap, description };
}

class ZodType {
  get description() {
    return this._def.description;
  }
  _getType(input) {
    return getParsedType(input.data);
  }
  _getOrReturnCtx(input, ctx) {
    return ctx || {
      common: input.parent.common,
      data: input.data,
      parsedType: getParsedType(input.data),
      schemaErrorMap: this._def.errorMap,
      path: input.path,
      parent: input.parent
    };
  }
  _processInputParams(input) {
    return {
      status: new ParseStatus,
      ctx: {
        common: input.parent.common,
        data: input.data,
        parsedType: getParsedType(input.data),
        schemaErrorMap: this._def.errorMap,
        path: input.path,
        parent: input.parent
      }
    };
  }
  _parseSync(input) {
    const result = this._parse(input);
    if (isAsync(result)) {
      throw new Error("Synchronous parse encountered promise.");
    }
    return result;
  }
  _parseAsync(input) {
    const result = this._parse(input);
    return Promise.resolve(result);
  }
  parse(data, params) {
    const result = this.safeParse(data, params);
    if (result.success)
      return result.data;
    throw result.error;
  }
  safeParse(data, params) {
    const ctx = {
      common: {
        issues: [],
        async: params?.async ?? false,
        contextualErrorMap: params?.errorMap
      },
      path: params?.path || [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType(data)
    };
    const result = this._parseSync({ data, path: ctx.path, parent: ctx });
    return handleResult(ctx, result);
  }
  "~validate"(data) {
    const ctx = {
      common: {
        issues: [],
        async: !!this["~standard"].async
      },
      path: [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType(data)
    };
    if (!this["~standard"].async) {
      try {
        const result = this._parseSync({ data, path: [], parent: ctx });
        return isValid(result) ? {
          value: result.value
        } : {
          issues: ctx.common.issues
        };
      } catch (err) {
        if (err?.message?.toLowerCase()?.includes("encountered")) {
          this["~standard"].async = true;
        }
        ctx.common = {
          issues: [],
          async: true
        };
      }
    }
    return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
      value: result.value
    } : {
      issues: ctx.common.issues
    });
  }
  async parseAsync(data, params) {
    const result = await this.safeParseAsync(data, params);
    if (result.success)
      return result.data;
    throw result.error;
  }
  async safeParseAsync(data, params) {
    const ctx = {
      common: {
        issues: [],
        contextualErrorMap: params?.errorMap,
        async: true
      },
      path: params?.path || [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType(data)
    };
    const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
    const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
    return handleResult(ctx, result);
  }
  refine(check, message) {
    const getIssueProperties = (val) => {
      if (typeof message === "string" || typeof message === "undefined") {
        return { message };
      } else if (typeof message === "function") {
        return message(val);
      } else {
        return message;
      }
    };
    return this._refinement((val, ctx) => {
      const result = check(val);
      const setError = () => ctx.addIssue({
        code: ZodIssueCode.custom,
        ...getIssueProperties(val)
      });
      if (typeof Promise !== "undefined" && result instanceof Promise) {
        return result.then((data) => {
          if (!data) {
            setError();
            return false;
          } else {
            return true;
          }
        });
      }
      if (!result) {
        setError();
        return false;
      } else {
        return true;
      }
    });
  }
  refinement(check, refinementData) {
    return this._refinement((val, ctx) => {
      if (!check(val)) {
        ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
        return false;
      } else {
        return true;
      }
    });
  }
  _refinement(refinement) {
    return new ZodEffects({
      schema: this,
      typeName: ZodFirstPartyTypeKind.ZodEffects,
      effect: { type: "refinement", refinement }
    });
  }
  superRefine(refinement) {
    return this._refinement(refinement);
  }
  constructor(def) {
    this.spa = this.safeParseAsync;
    this._def = def;
    this.parse = this.parse.bind(this);
    this.safeParse = this.safeParse.bind(this);
    this.parseAsync = this.parseAsync.bind(this);
    this.safeParseAsync = this.safeParseAsync.bind(this);
    this.spa = this.spa.bind(this);
    this.refine = this.refine.bind(this);
    this.refinement = this.refinement.bind(this);
    this.superRefine = this.superRefine.bind(this);
    this.optional = this.optional.bind(this);
    this.nullable = this.nullable.bind(this);
    this.nullish = this.nullish.bind(this);
    this.array = this.array.bind(this);
    this.promise = this.promise.bind(this);
    this.or = this.or.bind(this);
    this.and = this.and.bind(this);
    this.transform = this.transform.bind(this);
    this.brand = this.brand.bind(this);
    this.default = this.default.bind(this);
    this.catch = this.catch.bind(this);
    this.describe = this.describe.bind(this);
    this.pipe = this.pipe.bind(this);
    this.readonly = this.readonly.bind(this);
    this.isNullable = this.isNullable.bind(this);
    this.isOptional = this.isOptional.bind(this);
    this["~standard"] = {
      version: 1,
      vendor: "zod",
      validate: (data) => this["~validate"](data)
    };
  }
  optional() {
    return ZodOptional.create(this, this._def);
  }
  nullable() {
    return ZodNullable.create(this, this._def);
  }
  nullish() {
    return this.nullable().optional();
  }
  array() {
    return ZodArray.create(this);
  }
  promise() {
    return ZodPromise.create(this, this._def);
  }
  or(option) {
    return ZodUnion.create([this, option], this._def);
  }
  and(incoming) {
    return ZodIntersection.create(this, incoming, this._def);
  }
  transform(transform) {
    return new ZodEffects({
      ...processCreateParams(this._def),
      schema: this,
      typeName: ZodFirstPartyTypeKind.ZodEffects,
      effect: { type: "transform", transform }
    });
  }
  default(def) {
    const defaultValueFunc = typeof def === "function" ? def : () => def;
    return new ZodDefault({
      ...processCreateParams(this._def),
      innerType: this,
      defaultValue: defaultValueFunc,
      typeName: ZodFirstPartyTypeKind.ZodDefault
    });
  }
  brand() {
    return new ZodBranded({
      typeName: ZodFirstPartyTypeKind.ZodBranded,
      type: this,
      ...processCreateParams(this._def)
    });
  }
  catch(def) {
    const catchValueFunc = typeof def === "function" ? def : () => def;
    return new ZodCatch({
      ...processCreateParams(this._def),
      innerType: this,
      catchValue: catchValueFunc,
      typeName: ZodFirstPartyTypeKind.ZodCatch
    });
  }
  describe(description) {
    const This = this.constructor;
    return new This({
      ...this._def,
      description
    });
  }
  pipe(target) {
    return ZodPipeline.create(this, target);
  }
  readonly() {
    return ZodReadonly.create(this);
  }
  isOptional() {
    return this.safeParse(undefined).success;
  }
  isNullable() {
    return this.safeParse(null).success;
  }
}
var cuidRegex = /^c[^\s-]{8,}$/i;
var cuid2Regex = /^[0-9a-z]+$/;
var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
var nanoidRegex = /^[a-z0-9_-]{21}$/i;
var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
var emojiRegex;
var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
var dateRegex = new RegExp(`^${dateRegexSource}$`);
function timeRegexSource(args) {
  let secondsRegexSource = `[0-5]\\d`;
  if (args.precision) {
    secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
  } else if (args.precision == null) {
    secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
  }
  const secondsQuantifier = args.precision ? "+" : "?";
  return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
}
function timeRegex(args) {
  return new RegExp(`^${timeRegexSource(args)}$`);
}
function datetimeRegex(args) {
  let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
  const opts = [];
  opts.push(args.local ? `Z?` : `Z`);
  if (args.offset)
    opts.push(`([+-]\\d{2}:?\\d{2})`);
  regex = `${regex}(${opts.join("|")})`;
  return new RegExp(`^${regex}$`);
}
function isValidIP(ip, version) {
  if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
    return true;
  }
  if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
    return true;
  }
  return false;
}
function isValidJWT(jwt, alg) {
  if (!jwtRegex.test(jwt))
    return false;
  try {
    const [header] = jwt.split(".");
    if (!header)
      return false;
    const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
    const decoded = JSON.parse(atob(base64));
    if (typeof decoded !== "object" || decoded === null)
      return false;
    if ("typ" in decoded && decoded?.typ !== "JWT")
      return false;
    if (!decoded.alg)
      return false;
    if (alg && decoded.alg !== alg)
      return false;
    return true;
  } catch {
    return false;
  }
}
function isValidCidr(ip, version) {
  if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
    return true;
  }
  if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
    return true;
  }
  return false;
}

class ZodString extends ZodType {
  _parse(input) {
    if (this._def.coerce) {
      input.data = String(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.string) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.string,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    const status = new ParseStatus;
    let ctx = undefined;
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        if (input.data.length < check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: check.value,
            type: "string",
            inclusive: true,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        if (input.data.length > check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: check.value,
            type: "string",
            inclusive: true,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "length") {
        const tooBig = input.data.length > check.value;
        const tooSmall = input.data.length < check.value;
        if (tooBig || tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          if (tooBig) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_big,
              maximum: check.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check.message
            });
          } else if (tooSmall) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_small,
              minimum: check.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check.message
            });
          }
          status.dirty();
        }
      } else if (check.kind === "email") {
        if (!emailRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "email",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "emoji") {
        if (!emojiRegex) {
          emojiRegex = new RegExp(_emojiRegex, "u");
        }
        if (!emojiRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "emoji",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "uuid") {
        if (!uuidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "uuid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "nanoid") {
        if (!nanoidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "nanoid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cuid") {
        if (!cuidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cuid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cuid2") {
        if (!cuid2Regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cuid2",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "ulid") {
        if (!ulidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "ulid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "url") {
        try {
          new URL(input.data);
        } catch {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "url",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "regex") {
        check.regex.lastIndex = 0;
        const testResult = check.regex.test(input.data);
        if (!testResult) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "regex",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "trim") {
        input.data = input.data.trim();
      } else if (check.kind === "includes") {
        if (!input.data.includes(check.value, check.position)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { includes: check.value, position: check.position },
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "toLowerCase") {
        input.data = input.data.toLowerCase();
      } else if (check.kind === "toUpperCase") {
        input.data = input.data.toUpperCase();
      } else if (check.kind === "startsWith") {
        if (!input.data.startsWith(check.value)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { startsWith: check.value },
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "endsWith") {
        if (!input.data.endsWith(check.value)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { endsWith: check.value },
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "datetime") {
        const regex = datetimeRegex(check);
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "datetime",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "date") {
        const regex = dateRegex;
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "date",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "time") {
        const regex = timeRegex(check);
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "time",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "duration") {
        if (!durationRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "duration",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "ip") {
        if (!isValidIP(input.data, check.version)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "ip",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "jwt") {
        if (!isValidJWT(input.data, check.alg)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "jwt",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cidr") {
        if (!isValidCidr(input.data, check.version)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cidr",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "base64") {
        if (!base64Regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "base64",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "base64url") {
        if (!base64urlRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "base64url",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return { status: status.value, value: input.data };
  }
  _regex(regex, validation, message) {
    return this.refinement((data) => regex.test(data), {
      validation,
      code: ZodIssueCode.invalid_string,
      ...errorUtil.errToObj(message)
    });
  }
  _addCheck(check) {
    return new ZodString({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  email(message) {
    return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
  }
  url(message) {
    return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
  }
  emoji(message) {
    return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
  }
  uuid(message) {
    return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
  }
  nanoid(message) {
    return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
  }
  cuid(message) {
    return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
  }
  cuid2(message) {
    return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
  }
  ulid(message) {
    return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
  }
  base64(message) {
    return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
  }
  base64url(message) {
    return this._addCheck({
      kind: "base64url",
      ...errorUtil.errToObj(message)
    });
  }
  jwt(options) {
    return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
  }
  ip(options) {
    return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
  }
  cidr(options) {
    return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
  }
  datetime(options) {
    if (typeof options === "string") {
      return this._addCheck({
        kind: "datetime",
        precision: null,
        offset: false,
        local: false,
        message: options
      });
    }
    return this._addCheck({
      kind: "datetime",
      precision: typeof options?.precision === "undefined" ? null : options?.precision,
      offset: options?.offset ?? false,
      local: options?.local ?? false,
      ...errorUtil.errToObj(options?.message)
    });
  }
  date(message) {
    return this._addCheck({ kind: "date", message });
  }
  time(options) {
    if (typeof options === "string") {
      return this._addCheck({
        kind: "time",
        precision: null,
        message: options
      });
    }
    return this._addCheck({
      kind: "time",
      precision: typeof options?.precision === "undefined" ? null : options?.precision,
      ...errorUtil.errToObj(options?.message)
    });
  }
  duration(message) {
    return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
  }
  regex(regex, message) {
    return this._addCheck({
      kind: "regex",
      regex,
      ...errorUtil.errToObj(message)
    });
  }
  includes(value, options) {
    return this._addCheck({
      kind: "includes",
      value,
      position: options?.position,
      ...errorUtil.errToObj(options?.message)
    });
  }
  startsWith(value, message) {
    return this._addCheck({
      kind: "startsWith",
      value,
      ...errorUtil.errToObj(message)
    });
  }
  endsWith(value, message) {
    return this._addCheck({
      kind: "endsWith",
      value,
      ...errorUtil.errToObj(message)
    });
  }
  min(minLength, message) {
    return this._addCheck({
      kind: "min",
      value: minLength,
      ...errorUtil.errToObj(message)
    });
  }
  max(maxLength, message) {
    return this._addCheck({
      kind: "max",
      value: maxLength,
      ...errorUtil.errToObj(message)
    });
  }
  length(len, message) {
    return this._addCheck({
      kind: "length",
      value: len,
      ...errorUtil.errToObj(message)
    });
  }
  nonempty(message) {
    return this.min(1, errorUtil.errToObj(message));
  }
  trim() {
    return new ZodString({
      ...this._def,
      checks: [...this._def.checks, { kind: "trim" }]
    });
  }
  toLowerCase() {
    return new ZodString({
      ...this._def,
      checks: [...this._def.checks, { kind: "toLowerCase" }]
    });
  }
  toUpperCase() {
    return new ZodString({
      ...this._def,
      checks: [...this._def.checks, { kind: "toUpperCase" }]
    });
  }
  get isDatetime() {
    return !!this._def.checks.find((ch) => ch.kind === "datetime");
  }
  get isDate() {
    return !!this._def.checks.find((ch) => ch.kind === "date");
  }
  get isTime() {
    return !!this._def.checks.find((ch) => ch.kind === "time");
  }
  get isDuration() {
    return !!this._def.checks.find((ch) => ch.kind === "duration");
  }
  get isEmail() {
    return !!this._def.checks.find((ch) => ch.kind === "email");
  }
  get isURL() {
    return !!this._def.checks.find((ch) => ch.kind === "url");
  }
  get isEmoji() {
    return !!this._def.checks.find((ch) => ch.kind === "emoji");
  }
  get isUUID() {
    return !!this._def.checks.find((ch) => ch.kind === "uuid");
  }
  get isNANOID() {
    return !!this._def.checks.find((ch) => ch.kind === "nanoid");
  }
  get isCUID() {
    return !!this._def.checks.find((ch) => ch.kind === "cuid");
  }
  get isCUID2() {
    return !!this._def.checks.find((ch) => ch.kind === "cuid2");
  }
  get isULID() {
    return !!this._def.checks.find((ch) => ch.kind === "ulid");
  }
  get isIP() {
    return !!this._def.checks.find((ch) => ch.kind === "ip");
  }
  get isCIDR() {
    return !!this._def.checks.find((ch) => ch.kind === "cidr");
  }
  get isBase64() {
    return !!this._def.checks.find((ch) => ch.kind === "base64");
  }
  get isBase64url() {
    return !!this._def.checks.find((ch) => ch.kind === "base64url");
  }
  get minLength() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min;
  }
  get maxLength() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max;
  }
}
ZodString.create = (params) => {
  return new ZodString({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodString,
    coerce: params?.coerce ?? false,
    ...processCreateParams(params)
  });
};
function floatSafeRemainder(val, step) {
  const valDecCount = (val.toString().split(".")[1] || "").length;
  const stepDecCount = (step.toString().split(".")[1] || "").length;
  const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
  const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
  return valInt % stepInt / 10 ** decCount;
}

class ZodNumber extends ZodType {
  constructor() {
    super(...arguments);
    this.min = this.gte;
    this.max = this.lte;
    this.step = this.multipleOf;
  }
  _parse(input) {
    if (this._def.coerce) {
      input.data = Number(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.number) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.number,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    let ctx = undefined;
    const status = new ParseStatus;
    for (const check of this._def.checks) {
      if (check.kind === "int") {
        if (!util.isInteger(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: "integer",
            received: "float",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "min") {
        const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
        if (tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: check.value,
            type: "number",
            inclusive: check.inclusive,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
        if (tooBig) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: check.value,
            type: "number",
            inclusive: check.inclusive,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "multipleOf") {
        if (floatSafeRemainder(input.data, check.value) !== 0) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_multiple_of,
            multipleOf: check.value,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "finite") {
        if (!Number.isFinite(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_finite,
            message: check.message
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return { status: status.value, value: input.data };
  }
  gte(value, message) {
    return this.setLimit("min", value, true, errorUtil.toString(message));
  }
  gt(value, message) {
    return this.setLimit("min", value, false, errorUtil.toString(message));
  }
  lte(value, message) {
    return this.setLimit("max", value, true, errorUtil.toString(message));
  }
  lt(value, message) {
    return this.setLimit("max", value, false, errorUtil.toString(message));
  }
  setLimit(kind, value, inclusive, message) {
    return new ZodNumber({
      ...this._def,
      checks: [
        ...this._def.checks,
        {
          kind,
          value,
          inclusive,
          message: errorUtil.toString(message)
        }
      ]
    });
  }
  _addCheck(check) {
    return new ZodNumber({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  int(message) {
    return this._addCheck({
      kind: "int",
      message: errorUtil.toString(message)
    });
  }
  positive(message) {
    return this._addCheck({
      kind: "min",
      value: 0,
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  negative(message) {
    return this._addCheck({
      kind: "max",
      value: 0,
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  nonpositive(message) {
    return this._addCheck({
      kind: "max",
      value: 0,
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  nonnegative(message) {
    return this._addCheck({
      kind: "min",
      value: 0,
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  multipleOf(value, message) {
    return this._addCheck({
      kind: "multipleOf",
      value,
      message: errorUtil.toString(message)
    });
  }
  finite(message) {
    return this._addCheck({
      kind: "finite",
      message: errorUtil.toString(message)
    });
  }
  safe(message) {
    return this._addCheck({
      kind: "min",
      inclusive: true,
      value: Number.MIN_SAFE_INTEGER,
      message: errorUtil.toString(message)
    })._addCheck({
      kind: "max",
      inclusive: true,
      value: Number.MAX_SAFE_INTEGER,
      message: errorUtil.toString(message)
    });
  }
  get minValue() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min;
  }
  get maxValue() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max;
  }
  get isInt() {
    return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
  }
  get isFinite() {
    let max = null;
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
        return true;
      } else if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      } else if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return Number.isFinite(min) && Number.isFinite(max);
  }
}
ZodNumber.create = (params) => {
  return new ZodNumber({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodNumber,
    coerce: params?.coerce || false,
    ...processCreateParams(params)
  });
};

class ZodBigInt extends ZodType {
  constructor() {
    super(...arguments);
    this.min = this.gte;
    this.max = this.lte;
  }
  _parse(input) {
    if (this._def.coerce) {
      try {
        input.data = BigInt(input.data);
      } catch {
        return this._getInvalidInput(input);
      }
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.bigint) {
      return this._getInvalidInput(input);
    }
    let ctx = undefined;
    const status = new ParseStatus;
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
        if (tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            type: "bigint",
            minimum: check.value,
            inclusive: check.inclusive,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
        if (tooBig) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            type: "bigint",
            maximum: check.value,
            inclusive: check.inclusive,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "multipleOf") {
        if (input.data % check.value !== BigInt(0)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_multiple_of,
            multipleOf: check.value,
            message: check.message
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return { status: status.value, value: input.data };
  }
  _getInvalidInput(input) {
    const ctx = this._getOrReturnCtx(input);
    addIssueToContext(ctx, {
      code: ZodIssueCode.invalid_type,
      expected: ZodParsedType.bigint,
      received: ctx.parsedType
    });
    return INVALID;
  }
  gte(value, message) {
    return this.setLimit("min", value, true, errorUtil.toString(message));
  }
  gt(value, message) {
    return this.setLimit("min", value, false, errorUtil.toString(message));
  }
  lte(value, message) {
    return this.setLimit("max", value, true, errorUtil.toString(message));
  }
  lt(value, message) {
    return this.setLimit("max", value, false, errorUtil.toString(message));
  }
  setLimit(kind, value, inclusive, message) {
    return new ZodBigInt({
      ...this._def,
      checks: [
        ...this._def.checks,
        {
          kind,
          value,
          inclusive,
          message: errorUtil.toString(message)
        }
      ]
    });
  }
  _addCheck(check) {
    return new ZodBigInt({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  positive(message) {
    return this._addCheck({
      kind: "min",
      value: BigInt(0),
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  negative(message) {
    return this._addCheck({
      kind: "max",
      value: BigInt(0),
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  nonpositive(message) {
    return this._addCheck({
      kind: "max",
      value: BigInt(0),
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  nonnegative(message) {
    return this._addCheck({
      kind: "min",
      value: BigInt(0),
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  multipleOf(value, message) {
    return this._addCheck({
      kind: "multipleOf",
      value,
      message: errorUtil.toString(message)
    });
  }
  get minValue() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min;
  }
  get maxValue() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max;
  }
}
ZodBigInt.create = (params) => {
  return new ZodBigInt({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodBigInt,
    coerce: params?.coerce ?? false,
    ...processCreateParams(params)
  });
};

class ZodBoolean extends ZodType {
  _parse(input) {
    if (this._def.coerce) {
      input.data = Boolean(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.boolean) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.boolean,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodBoolean.create = (params) => {
  return new ZodBoolean({
    typeName: ZodFirstPartyTypeKind.ZodBoolean,
    coerce: params?.coerce || false,
    ...processCreateParams(params)
  });
};

class ZodDate extends ZodType {
  _parse(input) {
    if (this._def.coerce) {
      input.data = new Date(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.date) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.date,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    if (Number.isNaN(input.data.getTime())) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_date
      });
      return INVALID;
    }
    const status = new ParseStatus;
    let ctx = undefined;
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        if (input.data.getTime() < check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            message: check.message,
            inclusive: true,
            exact: false,
            minimum: check.value,
            type: "date"
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        if (input.data.getTime() > check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            message: check.message,
            inclusive: true,
            exact: false,
            maximum: check.value,
            type: "date"
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return {
      status: status.value,
      value: new Date(input.data.getTime())
    };
  }
  _addCheck(check) {
    return new ZodDate({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  min(minDate, message) {
    return this._addCheck({
      kind: "min",
      value: minDate.getTime(),
      message: errorUtil.toString(message)
    });
  }
  max(maxDate, message) {
    return this._addCheck({
      kind: "max",
      value: maxDate.getTime(),
      message: errorUtil.toString(message)
    });
  }
  get minDate() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min != null ? new Date(min) : null;
  }
  get maxDate() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max != null ? new Date(max) : null;
  }
}
ZodDate.create = (params) => {
  return new ZodDate({
    checks: [],
    coerce: params?.coerce || false,
    typeName: ZodFirstPartyTypeKind.ZodDate,
    ...processCreateParams(params)
  });
};

class ZodSymbol extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.symbol) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.symbol,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodSymbol.create = (params) => {
  return new ZodSymbol({
    typeName: ZodFirstPartyTypeKind.ZodSymbol,
    ...processCreateParams(params)
  });
};

class ZodUndefined extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.undefined) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.undefined,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodUndefined.create = (params) => {
  return new ZodUndefined({
    typeName: ZodFirstPartyTypeKind.ZodUndefined,
    ...processCreateParams(params)
  });
};

class ZodNull extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.null) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.null,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodNull.create = (params) => {
  return new ZodNull({
    typeName: ZodFirstPartyTypeKind.ZodNull,
    ...processCreateParams(params)
  });
};

class ZodAny extends ZodType {
  constructor() {
    super(...arguments);
    this._any = true;
  }
  _parse(input) {
    return OK(input.data);
  }
}
ZodAny.create = (params) => {
  return new ZodAny({
    typeName: ZodFirstPartyTypeKind.ZodAny,
    ...processCreateParams(params)
  });
};

class ZodUnknown extends ZodType {
  constructor() {
    super(...arguments);
    this._unknown = true;
  }
  _parse(input) {
    return OK(input.data);
  }
}
ZodUnknown.create = (params) => {
  return new ZodUnknown({
    typeName: ZodFirstPartyTypeKind.ZodUnknown,
    ...processCreateParams(params)
  });
};

class ZodNever extends ZodType {
  _parse(input) {
    const ctx = this._getOrReturnCtx(input);
    addIssueToContext(ctx, {
      code: ZodIssueCode.invalid_type,
      expected: ZodParsedType.never,
      received: ctx.parsedType
    });
    return INVALID;
  }
}
ZodNever.create = (params) => {
  return new ZodNever({
    typeName: ZodFirstPartyTypeKind.ZodNever,
    ...processCreateParams(params)
  });
};

class ZodVoid extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.undefined) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.void,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodVoid.create = (params) => {
  return new ZodVoid({
    typeName: ZodFirstPartyTypeKind.ZodVoid,
    ...processCreateParams(params)
  });
};

class ZodArray extends ZodType {
  _parse(input) {
    const { ctx, status } = this._processInputParams(input);
    const def = this._def;
    if (ctx.parsedType !== ZodParsedType.array) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.array,
        received: ctx.parsedType
      });
      return INVALID;
    }
    if (def.exactLength !== null) {
      const tooBig = ctx.data.length > def.exactLength.value;
      const tooSmall = ctx.data.length < def.exactLength.value;
      if (tooBig || tooSmall) {
        addIssueToContext(ctx, {
          code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
          minimum: tooSmall ? def.exactLength.value : undefined,
          maximum: tooBig ? def.exactLength.value : undefined,
          type: "array",
          inclusive: true,
          exact: true,
          message: def.exactLength.message
        });
        status.dirty();
      }
    }
    if (def.minLength !== null) {
      if (ctx.data.length < def.minLength.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_small,
          minimum: def.minLength.value,
          type: "array",
          inclusive: true,
          exact: false,
          message: def.minLength.message
        });
        status.dirty();
      }
    }
    if (def.maxLength !== null) {
      if (ctx.data.length > def.maxLength.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_big,
          maximum: def.maxLength.value,
          type: "array",
          inclusive: true,
          exact: false,
          message: def.maxLength.message
        });
        status.dirty();
      }
    }
    if (ctx.common.async) {
      return Promise.all([...ctx.data].map((item, i) => {
        return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
      })).then((result2) => {
        return ParseStatus.mergeArray(status, result2);
      });
    }
    const result = [...ctx.data].map((item, i) => {
      return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
    });
    return ParseStatus.mergeArray(status, result);
  }
  get element() {
    return this._def.type;
  }
  min(minLength, message) {
    return new ZodArray({
      ...this._def,
      minLength: { value: minLength, message: errorUtil.toString(message) }
    });
  }
  max(maxLength, message) {
    return new ZodArray({
      ...this._def,
      maxLength: { value: maxLength, message: errorUtil.toString(message) }
    });
  }
  length(len, message) {
    return new ZodArray({
      ...this._def,
      exactLength: { value: len, message: errorUtil.toString(message) }
    });
  }
  nonempty(message) {
    return this.min(1, message);
  }
}
ZodArray.create = (schema, params) => {
  return new ZodArray({
    type: schema,
    minLength: null,
    maxLength: null,
    exactLength: null,
    typeName: ZodFirstPartyTypeKind.ZodArray,
    ...processCreateParams(params)
  });
};
function deepPartialify(schema) {
  if (schema instanceof ZodObject) {
    const newShape = {};
    for (const key in schema.shape) {
      const fieldSchema = schema.shape[key];
      newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
    }
    return new ZodObject({
      ...schema._def,
      shape: () => newShape
    });
  } else if (schema instanceof ZodArray) {
    return new ZodArray({
      ...schema._def,
      type: deepPartialify(schema.element)
    });
  } else if (schema instanceof ZodOptional) {
    return ZodOptional.create(deepPartialify(schema.unwrap()));
  } else if (schema instanceof ZodNullable) {
    return ZodNullable.create(deepPartialify(schema.unwrap()));
  } else if (schema instanceof ZodTuple) {
    return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
  } else {
    return schema;
  }
}

class ZodObject extends ZodType {
  constructor() {
    super(...arguments);
    this._cached = null;
    this.nonstrict = this.passthrough;
    this.augment = this.extend;
  }
  _getCached() {
    if (this._cached !== null)
      return this._cached;
    const shape = this._def.shape();
    const keys = util.objectKeys(shape);
    this._cached = { shape, keys };
    return this._cached;
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.object) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    const { status, ctx } = this._processInputParams(input);
    const { shape, keys: shapeKeys } = this._getCached();
    const extraKeys = [];
    if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
      for (const key in ctx.data) {
        if (!shapeKeys.includes(key)) {
          extraKeys.push(key);
        }
      }
    }
    const pairs = [];
    for (const key of shapeKeys) {
      const keyValidator = shape[key];
      const value = ctx.data[key];
      pairs.push({
        key: { status: "valid", value: key },
        value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
        alwaysSet: key in ctx.data
      });
    }
    if (this._def.catchall instanceof ZodNever) {
      const unknownKeys = this._def.unknownKeys;
      if (unknownKeys === "passthrough") {
        for (const key of extraKeys) {
          pairs.push({
            key: { status: "valid", value: key },
            value: { status: "valid", value: ctx.data[key] }
          });
        }
      } else if (unknownKeys === "strict") {
        if (extraKeys.length > 0) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.unrecognized_keys,
            keys: extraKeys
          });
          status.dirty();
        }
      } else if (unknownKeys === "strip") {} else {
        throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
      }
    } else {
      const catchall = this._def.catchall;
      for (const key of extraKeys) {
        const value = ctx.data[key];
        pairs.push({
          key: { status: "valid", value: key },
          value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
          alwaysSet: key in ctx.data
        });
      }
    }
    if (ctx.common.async) {
      return Promise.resolve().then(async () => {
        const syncPairs = [];
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          syncPairs.push({
            key,
            value,
            alwaysSet: pair.alwaysSet
          });
        }
        return syncPairs;
      }).then((syncPairs) => {
        return ParseStatus.mergeObjectSync(status, syncPairs);
      });
    } else {
      return ParseStatus.mergeObjectSync(status, pairs);
    }
  }
  get shape() {
    return this._def.shape();
  }
  strict(message) {
    errorUtil.errToObj;
    return new ZodObject({
      ...this._def,
      unknownKeys: "strict",
      ...message !== undefined ? {
        errorMap: (issue, ctx) => {
          const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
          if (issue.code === "unrecognized_keys")
            return {
              message: errorUtil.errToObj(message).message ?? defaultError
            };
          return {
            message: defaultError
          };
        }
      } : {}
    });
  }
  strip() {
    return new ZodObject({
      ...this._def,
      unknownKeys: "strip"
    });
  }
  passthrough() {
    return new ZodObject({
      ...this._def,
      unknownKeys: "passthrough"
    });
  }
  extend(augmentation) {
    return new ZodObject({
      ...this._def,
      shape: () => ({
        ...this._def.shape(),
        ...augmentation
      })
    });
  }
  merge(merging) {
    const merged = new ZodObject({
      unknownKeys: merging._def.unknownKeys,
      catchall: merging._def.catchall,
      shape: () => ({
        ...this._def.shape(),
        ...merging._def.shape()
      }),
      typeName: ZodFirstPartyTypeKind.ZodObject
    });
    return merged;
  }
  setKey(key, schema) {
    return this.augment({ [key]: schema });
  }
  catchall(index) {
    return new ZodObject({
      ...this._def,
      catchall: index
    });
  }
  pick(mask) {
    const shape = {};
    for (const key of util.objectKeys(mask)) {
      if (mask[key] && this.shape[key]) {
        shape[key] = this.shape[key];
      }
    }
    return new ZodObject({
      ...this._def,
      shape: () => shape
    });
  }
  omit(mask) {
    const shape = {};
    for (const key of util.objectKeys(this.shape)) {
      if (!mask[key]) {
        shape[key] = this.shape[key];
      }
    }
    return new ZodObject({
      ...this._def,
      shape: () => shape
    });
  }
  deepPartial() {
    return deepPartialify(this);
  }
  partial(mask) {
    const newShape = {};
    for (const key of util.objectKeys(this.shape)) {
      const fieldSchema = this.shape[key];
      if (mask && !mask[key]) {
        newShape[key] = fieldSchema;
      } else {
        newShape[key] = fieldSchema.optional();
      }
    }
    return new ZodObject({
      ...this._def,
      shape: () => newShape
    });
  }
  required(mask) {
    const newShape = {};
    for (const key of util.objectKeys(this.shape)) {
      if (mask && !mask[key]) {
        newShape[key] = this.shape[key];
      } else {
        const fieldSchema = this.shape[key];
        let newField = fieldSchema;
        while (newField instanceof ZodOptional) {
          newField = newField._def.innerType;
        }
        newShape[key] = newField;
      }
    }
    return new ZodObject({
      ...this._def,
      shape: () => newShape
    });
  }
  keyof() {
    return createZodEnum(util.objectKeys(this.shape));
  }
}
ZodObject.create = (shape, params) => {
  return new ZodObject({
    shape: () => shape,
    unknownKeys: "strip",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params)
  });
};
ZodObject.strictCreate = (shape, params) => {
  return new ZodObject({
    shape: () => shape,
    unknownKeys: "strict",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params)
  });
};
ZodObject.lazycreate = (shape, params) => {
  return new ZodObject({
    shape,
    unknownKeys: "strip",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params)
  });
};

class ZodUnion extends ZodType {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const options = this._def.options;
    function handleResults(results) {
      for (const result of results) {
        if (result.result.status === "valid") {
          return result.result;
        }
      }
      for (const result of results) {
        if (result.result.status === "dirty") {
          ctx.common.issues.push(...result.ctx.common.issues);
          return result.result;
        }
      }
      const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union,
        unionErrors
      });
      return INVALID;
    }
    if (ctx.common.async) {
      return Promise.all(options.map(async (option) => {
        const childCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          },
          parent: null
        };
        return {
          result: await option._parseAsync({
            data: ctx.data,
            path: ctx.path,
            parent: childCtx
          }),
          ctx: childCtx
        };
      })).then(handleResults);
    } else {
      let dirty = undefined;
      const issues = [];
      for (const option of options) {
        const childCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          },
          parent: null
        };
        const result = option._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: childCtx
        });
        if (result.status === "valid") {
          return result;
        } else if (result.status === "dirty" && !dirty) {
          dirty = { result, ctx: childCtx };
        }
        if (childCtx.common.issues.length) {
          issues.push(childCtx.common.issues);
        }
      }
      if (dirty) {
        ctx.common.issues.push(...dirty.ctx.common.issues);
        return dirty.result;
      }
      const unionErrors = issues.map((issues2) => new ZodError(issues2));
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union,
        unionErrors
      });
      return INVALID;
    }
  }
  get options() {
    return this._def.options;
  }
}
ZodUnion.create = (types, params) => {
  return new ZodUnion({
    options: types,
    typeName: ZodFirstPartyTypeKind.ZodUnion,
    ...processCreateParams(params)
  });
};
var getDiscriminator = (type) => {
  if (type instanceof ZodLazy) {
    return getDiscriminator(type.schema);
  } else if (type instanceof ZodEffects) {
    return getDiscriminator(type.innerType());
  } else if (type instanceof ZodLiteral) {
    return [type.value];
  } else if (type instanceof ZodEnum) {
    return type.options;
  } else if (type instanceof ZodNativeEnum) {
    return util.objectValues(type.enum);
  } else if (type instanceof ZodDefault) {
    return getDiscriminator(type._def.innerType);
  } else if (type instanceof ZodUndefined) {
    return [undefined];
  } else if (type instanceof ZodNull) {
    return [null];
  } else if (type instanceof ZodOptional) {
    return [undefined, ...getDiscriminator(type.unwrap())];
  } else if (type instanceof ZodNullable) {
    return [null, ...getDiscriminator(type.unwrap())];
  } else if (type instanceof ZodBranded) {
    return getDiscriminator(type.unwrap());
  } else if (type instanceof ZodReadonly) {
    return getDiscriminator(type.unwrap());
  } else if (type instanceof ZodCatch) {
    return getDiscriminator(type._def.innerType);
  } else {
    return [];
  }
};

class ZodDiscriminatedUnion extends ZodType {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.object) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const discriminator = this.discriminator;
    const discriminatorValue = ctx.data[discriminator];
    const option = this.optionsMap.get(discriminatorValue);
    if (!option) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union_discriminator,
        options: Array.from(this.optionsMap.keys()),
        path: [discriminator]
      });
      return INVALID;
    }
    if (ctx.common.async) {
      return option._parseAsync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
    } else {
      return option._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
    }
  }
  get discriminator() {
    return this._def.discriminator;
  }
  get options() {
    return this._def.options;
  }
  get optionsMap() {
    return this._def.optionsMap;
  }
  static create(discriminator, options, params) {
    const optionsMap = new Map;
    for (const type of options) {
      const discriminatorValues = getDiscriminator(type.shape[discriminator]);
      if (!discriminatorValues.length) {
        throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
      }
      for (const value of discriminatorValues) {
        if (optionsMap.has(value)) {
          throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
        }
        optionsMap.set(value, type);
      }
    }
    return new ZodDiscriminatedUnion({
      typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
      discriminator,
      options,
      optionsMap,
      ...processCreateParams(params)
    });
  }
}
function mergeValues(a, b) {
  const aType = getParsedType(a);
  const bType = getParsedType(b);
  if (a === b) {
    return { valid: true, data: a };
  } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
    const bKeys = util.objectKeys(b);
    const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a, ...b };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues(a[key], b[key]);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newObj[key] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
    if (a.length !== b.length) {
      return { valid: false };
    }
    const newArray = [];
    for (let index = 0;index < a.length; index++) {
      const itemA = a[index];
      const itemB = b[index];
      const sharedValue = mergeValues(itemA, itemB);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newArray.push(sharedValue.data);
    }
    return { valid: true, data: newArray };
  } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
    return { valid: true, data: a };
  } else {
    return { valid: false };
  }
}

class ZodIntersection extends ZodType {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    const handleParsed = (parsedLeft, parsedRight) => {
      if (isAborted(parsedLeft) || isAborted(parsedRight)) {
        return INVALID;
      }
      const merged = mergeValues(parsedLeft.value, parsedRight.value);
      if (!merged.valid) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.invalid_intersection_types
        });
        return INVALID;
      }
      if (isDirty(parsedLeft) || isDirty(parsedRight)) {
        status.dirty();
      }
      return { status: status.value, value: merged.data };
    };
    if (ctx.common.async) {
      return Promise.all([
        this._def.left._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        }),
        this._def.right._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        })
      ]).then(([left, right]) => handleParsed(left, right));
    } else {
      return handleParsed(this._def.left._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      }), this._def.right._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      }));
    }
  }
}
ZodIntersection.create = (left, right, params) => {
  return new ZodIntersection({
    left,
    right,
    typeName: ZodFirstPartyTypeKind.ZodIntersection,
    ...processCreateParams(params)
  });
};

class ZodTuple extends ZodType {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.array) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.array,
        received: ctx.parsedType
      });
      return INVALID;
    }
    if (ctx.data.length < this._def.items.length) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.too_small,
        minimum: this._def.items.length,
        inclusive: true,
        exact: false,
        type: "array"
      });
      return INVALID;
    }
    const rest = this._def.rest;
    if (!rest && ctx.data.length > this._def.items.length) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.too_big,
        maximum: this._def.items.length,
        inclusive: true,
        exact: false,
        type: "array"
      });
      status.dirty();
    }
    const items = [...ctx.data].map((item, itemIndex) => {
      const schema = this._def.items[itemIndex] || this._def.rest;
      if (!schema)
        return null;
      return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
    }).filter((x) => !!x);
    if (ctx.common.async) {
      return Promise.all(items).then((results) => {
        return ParseStatus.mergeArray(status, results);
      });
    } else {
      return ParseStatus.mergeArray(status, items);
    }
  }
  get items() {
    return this._def.items;
  }
  rest(rest) {
    return new ZodTuple({
      ...this._def,
      rest
    });
  }
}
ZodTuple.create = (schemas, params) => {
  if (!Array.isArray(schemas)) {
    throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
  }
  return new ZodTuple({
    items: schemas,
    typeName: ZodFirstPartyTypeKind.ZodTuple,
    rest: null,
    ...processCreateParams(params)
  });
};

class ZodRecord extends ZodType {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.object) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const pairs = [];
    const keyType = this._def.keyType;
    const valueType = this._def.valueType;
    for (const key in ctx.data) {
      pairs.push({
        key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
        value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
        alwaysSet: key in ctx.data
      });
    }
    if (ctx.common.async) {
      return ParseStatus.mergeObjectAsync(status, pairs);
    } else {
      return ParseStatus.mergeObjectSync(status, pairs);
    }
  }
  get element() {
    return this._def.valueType;
  }
  static create(first, second, third) {
    if (second instanceof ZodType) {
      return new ZodRecord({
        keyType: first,
        valueType: second,
        typeName: ZodFirstPartyTypeKind.ZodRecord,
        ...processCreateParams(third)
      });
    }
    return new ZodRecord({
      keyType: ZodString.create(),
      valueType: first,
      typeName: ZodFirstPartyTypeKind.ZodRecord,
      ...processCreateParams(second)
    });
  }
}

class ZodMap extends ZodType {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.map) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.map,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const keyType = this._def.keyType;
    const valueType = this._def.valueType;
    const pairs = [...ctx.data.entries()].map(([key, value], index) => {
      return {
        key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
        value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
      };
    });
    if (ctx.common.async) {
      const finalMap = new Map;
      return Promise.resolve().then(async () => {
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          if (key.status === "aborted" || value.status === "aborted") {
            return INVALID;
          }
          if (key.status === "dirty" || value.status === "dirty") {
            status.dirty();
          }
          finalMap.set(key.value, value.value);
        }
        return { status: status.value, value: finalMap };
      });
    } else {
      const finalMap = new Map;
      for (const pair of pairs) {
        const key = pair.key;
        const value = pair.value;
        if (key.status === "aborted" || value.status === "aborted") {
          return INVALID;
        }
        if (key.status === "dirty" || value.status === "dirty") {
          status.dirty();
        }
        finalMap.set(key.value, value.value);
      }
      return { status: status.value, value: finalMap };
    }
  }
}
ZodMap.create = (keyType, valueType, params) => {
  return new ZodMap({
    valueType,
    keyType,
    typeName: ZodFirstPartyTypeKind.ZodMap,
    ...processCreateParams(params)
  });
};

class ZodSet extends ZodType {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.set) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.set,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const def = this._def;
    if (def.minSize !== null) {
      if (ctx.data.size < def.minSize.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_small,
          minimum: def.minSize.value,
          type: "set",
          inclusive: true,
          exact: false,
          message: def.minSize.message
        });
        status.dirty();
      }
    }
    if (def.maxSize !== null) {
      if (ctx.data.size > def.maxSize.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_big,
          maximum: def.maxSize.value,
          type: "set",
          inclusive: true,
          exact: false,
          message: def.maxSize.message
        });
        status.dirty();
      }
    }
    const valueType = this._def.valueType;
    function finalizeSet(elements2) {
      const parsedSet = new Set;
      for (const element of elements2) {
        if (element.status === "aborted")
          return INVALID;
        if (element.status === "dirty")
          status.dirty();
        parsedSet.add(element.value);
      }
      return { status: status.value, value: parsedSet };
    }
    const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
    if (ctx.common.async) {
      return Promise.all(elements).then((elements2) => finalizeSet(elements2));
    } else {
      return finalizeSet(elements);
    }
  }
  min(minSize, message) {
    return new ZodSet({
      ...this._def,
      minSize: { value: minSize, message: errorUtil.toString(message) }
    });
  }
  max(maxSize, message) {
    return new ZodSet({
      ...this._def,
      maxSize: { value: maxSize, message: errorUtil.toString(message) }
    });
  }
  size(size, message) {
    return this.min(size, message).max(size, message);
  }
  nonempty(message) {
    return this.min(1, message);
  }
}
ZodSet.create = (valueType, params) => {
  return new ZodSet({
    valueType,
    minSize: null,
    maxSize: null,
    typeName: ZodFirstPartyTypeKind.ZodSet,
    ...processCreateParams(params)
  });
};

class ZodFunction extends ZodType {
  constructor() {
    super(...arguments);
    this.validate = this.implement;
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.function) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.function,
        received: ctx.parsedType
      });
      return INVALID;
    }
    function makeArgsIssue(args, error) {
      return makeIssue({
        data: args,
        path: ctx.path,
        errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
        issueData: {
          code: ZodIssueCode.invalid_arguments,
          argumentsError: error
        }
      });
    }
    function makeReturnsIssue(returns, error) {
      return makeIssue({
        data: returns,
        path: ctx.path,
        errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
        issueData: {
          code: ZodIssueCode.invalid_return_type,
          returnTypeError: error
        }
      });
    }
    const params = { errorMap: ctx.common.contextualErrorMap };
    const fn = ctx.data;
    if (this._def.returns instanceof ZodPromise) {
      const me = this;
      return OK(async function(...args) {
        const error = new ZodError([]);
        const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
          error.addIssue(makeArgsIssue(args, e));
          throw error;
        });
        const result = await Reflect.apply(fn, this, parsedArgs);
        const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
          error.addIssue(makeReturnsIssue(result, e));
          throw error;
        });
        return parsedReturns;
      });
    } else {
      const me = this;
      return OK(function(...args) {
        const parsedArgs = me._def.args.safeParse(args, params);
        if (!parsedArgs.success) {
          throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
        }
        const result = Reflect.apply(fn, this, parsedArgs.data);
        const parsedReturns = me._def.returns.safeParse(result, params);
        if (!parsedReturns.success) {
          throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
        }
        return parsedReturns.data;
      });
    }
  }
  parameters() {
    return this._def.args;
  }
  returnType() {
    return this._def.returns;
  }
  args(...items) {
    return new ZodFunction({
      ...this._def,
      args: ZodTuple.create(items).rest(ZodUnknown.create())
    });
  }
  returns(returnType) {
    return new ZodFunction({
      ...this._def,
      returns: returnType
    });
  }
  implement(func) {
    const validatedFunc = this.parse(func);
    return validatedFunc;
  }
  strictImplement(func) {
    const validatedFunc = this.parse(func);
    return validatedFunc;
  }
  static create(args, returns, params) {
    return new ZodFunction({
      args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
      returns: returns || ZodUnknown.create(),
      typeName: ZodFirstPartyTypeKind.ZodFunction,
      ...processCreateParams(params)
    });
  }
}

class ZodLazy extends ZodType {
  get schema() {
    return this._def.getter();
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const lazySchema = this._def.getter();
    return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
  }
}
ZodLazy.create = (getter, params) => {
  return new ZodLazy({
    getter,
    typeName: ZodFirstPartyTypeKind.ZodLazy,
    ...processCreateParams(params)
  });
};

class ZodLiteral extends ZodType {
  _parse(input) {
    if (input.data !== this._def.value) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_literal,
        expected: this._def.value
      });
      return INVALID;
    }
    return { status: "valid", value: input.data };
  }
  get value() {
    return this._def.value;
  }
}
ZodLiteral.create = (value, params) => {
  return new ZodLiteral({
    value,
    typeName: ZodFirstPartyTypeKind.ZodLiteral,
    ...processCreateParams(params)
  });
};
function createZodEnum(values, params) {
  return new ZodEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodEnum,
    ...processCreateParams(params)
  });
}

class ZodEnum extends ZodType {
  _parse(input) {
    if (typeof input.data !== "string") {
      const ctx = this._getOrReturnCtx(input);
      const expectedValues = this._def.values;
      addIssueToContext(ctx, {
        expected: util.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode.invalid_type
      });
      return INVALID;
    }
    if (!this._cache) {
      this._cache = new Set(this._def.values);
    }
    if (!this._cache.has(input.data)) {
      const ctx = this._getOrReturnCtx(input);
      const expectedValues = this._def.values;
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_enum_value,
        options: expectedValues
      });
      return INVALID;
    }
    return OK(input.data);
  }
  get options() {
    return this._def.values;
  }
  get enum() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  get Values() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  get Enum() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  extract(values, newDef = this._def) {
    return ZodEnum.create(values, {
      ...this._def,
      ...newDef
    });
  }
  exclude(values, newDef = this._def) {
    return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
      ...this._def,
      ...newDef
    });
  }
}
ZodEnum.create = createZodEnum;

class ZodNativeEnum extends ZodType {
  _parse(input) {
    const nativeEnumValues = util.getValidEnumValues(this._def.values);
    const ctx = this._getOrReturnCtx(input);
    if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
      const expectedValues = util.objectValues(nativeEnumValues);
      addIssueToContext(ctx, {
        expected: util.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode.invalid_type
      });
      return INVALID;
    }
    if (!this._cache) {
      this._cache = new Set(util.getValidEnumValues(this._def.values));
    }
    if (!this._cache.has(input.data)) {
      const expectedValues = util.objectValues(nativeEnumValues);
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_enum_value,
        options: expectedValues
      });
      return INVALID;
    }
    return OK(input.data);
  }
  get enum() {
    return this._def.values;
  }
}
ZodNativeEnum.create = (values, params) => {
  return new ZodNativeEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
    ...processCreateParams(params)
  });
};

class ZodPromise extends ZodType {
  unwrap() {
    return this._def.type;
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.promise,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
    return OK(promisified.then((data) => {
      return this._def.type.parseAsync(data, {
        path: ctx.path,
        errorMap: ctx.common.contextualErrorMap
      });
    }));
  }
}
ZodPromise.create = (schema, params) => {
  return new ZodPromise({
    type: schema,
    typeName: ZodFirstPartyTypeKind.ZodPromise,
    ...processCreateParams(params)
  });
};

class ZodEffects extends ZodType {
  innerType() {
    return this._def.schema;
  }
  sourceType() {
    return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    const effect = this._def.effect || null;
    const checkCtx = {
      addIssue: (arg) => {
        addIssueToContext(ctx, arg);
        if (arg.fatal) {
          status.abort();
        } else {
          status.dirty();
        }
      },
      get path() {
        return ctx.path;
      }
    };
    checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
    if (effect.type === "preprocess") {
      const processed = effect.transform(ctx.data, checkCtx);
      if (ctx.common.async) {
        return Promise.resolve(processed).then(async (processed2) => {
          if (status.value === "aborted")
            return INVALID;
          const result = await this._def.schema._parseAsync({
            data: processed2,
            path: ctx.path,
            parent: ctx
          });
          if (result.status === "aborted")
            return INVALID;
          if (result.status === "dirty")
            return DIRTY(result.value);
          if (status.value === "dirty")
            return DIRTY(result.value);
          return result;
        });
      } else {
        if (status.value === "aborted")
          return INVALID;
        const result = this._def.schema._parseSync({
          data: processed,
          path: ctx.path,
          parent: ctx
        });
        if (result.status === "aborted")
          return INVALID;
        if (result.status === "dirty")
          return DIRTY(result.value);
        if (status.value === "dirty")
          return DIRTY(result.value);
        return result;
      }
    }
    if (effect.type === "refinement") {
      const executeRefinement = (acc) => {
        const result = effect.refinement(acc, checkCtx);
        if (ctx.common.async) {
          return Promise.resolve(result);
        }
        if (result instanceof Promise) {
          throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
        }
        return acc;
      };
      if (ctx.common.async === false) {
        const inner = this._def.schema._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (inner.status === "aborted")
          return INVALID;
        if (inner.status === "dirty")
          status.dirty();
        executeRefinement(inner.value);
        return { status: status.value, value: inner.value };
      } else {
        return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
          if (inner.status === "aborted")
            return INVALID;
          if (inner.status === "dirty")
            status.dirty();
          return executeRefinement(inner.value).then(() => {
            return { status: status.value, value: inner.value };
          });
        });
      }
    }
    if (effect.type === "transform") {
      if (ctx.common.async === false) {
        const base = this._def.schema._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (!isValid(base))
          return INVALID;
        const result = effect.transform(base.value, checkCtx);
        if (result instanceof Promise) {
          throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
        }
        return { status: status.value, value: result };
      } else {
        return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
          if (!isValid(base))
            return INVALID;
          return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
            status: status.value,
            value: result
          }));
        });
      }
    }
    util.assertNever(effect);
  }
}
ZodEffects.create = (schema, effect, params) => {
  return new ZodEffects({
    schema,
    typeName: ZodFirstPartyTypeKind.ZodEffects,
    effect,
    ...processCreateParams(params)
  });
};
ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
  return new ZodEffects({
    schema,
    effect: { type: "preprocess", transform: preprocess },
    typeName: ZodFirstPartyTypeKind.ZodEffects,
    ...processCreateParams(params)
  });
};
class ZodOptional extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType === ZodParsedType.undefined) {
      return OK(undefined);
    }
    return this._def.innerType._parse(input);
  }
  unwrap() {
    return this._def.innerType;
  }
}
ZodOptional.create = (type, params) => {
  return new ZodOptional({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodOptional,
    ...processCreateParams(params)
  });
};

class ZodNullable extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType === ZodParsedType.null) {
      return OK(null);
    }
    return this._def.innerType._parse(input);
  }
  unwrap() {
    return this._def.innerType;
  }
}
ZodNullable.create = (type, params) => {
  return new ZodNullable({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodNullable,
    ...processCreateParams(params)
  });
};

class ZodDefault extends ZodType {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    let data = ctx.data;
    if (ctx.parsedType === ZodParsedType.undefined) {
      data = this._def.defaultValue();
    }
    return this._def.innerType._parse({
      data,
      path: ctx.path,
      parent: ctx
    });
  }
  removeDefault() {
    return this._def.innerType;
  }
}
ZodDefault.create = (type, params) => {
  return new ZodDefault({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodDefault,
    defaultValue: typeof params.default === "function" ? params.default : () => params.default,
    ...processCreateParams(params)
  });
};

class ZodCatch extends ZodType {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const newCtx = {
      ...ctx,
      common: {
        ...ctx.common,
        issues: []
      }
    };
    const result = this._def.innerType._parse({
      data: newCtx.data,
      path: newCtx.path,
      parent: {
        ...newCtx
      }
    });
    if (isAsync(result)) {
      return result.then((result2) => {
        return {
          status: "valid",
          value: result2.status === "valid" ? result2.value : this._def.catchValue({
            get error() {
              return new ZodError(newCtx.common.issues);
            },
            input: newCtx.data
          })
        };
      });
    } else {
      return {
        status: "valid",
        value: result.status === "valid" ? result.value : this._def.catchValue({
          get error() {
            return new ZodError(newCtx.common.issues);
          },
          input: newCtx.data
        })
      };
    }
  }
  removeCatch() {
    return this._def.innerType;
  }
}
ZodCatch.create = (type, params) => {
  return new ZodCatch({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodCatch,
    catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
    ...processCreateParams(params)
  });
};

class ZodNaN extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.nan) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.nan,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return { status: "valid", value: input.data };
  }
}
ZodNaN.create = (params) => {
  return new ZodNaN({
    typeName: ZodFirstPartyTypeKind.ZodNaN,
    ...processCreateParams(params)
  });
};
var BRAND = Symbol("zod_brand");

class ZodBranded extends ZodType {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const data = ctx.data;
    return this._def.type._parse({
      data,
      path: ctx.path,
      parent: ctx
    });
  }
  unwrap() {
    return this._def.type;
  }
}

class ZodPipeline extends ZodType {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.common.async) {
      const handleAsync = async () => {
        const inResult = await this._def.in._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (inResult.status === "aborted")
          return INVALID;
        if (inResult.status === "dirty") {
          status.dirty();
          return DIRTY(inResult.value);
        } else {
          return this._def.out._parseAsync({
            data: inResult.value,
            path: ctx.path,
            parent: ctx
          });
        }
      };
      return handleAsync();
    } else {
      const inResult = this._def.in._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
      if (inResult.status === "aborted")
        return INVALID;
      if (inResult.status === "dirty") {
        status.dirty();
        return {
          status: "dirty",
          value: inResult.value
        };
      } else {
        return this._def.out._parseSync({
          data: inResult.value,
          path: ctx.path,
          parent: ctx
        });
      }
    }
  }
  static create(a, b) {
    return new ZodPipeline({
      in: a,
      out: b,
      typeName: ZodFirstPartyTypeKind.ZodPipeline
    });
  }
}

class ZodReadonly extends ZodType {
  _parse(input) {
    const result = this._def.innerType._parse(input);
    const freeze = (data) => {
      if (isValid(data)) {
        data.value = Object.freeze(data.value);
      }
      return data;
    };
    return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
  }
  unwrap() {
    return this._def.innerType;
  }
}
ZodReadonly.create = (type, params) => {
  return new ZodReadonly({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodReadonly,
    ...processCreateParams(params)
  });
};
function cleanParams(params, data) {
  const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
  const p2 = typeof p === "string" ? { message: p } : p;
  return p2;
}
function custom(check, _params = {}, fatal) {
  if (check)
    return ZodAny.create().superRefine((data, ctx) => {
      const r = check(data);
      if (r instanceof Promise) {
        return r.then((r2) => {
          if (!r2) {
            const params = cleanParams(_params, data);
            const _fatal = params.fatal ?? fatal ?? true;
            ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
          }
        });
      }
      if (!r) {
        const params = cleanParams(_params, data);
        const _fatal = params.fatal ?? fatal ?? true;
        ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
      }
      return;
    });
  return ZodAny.create();
}
var late = {
  object: ZodObject.lazycreate
};
var ZodFirstPartyTypeKind;
(function(ZodFirstPartyTypeKind2) {
  ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
  ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
  ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
  ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
  ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
  ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
  ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
  ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
  ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
  ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
  ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
  ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
  ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
  ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
  ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
  ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
  ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
  ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
  ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
  ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
  ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
  ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
  ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
  ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
  ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
  ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
  ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
  ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
  ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
  ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
  ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
  ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
  ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
  ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
  ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
  ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
var instanceOfType = (cls, params = {
  message: `Input not instance of ${cls.name}`
}) => custom((data) => data instanceof cls, params);
var stringType = ZodString.create;
var numberType = ZodNumber.create;
var nanType = ZodNaN.create;
var bigIntType = ZodBigInt.create;
var booleanType = ZodBoolean.create;
var dateType = ZodDate.create;
var symbolType = ZodSymbol.create;
var undefinedType = ZodUndefined.create;
var nullType = ZodNull.create;
var anyType = ZodAny.create;
var unknownType = ZodUnknown.create;
var neverType = ZodNever.create;
var voidType = ZodVoid.create;
var arrayType = ZodArray.create;
var objectType = ZodObject.create;
var strictObjectType = ZodObject.strictCreate;
var unionType = ZodUnion.create;
var discriminatedUnionType = ZodDiscriminatedUnion.create;
var intersectionType = ZodIntersection.create;
var tupleType = ZodTuple.create;
var recordType = ZodRecord.create;
var mapType = ZodMap.create;
var setType = ZodSet.create;
var functionType = ZodFunction.create;
var lazyType = ZodLazy.create;
var literalType = ZodLiteral.create;
var enumType = ZodEnum.create;
var nativeEnumType = ZodNativeEnum.create;
var promiseType = ZodPromise.create;
var effectsType = ZodEffects.create;
var optionalType = ZodOptional.create;
var nullableType = ZodNullable.create;
var preprocessType = ZodEffects.createWithPreprocess;
var pipelineType = ZodPipeline.create;
var ostring = () => stringType().optional();
var onumber = () => numberType().optional();
var oboolean = () => booleanType().optional();
var coerce = {
  string: (arg) => ZodString.create({ ...arg, coerce: true }),
  number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
  boolean: (arg) => ZodBoolean.create({
    ...arg,
    coerce: true
  }),
  bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
  date: (arg) => ZodDate.create({ ...arg, coerce: true })
};
var NEVER = INVALID;
// src/serve/projection-policy.ts
import { ActorPointerSchema, EvidencePointerSchema, ResourcePointerSchema } from "@hasna/contracts";

// src/lib/guarded-project-mutation.ts
import { createHash } from "crypto";
var GUARDED_PROJECT_MUTATION_ROUTE = "projects.guarded-metadata-mutation.v1";
var COMPLETE_STABLE_PROJECT_ID_PATTERN = "^wks_[A-Za-z0-9_-]{12,}$";
var COMPLETE_STABLE_PROJECT_ID_RE = new RegExp(COMPLETE_STABLE_PROJECT_ID_PATTERN);
function assertCompleteStableProjectId(value) {
  if (!COMPLETE_STABLE_PROJECT_ID_RE.test(value)) {
    throw new Error("guarded project mutation requires a complete stable project id beginning with wks_; slugs, paths, names, and partial ids are refused");
  }
}
function assertPositiveBounds(bounds) {
  if (!Number.isInteger(bounds.response_byte_limit) || bounds.response_byte_limit <= 0) {
    throw new Error("response_byte_limit must be a positive integer");
  }
  if (!Number.isInteger(bounds.time_budget_ms) || bounds.time_budget_ms <= 0) {
    throw new Error("time_budget_ms must be a positive integer");
  }
}
function canonicalJson(value) {
  return JSON.stringify(canonicalize(value));
}
function canonicalize(value) {
  if (Array.isArray(value))
    return value.map((item) => canonicalize(item));
  if (!value || typeof value !== "object")
    return value;
  const out = {};
  for (const key of Object.keys(value).sort()) {
    const next = value[key];
    if (next !== undefined)
      out[key] = canonicalize(next);
  }
  return out;
}
function sha256(value) {
  return createHash("sha256").update(value).digest("hex");
}
function requestDigest(patch) {
  return sha256(canonicalJson(normalizePatch(patch)));
}
function preconditionDigest(input) {
  return sha256(canonicalJson({ project_id: input.project_id, revision: input.expected_revision }));
}
function deriveGuardedIdempotencyKey(input) {
  return `gpm_${sha256(canonicalJson({
    route: GUARDED_PROJECT_MUTATION_ROUTE,
    operation_id: input.operation_id,
    step_id: input.step_id,
    direction: input.direction,
    target_id: input.target_id,
    request_digest: input.request_digest,
    precondition_digest: input.precondition_digest
  })).slice(0, 48)}`;
}
function normalizePatch(patch) {
  const allowed = {};
  const keys = [
    "name",
    "slug",
    "description",
    "kind",
    "status",
    "root_id",
    "recipe_id",
    "canonical_machine",
    "primary_path",
    "git_remote",
    "s3_bucket",
    "s3_prefix",
    "tags",
    "integrations",
    "metadata",
    "last_opened_at",
    "agent_id",
    "source",
    "prompt",
    "command"
  ];
  for (const key of keys) {
    if (patch[key] !== undefined) {
      allowed[key] = patch[key];
    }
  }
  return canonicalize(allowed);
}
function workspaceRevision(workspace) {
  if (!workspace.updated_at)
    throw new Error(`project ${workspace.id} has no authority revision`);
  return workspace.updated_at;
}
function workspaceSnapshot(workspace) {
  return canonicalize(workspace);
}
function rowToGuardedReceipt(row) {
  return {
    receipt_id: row.receipt_id,
    operation_id: row.operation_id,
    step_id: row.step_id,
    direction: row.direction,
    idempotency_key: row.idempotency_key,
    target_id: row.target_id,
    request_digest: row.request_digest,
    precondition_digest: row.precondition_digest,
    expected_revision: row.expected_revision,
    outcome: row.outcome,
    reason: row.reason,
    result_project_id: row.result_project_id,
    duplicate_of_receipt_id: row.duplicate_of_receipt_id,
    before: parseJson(row.before_json),
    after: parseJson(row.after_json),
    post_revision: row.post_revision,
    created_at: row.created_at
  };
}
function parseJson(raw) {
  if (!raw)
    return null;
  return JSON.parse(raw);
}
function timedOut(startedAtMs, timeBudgetMs) {
  return Date.now() - startedAtMs > timeBudgetMs;
}
function responseControl(payload, bounds, startedAtMs, operation = "guarded mutation", completeness = {
  complete: true,
  truncated: false
}) {
  assertPositiveBounds(bounds);
  const bytes = Buffer.byteLength(JSON.stringify(payload), "utf8");
  const elapsed = Math.max(Date.now() - startedAtMs, 0);
  if (bytes > bounds.response_byte_limit) {
    throw new Error(`${operation} response byte budget exceeded: ${bytes} > ${bounds.response_byte_limit}`);
  }
  if (elapsed > bounds.time_budget_ms) {
    throw new Error(`${operation} time budget exceeded: ${elapsed} > ${bounds.time_budget_ms}`);
  }
  return {
    response_byte_limit: bounds.response_byte_limit,
    time_budget_ms: bounds.time_budget_ms,
    response_bytes: bytes,
    elapsed_ms: elapsed,
    ...completeness
  };
}
function withResponseControl(payload, bounds, startedAtMs, operation = "guarded mutation", completeness = {
  complete: true,
  truncated: false
}) {
  const envelope = {
    ...payload,
    response_control: {
      response_byte_limit: bounds.response_byte_limit,
      time_budget_ms: bounds.time_budget_ms,
      response_bytes: 0,
      elapsed_ms: 0,
      ...completeness
    }
  };
  envelope.response_control = responseControl(envelope, bounds, startedAtMs, operation, completeness);
  envelope.response_control = responseControl(envelope, bounds, startedAtMs, operation, completeness);
  return envelope;
}
function buildGuardedProjectReadResult(project, input, startedAtMs, resourceLinks = { links: [], max_items: 1000, collection_digest: sha256("[]") }) {
  assertCompleteStableProjectId(input.project_id);
  assertPositiveBounds(input);
  if (project.id !== input.project_id) {
    throw new Error(`guarded project read target mismatch: requested ${input.project_id}, received ${project.id}`);
  }
  return withResponseControl({
    ok: true,
    project_id: project.id,
    project,
    current_revision: workspaceRevision(project),
    resource_links: resourceLinks.links,
    resource_link_count: resourceLinks.links.length,
    resource_link_max_items: resourceLinks.max_items,
    resource_link_collection_digest: resourceLinks.collection_digest
  }, input, startedAtMs, "guarded project read");
}
function buildReceiptId(input) {
  return `gpmr_${sha256(canonicalJson(input)).slice(0, 32)}`;
}

// src/serve/projection-policy.ts
var exact = exports_external.string().trim().min(1).max(200).refine((v) => !v.includes("*"));
var tenant = exports_external.string().uuid().transform((v) => v.toLowerCase());
var digest = exports_external.string().regex(/^[a-f0-9]{64}$/);
var subject = exports_external.object({ app: exact, tenant_id: tenant, agent: exact, kid: exact.optional() }).strict();
var owner = ActorPointerSchema.refine((v) => Boolean(v.provider) && !v.id.includes("*") && !v.provider.includes("*"), "owner must have an exact authority");
var evidence = EvidencePointerSchema.refine((v) => Boolean(v.uri && v.sha256), "policy evidence requires uri and digest");
var resource = ResourcePointerSchema.refine((v) => Boolean(v.sourcePackage && v.externalId), "policy reference requires source package and immutable external id");
var ProjectionPolicySchema = exports_external.object({
  schema: exports_external.literal("projects.projection_issuer_policy.v1"),
  id: exact,
  revision: exports_external.number().int().positive().max(Number.MAX_SAFE_INTEGER),
  digest,
  state: exports_external.enum(["active", "disabled"]),
  authority: exact,
  evidence_refs: exports_external.array(evidence).min(1).max(32),
  bindings: exports_external.array(exports_external.object({
    project_id: exports_external.string().regex(new RegExp(COMPLETE_STABLE_PROJECT_ID_PATTERN)),
    tenant_id: tenant,
    subjects: exports_external.array(subject).min(1).max(64),
    operations: exports_external.array(exports_external.enum(["issue", "read"])).min(1).max(2),
    owner_refs: exports_external.array(owner).min(1).max(32),
    repository_ref: resource.refine((v) => v.kind === "repo"),
    workspace_ref: resource.refine((v) => v.kind === "project")
  }).strict()).min(1).max(256)
}).strict();

class ProjectionError extends Error {
  status;
  code;
  constructor(status, code) {
    super(code);
    this.status = status;
    this.code = code;
  }
}
function projectionPolicyDigest(value) {
  const { digest: _, ...body } = value;
  return sha256(canonicalJson(body));
}
function freeze(value) {
  if (value && typeof value === "object") {
    Object.values(value).forEach(freeze);
    Object.freeze(value);
  }
  return value;
}
function validateProjectionPolicy(input) {
  try {
    if (Buffer.byteLength(JSON.stringify(input)) > 262144)
      return;
    const p = ProjectionPolicySchema.parse(input);
    if (p.digest !== projectionPolicyDigest(p))
      return;
    const projects = new Set;
    for (const b of p.bindings) {
      if (projects.has(b.project_id) || b.workspace_ref.externalId !== b.project_id || b.workspace_ref.sourcePackage !== "@hasna/projects")
        return;
      projects.add(b.project_id);
      if (new Set(b.operations).size !== b.operations.length)
        return;
      if (new Set(b.owner_refs.map((v) => `${v.kind}:${v.id}`)).size !== b.owner_refs.length)
        return;
      for (let i = 0;i < b.subjects.length; i++) {
        const s = b.subjects[i];
        if (s.tenant_id !== b.tenant_id)
          return;
        if (b.subjects.slice(0, i).some((v) => v.app === s.app && v.agent === s.agent && (!v.kid || !s.kid || v.kid === s.kid)))
          return;
      }
    }
    return freeze(p);
  } catch {
    return;
  }
}
function authorizeProjection(policy, principal, projectId, operation) {
  if (!policy || policy.state !== "active")
    throw new ProjectionError(403, "PROJECTION_POLICY_UNAVAILABLE");
  const tid = tenant.safeParse(principal.tid);
  const b = policy.bindings.find((v) => v.project_id === projectId);
  if (!tid.success || !b || tid.data !== b.tenant_id || !principal.agent || !principal.scopes.includes(operation === "issue" ? "projects:write" : "projects:read") || !b.operations.includes(operation) || !b.subjects.some((s) => s.app === principal.app && s.agent === principal.agent && s.tenant_id === tid.data && (!s.kid || s.kid === principal.kid))) {
    throw new ProjectionError(403, "PROJECTION_NOT_AUTHORIZED");
  }
  return b;
}
function projectionSubject(principal) {
  return { app: principal.app, tenant_id: principal.tid.toLowerCase(), agent: principal.agent, kid: principal.kid };
}

// src/serve/projection-http.ts
function loadProjectionPolicy(path, json) {
  if (json !== undefined) {
    if (path !== undefined || Buffer.byteLength(json, "utf8") > 262144)
      return;
    try {
      return validateProjectionPolicy(JSON.parse(json));
    } catch {
      return;
    }
  }
  if (!path)
    return;
  let fd;
  try {
    fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
    const st = fstatSync(fd);
    if (!st.isFile() || st.size > 262144 || st.nlink !== 1 || st.mode & 18 || st.uid !== 0 && st.uid !== process.getuid?.())
      return;
    const buffer = Buffer.alloc(262145);
    const length = readSync(fd, buffer, 0, buffer.length, 0);
    if (length !== st.size || length > 262144)
      return;
    return validateProjectionPolicy(JSON.parse(buffer.subarray(0, length).toString("utf8")));
  } catch {
    return;
  } finally {
    if (fd !== undefined)
      closeSync(fd);
  }
}
async function readProjectionBody(request) {
  if (!request.body)
    throw new ProjectionError(400, "INVALID_PROJECTION_REQUEST");
  const reader = request.body.getReader();
  const chunks = [];
  let size = 0;
  let timer;
  try {
    return await Promise.race([
      (async () => {
        while (true) {
          const chunk = await reader.read();
          if (chunk.done)
            break;
          size += chunk.value.byteLength;
          if (size > 8192)
            throw new ProjectionError(413, "PROJECTION_REQUEST_TOO_LARGE");
          chunks.push(chunk.value);
        }
        try {
          return JSON.parse(Buffer.concat(chunks).toString("utf8"));
        } catch {
          throw new ProjectionError(400, "INVALID_PROJECTION_REQUEST");
        }
      })(),
      new Promise((_, reject) => {
        timer = setTimeout(() => reject(new ProjectionError(408, "PROJECTION_BODY_TIMEOUT")), 5000);
      })
    ]);
  } finally {
    clearTimeout(timer);
    reader.cancel().catch(() => {});
  }
}

// src/serve/index.ts
import { readFileSync as readFileSync3 } from "fs";
import { dirname as dirname3, join as join5 } from "path";
import { fileURLToPath as fileURLToPath2 } from "url";
import { ApiKeyStore } from "@hasna/contracts/auth";
import { resolveClientTransport as resolveClientTransport2 } from "@hasna/contracts/client";

// src/lib/client-configuration.ts
import {
  appConfigDiskValue,
  clientTransportEnvKeys,
  credentialOverrideEnvKey,
  credentialPointerEnvKey,
  keychainConfigValue,
  resolveCredential,
  CREDENTIAL_PROFILE_ENV_KEY
} from "@hasna/contracts/client";
function hostedConfigurationAbsent(app, env, credentials) {
  if (credentials?.apiKey !== undefined || credentials?.profile !== undefined)
    return false;
  const keys = clientTransportEnvKeys(app);
  for (const key of [
    ...keys.apiUrlKeys,
    ...keys.apiKeyKeys,
    credentialOverrideEnvKey(app),
    credentialPointerEnvKey(app),
    CREDENTIAL_PROFILE_ENV_KEY
  ]) {
    if (env[key] !== undefined)
      return false;
  }
  if (keychainConfigValue(app, env, credentials?.keychain) !== null)
    return false;
  if (appConfigDiskValue(app, env, keys.apiUrlKeys) !== null)
    return false;
  return resolveCredential(app, env, credentials) === null;
}
function unconfiguredForHostedUse(app, env, credentials) {
  try {
    return hostedConfigurationAbsent(app, env, credentials);
  } catch {
    return false;
  }
}

// src/generated/storage-kit/own.ts
function ownProp(source, key) {
  if (source === null || source === undefined)
    return;
  const kind = typeof source;
  if (kind !== "object" && kind !== "function")
    return;
  if (!Object.hasOwn(source, key))
    return;
  return source[key];
}
function ownString(source, key) {
  const value = ownProp(source, key);
  return typeof value === "string" ? value : undefined;
}
// src/generated/storage-kit/tls.ts
import { readFileSync } from "fs";
var PG_TLS_QUERY_PARAMETERS = new Set([
  "ssl",
  "sslmode",
  "sslrootcert",
  "sslcert",
  "sslkey",
  "sslpassword",
  "sslnegotiation",
  "uselibpqcompat"
]);
var EXPLICIT_SSL_ON_VALUES = new Set(["1", "true", "yes", "on", "require"]);
var EXPLICIT_SSL_OFF_VALUES = new Set(["0", "false", "no", "off", "disable"]);
var SSLMODE_VALUES = new Map([
  ["disable", "disable"],
  ["allow", "prefer"],
  ["prefer", "prefer"],
  ["require", "require"],
  ["verify-ca", "verify-ca"],
  ["verify-full", "verify-full"]
]);
function connectionStringParts(connectionString) {
  const queryStart = connectionString.indexOf("?");
  if (queryStart === -1) {
    return { base: connectionString, fragment: "", params: new URLSearchParams };
  }
  const base = connectionString.slice(0, queryStart);
  const queryAndFragment = connectionString.slice(queryStart + 1);
  const fragmentStart = queryAndFragment.indexOf("#");
  const query = fragmentStart === -1 ? queryAndFragment : queryAndFragment.slice(0, fragmentStart);
  const fragment = fragmentStart === -1 ? "" : queryAndFragment.slice(fragmentStart);
  return { base, fragment, params: new URLSearchParams(query) };
}
function tlsQueryValues(connectionString) {
  const values = new Map;
  for (const [key, value] of connectionStringParts(connectionString).params) {
    const normalized = key.toLowerCase();
    if (PG_TLS_QUERY_PARAMETERS.has(normalized))
      values.set(normalized, value);
  }
  return values;
}
function connectionStringWithoutTlsParameters(connectionString) {
  const { base, fragment, params } = connectionStringParts(connectionString);
  for (const key of [...params.keys()]) {
    if (PG_TLS_QUERY_PARAMETERS.has(key.toLowerCase()))
      params.delete(key);
  }
  const query = params.toString();
  return `${base}${query ? `?${query}` : ""}${fragment}`;
}
function rawSslMode(values) {
  const raw = values.get("sslmode");
  return raw === undefined ? undefined : raw.trim().toLowerCase();
}
function sslNegotiationFromConnectionString(connectionString) {
  const value = tlsQueryValues(connectionString).get("sslnegotiation")?.trim().toLowerCase();
  if (!value)
    return;
  if (value === "postgres" || value === "direct")
    return value;
  throw new Error(`Unknown sslnegotiation '${value}' in connection string; expected postgres or direct.`);
}
function sslModeFromConnectionString(connectionString) {
  const values = tlsQueryValues(connectionString);
  const sslmode = rawSslMode(values);
  if (sslmode !== undefined) {
    const resolved = SSLMODE_VALUES.get(sslmode);
    if (resolved)
      return resolved;
    throw new Error(`Unknown sslmode '${sslmode}' in connection string; expected one of ` + `${[...SSLMODE_VALUES.keys()].join(", ")}. Remove the parameter entirely to defer to ` + `PGSSLMODE \u2014 an empty value is not how that is spelled.`);
  }
  if (values.has("ssl")) {
    const ssl = values.get("ssl")?.trim().toLowerCase() ?? "";
    if (EXPLICIT_SSL_ON_VALUES.has(ssl))
      return "require";
    if (!EXPLICIT_SSL_OFF_VALUES.has(ssl)) {
      throw new Error(`Unknown ssl value '${ssl}' in connection string.`);
    }
    return "disable";
  }
  const sslnegotiation = values.get("sslnegotiation")?.trim().toLowerCase();
  if (sslnegotiation === "direct")
    return "require";
  return "disable";
}
function loadCaBundle(connectionString, options) {
  const env = ownProp(options, "env") ?? process.env;
  const ca = ownString(options, "ca");
  if (ca && ca.trim())
    return ca;
  const sslRootCert = tlsQueryValues(connectionString).get("sslrootcert")?.trim();
  const path = ownString(options, "caCertPath") ?? (sslRootCert ? sslRootCert : undefined) ?? ownString(env, "PGSSLROOTCERT") ?? ownString(env, "NODE_EXTRA_CA_CERTS");
  if (path && path.trim())
    return readFileSync(path.trim(), "utf8");
  return null;
}
function loadClientCertificate(connectionString) {
  const values = tlsQueryValues(connectionString);
  const material = {};
  const certPath = values.get("sslcert")?.trim();
  if (certPath)
    material.cert = readFileSync(certPath, "utf8");
  const keyPath = values.get("sslkey")?.trim();
  if (keyPath)
    material.key = readFileSync(keyPath, "utf8");
  const passphrase = values.get("sslpassword");
  if (passphrase)
    material.passphrase = passphrase;
  return material;
}
function resolveTlsConfig(connectionString, options = {}) {
  const mode = sslModeFromConnectionString(connectionString);
  if (mode === "disable") {
    const values = tlsQueryValues(connectionString);
    const sslmode = rawSslMode(values);
    const ssl = values.get("ssl")?.trim().toLowerCase();
    const explicitlyOff = sslmode === "disable" || ssl !== undefined && EXPLICIT_SSL_OFF_VALUES.has(ssl);
    return explicitlyOff ? false : undefined;
  }
  const ca = loadCaBundle(connectionString, options);
  const clientCertificate = loadClientCertificate(connectionString);
  if (mode === "prefer" || mode === "require") {
    return { rejectUnauthorized: true, ...ca ? { ca } : {}, ...clientCertificate };
  }
  if (!ca) {
    throw new Error(`sslmode=${mode} requires a CA bundle. Set PGSSLROOTCERT (or pass caCertPath/ca) to the ` + `Amazon RDS global bundle: https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem`);
  }
  return { rejectUnauthorized: true, ca, ...clientCertificate };
}
// src/generated/storage-kit/query.ts
function wrapExecutor(executor) {
  return {
    async query(sql, params) {
      const result = await executor.query(sql, params);
      return { rows: result.rows, rowCount: result.rowCount ?? result.rows.length };
    },
    async many(sql, params) {
      const result = await executor.query(sql, params);
      return result.rows;
    },
    async get(sql, params) {
      const result = await executor.query(sql, params);
      return result.rows[0] ?? null;
    },
    async one(sql, params) {
      const result = await executor.query(sql, params);
      if (result.rows.length !== 1) {
        throw new Error(`Expected exactly one row, got ${result.rows.length}.`);
      }
      return result.rows[0];
    },
    async execute(sql, params) {
      await executor.query(sql, params);
    }
  };
}
function createQueryClient(pool) {
  const base = wrapExecutor(pool);
  return {
    ...base,
    pool,
    async transaction(fn) {
      const client = await pool.connect();
      try {
        await client.query("BEGIN");
        const result = await fn(wrapExecutor(client));
        await client.query("COMMIT");
        return result;
      } catch (error) {
        try {
          await client.query("ROLLBACK");
        } catch {}
        throw error;
      } finally {
        client.release();
      }
    },
    async close() {
      await pool.end();
    }
  };
}
// src/generated/storage-kit/pool.ts
import pg from "pg";
function ownPoolOptions(options) {
  const own = Object.create(null);
  const ca = ownString(options, "ca");
  if (ca !== undefined)
    own.ca = ca;
  const caCertPath = ownString(options, "caCertPath");
  if (caCertPath !== undefined)
    own.caCertPath = caCertPath;
  const env = ownProp(options, "env");
  if (env !== undefined)
    own.env = env;
  const max = ownProp(options, "max");
  if (max !== undefined)
    own.max = max;
  const idleTimeoutMillis = ownProp(options, "idleTimeoutMillis");
  if (idleTimeoutMillis !== undefined)
    own.idleTimeoutMillis = idleTimeoutMillis;
  const connectionTimeoutMillis = ownProp(options, "connectionTimeoutMillis");
  if (connectionTimeoutMillis !== undefined)
    own.connectionTimeoutMillis = connectionTimeoutMillis;
  const applicationName = ownString(options, "applicationName");
  if (applicationName !== undefined)
    own.applicationName = applicationName;
  return own;
}
function createPgPool(options) {
  const connectionString = ownString(options, "connectionString");
  if (!connectionString || !connectionString.trim()) {
    throw new Error("createPgPool requires an own `connectionString` on the options object.");
  }
  const own = ownPoolOptions(options);
  const ssl = resolveTlsConfig(connectionString, {
    ...own.ca !== undefined ? { ca: own.ca } : {},
    ...own.caCertPath !== undefined ? { caCertPath: own.caCertPath } : {},
    ...own.env !== undefined ? { env: own.env } : {}
  });
  const config = {
    connectionString: connectionStringWithoutTlsParameters(connectionString)
  };
  if (ssl !== undefined)
    config.ssl = ssl;
  const sslnegotiation = sslNegotiationFromConnectionString(connectionString);
  if (sslnegotiation !== undefined)
    config.sslnegotiation = sslnegotiation;
  if (own.max !== undefined)
    config.max = own.max;
  if (own.idleTimeoutMillis !== undefined)
    config.idleTimeoutMillis = own.idleTimeoutMillis;
  if (own.connectionTimeoutMillis !== undefined)
    config.connectionTimeoutMillis = own.connectionTimeoutMillis;
  if (own.applicationName !== undefined)
    config.application_name = own.applicationName;
  return new pg.Pool(config);
}
// src/generated/storage-kit/migrations.ts
import { createHash as createHash2 } from "crypto";
var TRANSACTION_CONTROL_STATEMENT = /^(?:BEGIN|START\s+TRANSACTION|COMMIT|END|ROLLBACK|ABORT|SAVEPOINT|RELEASE|PREPARE\s+TRANSACTION|SET\s+(?:SESSION\s+CHARACTERISTICS\s+AS\s+)?TRANSACTION)\b/i;
function stripSqlBodies(sql) {
  let out = "";
  let i = 0;
  while (i < sql.length) {
    const ch = sql[i];
    const next = sql[i + 1];
    if (ch === "-" && next === "-") {
      while (i < sql.length && sql[i] !== `
`) {
        out += " ";
        i++;
      }
      continue;
    }
    if (ch === "/" && next === "*") {
      let depth = 1;
      out += "  ";
      i += 2;
      while (i < sql.length && depth > 0) {
        if (sql[i] === "/" && sql[i + 1] === "*") {
          depth++;
          out += "  ";
          i += 2;
        } else if (sql[i] === "*" && sql[i + 1] === "/") {
          depth--;
          out += "  ";
          i += 2;
        } else {
          out += " ";
          i++;
        }
      }
      continue;
    }
    if (ch === "$") {
      const match = /^\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$/.exec(sql.slice(i));
      if (match) {
        const tag = match[0];
        out += " ".repeat(tag.length);
        i += tag.length;
        const end = sql.indexOf(tag, i);
        if (end === -1) {
          out += " ".repeat(sql.length - i);
          i = sql.length;
        } else {
          out += " ".repeat(end - i + tag.length);
          i = end + tag.length;
        }
        continue;
      }
    }
    if (ch === "'" || ch === '"') {
      const quote = ch;
      const escaped = quote === "'" && /[eE]/.test(sql[i - 1] ?? "") && !/[A-Za-z0-9_$]/.test(sql[i - 2] ?? "");
      out += " ";
      i++;
      while (i < sql.length) {
        if (escaped && sql[i] === "\\") {
          out += "  ";
          i += 2;
          continue;
        }
        if (sql[i] === quote) {
          if (sql[i + 1] === quote) {
            out += "  ";
            i += 2;
            continue;
          }
          out += " ";
          i++;
          break;
        }
        out += " ";
        i++;
      }
      continue;
    }
    out += ch;
    i++;
  }
  return out;
}
function assertNoTransactionControl(migration) {
  for (const statement of stripSqlBodies(migration.sql).split(";")) {
    if (TRANSACTION_CONTROL_STATEMENT.test(statement.trim())) {
      throw new Error(`Migration '${migration.id}' contains a transaction-control statement; ` + "rewrite it as plain DDL so the ledger can apply and record it atomically.");
    }
  }
}
var DEFAULT_MIGRATION_LEDGER_TABLE = "schema_migrations";
function checksumSql(sql) {
  const normalized = sql.trim().replace(/\r\n/g, `
`);
  return `sha256:${createHash2("sha256").update(normalized).digest("hex")}`;
}
function defineMigration(id, sql) {
  return Object.freeze({ id, sql: sql.trim(), checksum: checksumSql(sql) });
}

class MigrationLedger {
  client;
  migrations;
  ledgerTable;
  acknowledgedLegacyIds;
  constructor(client, migrations, options = {}) {
    this.client = client;
    this.migrations = migrations;
    this.ledgerTable = ownString(options, "ledgerTable") ?? DEFAULT_MIGRATION_LEDGER_TABLE;
    const seen = new Set;
    for (const migration of migrations) {
      if (seen.has(migration.id))
        throw new Error(`Duplicate migration id: ${migration.id}`);
      seen.add(migration.id);
    }
    const rawAcknowledged = ownProp(options, "acknowledgedLegacyIds");
    if (rawAcknowledged !== undefined) {
      if (!Array.isArray(rawAcknowledged) || rawAcknowledged.some((id) => typeof id !== "string")) {
        throw new Error("acknowledgedLegacyIds must be an array of migration id strings");
      }
      this.acknowledgedLegacyIds = new Set(rawAcknowledged);
    } else {
      this.acknowledgedLegacyIds = new Set;
    }
    for (const id of this.acknowledgedLegacyIds) {
      if (seen.has(id)) {
        throw new Error(`Acknowledged legacy migration id '${id}' is also declared as a migration.`);
      }
    }
  }
  async ensureLedger() {
    await this.client.execute(`CREATE TABLE IF NOT EXISTS ${this.ledgerTable} (
         id TEXT PRIMARY KEY,
         checksum TEXT NOT NULL,
         applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
       )`);
  }
  async listApplied() {
    await this.ensureLedger();
    return this.readApplied();
  }
  async readApplied() {
    const rows = await this.client.many(`SELECT id, checksum, applied_at FROM ${this.ledgerTable} ORDER BY id ASC`);
    return rows.map((row) => ({
      id: row.id,
      checksum: row.checksum,
      appliedAt: row.applied_at instanceof Date ? row.applied_at.toISOString() : String(row.applied_at)
    }));
  }
  buildPlan(applied) {
    const known = new Set(this.migrations.map((m) => m.id));
    for (const row of applied) {
      if (known.has(row.id) || this.acknowledgedLegacyIds.has(row.id)) {
        continue;
      }
      throw new Error(`Applied migration '${row.id}' is not recognized by this build (downgrade?).`);
    }
    const appliedById = new Map(applied.map((row) => [row.id, row]));
    for (const migration of this.migrations) {
      const existing = appliedById.get(migration.id);
      if (existing && existing.checksum !== migration.checksum) {
        throw new Error(`Migration checksum mismatch for '${migration.id}': the SQL changed after it was applied.`);
      }
    }
    return this.migrations.map((migration) => ({
      migration,
      state: appliedById.has(migration.id) ? "already_applied" : "pending"
    }));
  }
  async migrate(opts = {}) {
    const dryRun = ownProp(opts, "dryRun") === true;
    for (const migration of this.migrations)
      assertNoTransactionControl(migration);
    await this.ensureLedger();
    const applied = await this.readApplied();
    const plan = this.buildPlan(applied);
    if (dryRun)
      return { dryRun, applied, plan };
    for (const item of plan) {
      if (item.state === "already_applied")
        continue;
      await this.client.execute(item.migration.sql);
      await this.client.execute(`INSERT INTO ${this.ledgerTable} (id, checksum, applied_at) VALUES ($1, $2, now())`, [item.migration.id, item.migration.checksum]);
    }
    return { dryRun, applied: await this.readApplied(), plan };
  }
}
// src/lib/redaction.ts
var PROJECT_REDACTED_VALUE = "[REDACTED]";
var SENSITIVE_KEY_PATTERN = /(^|[^a-z0-9])(password|passwd|pwd|secret|token|api[-_]?key|apikey|access[-_]?key|private[-_]?key|client[-_]?secret|credential|credentials|authorization|auth[-_]?header|cookie|session[-_]?token|npmrc|database[-_]?url|connection[-_]?string|dsn)([^a-z0-9]|$)/i;
var URL_CREDENTIAL_PATTERN = /\b([a-z][a-z0-9+.-]*:\/\/)([^/\s:@]+):([^/\s@]+)@/gi;
var AUTH_HEADER_PATTERN = /\b(Bearer|Basic)\s+[A-Za-z0-9+/_=:.~\-]+/gi;
var CLI_SECRET_FLAG_PATTERN = /((?:^|[\s,;])--?(?:password|passwd|pwd|secret|token|api[-_]?key|apikey|access[-_]?key|private[-_]?key|client[-_]?secret|credential|credentials|authorization|auth[-_]?header|cookie|session[-_]?token|npmrc|database[-_]?url|connection[-_]?string|dsn)(?:=|\s+))([^\s"'`,;]+)/gi;
var PRIVATE_KEY_PATTERN = /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g;
var KNOWN_SECRET_VALUE_PATTERN = /\b(sk-[A-Za-z0-9_-]{16,}|ghp\x5f[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,}|npm_[A-Za-z0-9_]{20,}|xox[baprs]-[A-Za-z0-9-]{10,}|AKIA[0-9A-Z]{16})\b/g;
var ENV_ASSIGNMENT_PATTERN = /(^|[\s,;])([A-Za-z_][A-Za-z0-9_]*(?:TOKEN|SECRET|PASSWORD|API_KEY|ACCESS_KEY|PRIVATE_KEY|CLIENT_SECRET|COOKIE|DSN|DATABASE_URL|CONNECTION_STRING)[A-Za-z0-9_]*)=([^\s"'`,;]+)/g;
var MAYBE_SECRET_TEXT_PATTERN = /:\/\/|PRIVATE KEY|Bearer\s|Basic\s|TOKEN|SECRET|PASSWORD|API_KEY|ACCESS_KEY|PRIVATE_KEY|CLIENT_SECRET|COOKIE|DSN|DATABASE_URL|CONNECTION_STRING|sk-|ghp\x5f|github_pat_|npm_|xox[baprs]-|AKIA/i;
function isSensitiveProjectKey(key) {
  return SENSITIVE_KEY_PATTERN.test(key.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase());
}
function redactProjectText(value) {
  if (!MAYBE_SECRET_TEXT_PATTERN.test(value))
    return value;
  return value.replace(PRIVATE_KEY_PATTERN, PROJECT_REDACTED_VALUE).replace(URL_CREDENTIAL_PATTERN, `$1${PROJECT_REDACTED_VALUE}@`).replace(AUTH_HEADER_PATTERN, `$1 ${PROJECT_REDACTED_VALUE}`).replace(CLI_SECRET_FLAG_PATTERN, `$1${PROJECT_REDACTED_VALUE}`).replace(KNOWN_SECRET_VALUE_PATTERN, PROJECT_REDACTED_VALUE).replace(ENV_ASSIGNMENT_PATTERN, `$1$2=${PROJECT_REDACTED_VALUE}`);
}

// src/serve/projection-source.ts
function projectionCanonicalJson(value) {
  let remaining = 1e5;
  function copy(input, depth) {
    if (--remaining < 0 || depth > 64)
      throw new ProjectionError(422, "PROJECTION_SOURCE_STRUCTURE_LIMIT");
    if (Array.isArray(input))
      return input.map((item) => copy(item, depth + 1));
    if (!input || typeof input !== "object")
      return input;
    const output = Object.create(null);
    for (const key of Object.keys(input).sort()) {
      const item = input[key];
      if (item !== undefined)
        output[key] = copy(item, depth + 1);
    }
    return output;
  }
  return JSON.stringify(copy(value, 0));
}
function unsafeUrl(text) {
  let decoded = text;
  let candidatesRemaining = 16384;
  let parseUnitsRemaining = 16777216;
  if (text.length > 1048576)
    return true;
  for (let pass = 0;pass < 8; pass++) {
    const inspected = decoded.replace(/[\t\n\r]/g, "");
    const tokens = inspected.matchAll(/[^\s<>"'`]+/gu);
    for (const tokenMatch of tokens) {
      const token = tokenMatch[0];
      const starts = new Set([0]);
      for (const match of token.matchAll(/[a-z][a-z0-9+.-]*:\/\/|\/\//gi))
        starts.add(match.index);
      for (const match of token.matchAll(/[({=,;]/g))
        starts.add(match.index + 1);
      for (const start of starts) {
        if (--candidatesRemaining < 0)
          return true;
        const candidate = token.slice(start);
        if (!candidate)
          continue;
        const remainder = inspected.slice(tokenMatch.index + start);
        for (const spelling of new Set([candidate, remainder])) {
          for (const representation of [spelling, `https://${spelling.replace(/^\/\//, "")}`]) {
            parseUnitsRemaining -= representation.length;
            if (parseUnitsRemaining < 0)
              return true;
            try {
              const url = new URL(representation);
              if (url.username || url.password || url.search.length > 1 || url.hash.length > 1)
                return true;
            } catch {}
          }
        }
      }
    }
    let next;
    try {
      next = decodeURIComponent(decoded);
    } catch {
      return /%(?:[0-9a-f]{2})/i.test(decoded);
    }
    if (next === decoded)
      return false;
    decoded = next;
  }
  return true;
}
function assertProjectionSourceSafe(value) {
  let remaining = 1e5;
  function inspect(input, depth) {
    if (--remaining < 0 || depth > 64)
      throw new ProjectionError(422, "PROJECTION_SOURCE_STRUCTURE_LIMIT");
    if (typeof input === "string") {
      if (redactProjectText(input) !== input || unsafeUrl(input))
        throw new ProjectionError(422, "PROJECTION_SOURCE_REQUIRES_REDACTION");
    } else if (Array.isArray(input))
      input.forEach((item) => inspect(item, depth + 1));
    else if (input && typeof input === "object") {
      for (const key of Object.keys(input)) {
        if (isSensitiveProjectKey(key))
          throw new ProjectionError(422, "PROJECTION_SOURCE_REQUIRES_REDACTION");
        inspect(key, depth + 1);
        inspect(input[key], depth + 1);
      }
    }
  }
  inspect(value, 0);
}

// src/serve/product-projection.ts
import { ProductProjectionSchema, computeDeploymentRecordDigest } from "@hasna/contracts";
var ProjectionIssueSchema = exports_external.object({
  request_id: exports_external.string().uuid(),
  expected_revision: exports_external.string().min(1).max(200),
  project_digest: exports_external.string().regex(/^[a-f0-9]{64}$/),
  resource_link_collection_digest: exports_external.string().regex(/^[a-f0-9]{64}$/),
  resource_link_max_items: exports_external.number().int().min(1).max(1000),
  response_byte_limit: exports_external.number().int().min(1024).max(1048576),
  time_budget_ms: exports_external.number().int().min(1).max(30000)
}).strict();
var ProjectionReadSchema = ProjectionIssueSchema.pick({ response_byte_limit: true, time_budget_ms: true });
var PROJECTION_RECEIPT_PATTERN = /^ppr_[a-f0-9]{64}$/;
function parseProjectionInput(schema, input) {
  const result = schema.safeParse(input);
  if (!result.success)
    throw new ProjectionError(400, "INVALID_PROJECTION_REQUEST");
  return result.data;
}
function bounds(value, input, started) {
  if (Date.now() - started > input.time_budget_ms || Buffer.byteLength(projectionCanonicalJson(value)) > input.response_byte_limit)
    throw new ProjectionError(422, "PROJECTION_BOUNDS_EXCEEDED");
}
function decoded(row) {
  return JSON.parse(projectionCanonicalJson(typeof row.receipt_json === "string" ? JSON.parse(row.receipt_json) : row.receipt_json));
}
async function issueProductProjection(db, snapshot, policy, principal, projectId, raw) {
  const started = Date.now();
  const binding = authorizeProjection(policy, principal, projectId, "issue");
  const input = parseProjectionInput(ProjectionIssueSchema, raw);
  const receiptId = `ppr_${sha256(input.request_id)}`;
  const subject2 = projectionSubject(principal);
  const requestDigest2 = sha256(projectionCanonicalJson({ project_id: projectId, subject: subject2, input, policy_digest: policy.digest }));
  await db.execute("SELECT set_config('statement_timeout', $1, true)", [String(input.time_budget_ms)]);
  await db.execute("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", [receiptId]);
  const prior = await db.get("SELECT request_digest, receipt_json FROM product_projection_receipts WHERE receipt_id = $1", [receiptId]);
  if (prior) {
    if (prior.request_digest !== requestDigest2)
      throw new ProjectionError(409, "PROJECTION_IDEMPOTENCY_CONFLICT");
    const receipt2 = decoded(prior);
    bounds(receipt2, input, started);
    return receipt2;
  }
  const read = await snapshot({ project_id: projectId, ...input }, started);
  const projectDigest = sha256(projectionCanonicalJson(read.project));
  if (read.current_revision !== input.expected_revision || projectDigest !== input.project_digest || read.resource_link_collection_digest !== input.resource_link_collection_digest)
    throw new ProjectionError(409, "PROJECTION_SOURCE_PRECONDITION_FAILED");
  const sequence = await db.one("SELECT nextval('product_projection_revision_seq')::text AS revision");
  const revision = Number(sequence.revision);
  if (!Number.isSafeInteger(revision) || revision <= 0)
    throw new ProjectionError(503, "PROJECTION_REVISION_EXHAUSTED");
  const time = await db.one(`SELECT to_char(clock_timestamp() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS issued_at`);
  const lifecycle = read.project.status;
  const source = {
    project: read.project,
    revision: read.current_revision,
    project_digest: projectDigest,
    resource_links: read.resource_links,
    resource_link_collection_digest: read.resource_link_collection_digest
  };
  const record = {
    schema: "hasna.product_projection.v1",
    id: receiptId,
    createdAt: time.issued_at,
    producer: { kind: "service", id: "@hasna/projects", provider: "@hasna/projects" },
    revision,
    sourceRevision: revision,
    sourceProjectRef: { kind: "project", id: projectId, sourcePackage: "@hasna/projects", externalId: projectId, tags: [] },
    slug: read.project.slug,
    displayName: read.project.name,
    repositoryRef: binding.repository_ref,
    workspaceRef: binding.workspace_ref,
    lifecycle,
    ownerRefs: binding.owner_refs,
    projectedAt: time.issued_at,
    sourceEvidenceRefs: [
      ...policy.evidence_refs,
      { id: `@hasna/projects:${receiptId}:source`, kind: "report", sha256: sha256(projectionCanonicalJson(source)) },
      { id: `@hasna/projects:policy:${policy.id}:${policy.revision}`, kind: "report", sha256: policy.digest }
    ]
  };
  const parsed = ProductProjectionSchema.safeParse({ ...record, digest: computeDeploymentRecordDigest(record) });
  if (!parsed.success)
    throw new ProjectionError(422, "PROJECTION_SOURCE_NOT_REPRESENTABLE");
  const receipt = {
    schema: "projects.product_projection_receipt.v1",
    receipt_id: receiptId,
    project_id: projectId,
    tenant_id: binding.tenant_id,
    issued_revision: revision,
    issued_at: time.issued_at,
    request: input,
    request_digest: requestDigest2,
    subject: subject2,
    policy: { id: policy.id, revision: policy.revision, digest: policy.digest, authority: policy.authority },
    source,
    projection: parsed.data
  };
  const payload = projectionCanonicalJson(receipt);
  assertProjectionSourceSafe(receipt);
  bounds(receipt, input, started);
  await db.execute(`INSERT INTO product_projection_receipts
    (receipt_id, project_id, tenant_id, issued_revision, request_digest, receipt_json)
    VALUES ($1, $2, $3, $4, $5, $6::jsonb)`, [receiptId, projectId, binding.tenant_id, revision, requestDigest2, payload]);
  const saved = await db.one("SELECT receipt_json FROM product_projection_receipts WHERE receipt_id = $1", [receiptId]);
  if (projectionCanonicalJson(decoded(saved)) !== payload)
    throw new ProjectionError(500, "PROJECTION_RECEIPT_READBACK_MISMATCH");
  bounds(receipt, input, started);
  return JSON.parse(payload);
}
async function readProductProjection(db, policy, principal, projectId, receiptId, raw) {
  const started = Date.now();
  const binding = authorizeProjection(policy, principal, projectId, "read");
  const input = parseProjectionInput(ProjectionReadSchema, raw);
  if (!PROJECTION_RECEIPT_PATTERN.test(receiptId))
    throw new ProjectionError(400, "INVALID_PROJECTION_RECEIPT_ID");
  await db.execute("SELECT set_config('statement_timeout', $1, true)", [String(input.time_budget_ms)]);
  const row = await db.get(`SELECT receipt_json FROM product_projection_receipts
    WHERE receipt_id = $1 AND project_id = $2 AND tenant_id = $3`, [receiptId, projectId, binding.tenant_id]);
  if (!row)
    throw new ProjectionError(404, "PROJECTION_RECEIPT_NOT_FOUND");
  const receipt = decoded(row);
  bounds(receipt, input, started);
  return receipt;
}

// ../../node_modules/.bun/nanoid@5.1.16/node_modules/nanoid/index.js
import { webcrypto as crypto2 } from "crypto";

// ../../node_modules/.bun/nanoid@5.1.16/node_modules/nanoid/url-alphabet/index.js
var urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";

// ../../node_modules/.bun/nanoid@5.1.16/node_modules/nanoid/index.js
var POOL_SIZE_MULTIPLIER = 128;
var pool2;
var poolOffset;
function fillPool(bytes) {
  if (bytes < 0)
    throw new RangeError("Wrong ID size");
  try {
    if (!pool2 || pool2.length < bytes) {
      pool2 = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER);
      crypto2.getRandomValues(pool2);
      poolOffset = 0;
    } else if (poolOffset + bytes > pool2.length) {
      crypto2.getRandomValues(pool2);
      poolOffset = 0;
    }
  } catch (e) {
    pool2 = undefined;
    throw e;
  }
  poolOffset += bytes;
}
function random(bytes) {
  fillPool(bytes |= 0);
  return pool2.subarray(poolOffset - bytes, poolOffset);
}
function customRandom(alphabet, defaultSize, getRandom) {
  let safeByteCutoff = 256 - 256 % alphabet.length;
  if (safeByteCutoff === 256) {
    let mask = alphabet.length - 1;
    return (size = defaultSize) => {
      if (!size)
        return "";
      let id = "";
      while (true) {
        let bytes = getRandom(size);
        let i = size;
        while (i--) {
          id += alphabet[bytes[i] & mask];
          if (id.length >= size)
            return id;
        }
      }
    };
  }
  let step = Math.ceil(1.6 * 256 * defaultSize / safeByteCutoff);
  return (size = defaultSize) => {
    if (!size)
      return "";
    let id = "";
    while (true) {
      let bytes = getRandom(step);
      let i = step;
      while (i--) {
        if (bytes[i] < safeByteCutoff) {
          id += alphabet[bytes[i] % alphabet.length];
          if (id.length >= size)
            return id;
        }
      }
    }
  };
}
function customAlphabet(alphabet, size = 21) {
  return customRandom(alphabet, size, random);
}
function nanoid(size = 21) {
  fillPool(size |= 0);
  let id = "";
  for (let i = poolOffset - size;i < poolOffset; i++) {
    id += urlAlphabet[pool2[i] & 63];
  }
  return id;
}

// src/types/workspace.ts
var PROJECT_RESOURCE_AUTHORITIES = ["todos", "conversations", "knowledge", "mementos", "orgs", "contacts", "files"];
var PROJECT_RESOURCE_LINK_DEFAULT_MAX_ITEMS = 1000;
var PROJECT_RELATIONS = ["parent_of", "depends_on", "related_to"];
var PROJECT_RELATION_ACYCLIC_KINDS = ["parent_of", "depends_on"];
var PROJECT_RELATION_DEFAULT_MAX_ITEMS = 1000;

// src/lib/project-relations.ts
var PROJECT_RELATION_ID_PREFIX = "prr_";
function projectRelationId(fromProjectId, toProjectId) {
  assertProjectRelationEndpointId(fromProjectId, "from_project_id");
  assertProjectRelationEndpointId(toProjectId, "to_project_id");
  return `${PROJECT_RELATION_ID_PREFIX}${sha256(canonicalJson({
    from_project_id: fromProjectId,
    to_project_id: toProjectId
  })).slice(0, 36)}`;
}
var FILES_PROJECT_REFERENCE_RE = /^prj_[A-Za-z0-9_-]+$/;
var COMPLETE_STABLE_PROJECT_ID_RE2 = new RegExp(COMPLETE_STABLE_PROJECT_ID_PATTERN);
function assertProjectRelationEndpointId(value, label) {
  const candidate = typeof value === "string" ? value.trim() : "";
  if (!candidate)
    throw new Error(`project relation ${label} must be a non-empty string`);
  if (!COMPLETE_STABLE_PROJECT_ID_RE2.test(candidate)) {
    const detail = FILES_PROJECT_REFERENCE_RE.test(candidate) ? `; '${candidate}' is a Files prj_ project reference, not a Projects identity` : "";
    throw new Error(`project relation ${label} must be a complete stable Projects identity of the form` + ` ${COMPLETE_STABLE_PROJECT_ID_PATTERN} (got '${candidate}')${detail}`);
  }
  assertCompleteStableProjectId(candidate);
  return candidate;
}
function normalizeProjectRelationKind(value, label = "relation") {
  if (typeof value !== "string" || !PROJECT_RELATIONS.includes(value)) {
    throw new Error(`project relation ${label} must be one of ${PROJECT_RELATIONS.join(", ")} (got '${String(value)}')`);
  }
  return value;
}
function projectRelationIsAcyclicKind(relation) {
  return PROJECT_RELATION_ACYCLIC_KINDS.includes(relation);
}
function assertProjectRelationNotSelf(fromProjectId, toProjectId) {
  if (fromProjectId === toProjectId) {
    throw new Error(`project relation refuses a self-link: from_project_id and to_project_id are both '${fromProjectId}'`);
  }
}
function assertProjectRelationEndpointActive(workspace, label, projectId) {
  if (!workspace) {
    throw new Error(`project relation ${label} '${projectId}' does not resolve in this tenant: no Projects identity with that id exists here`);
  }
  if (workspace.status !== "active") {
    throw new Error(`project relation ${label} '${projectId}' is ${workspace.status}: both endpoints of a relation must be active`);
  }
  return workspace;
}
function rowToProjectRelation(row) {
  return {
    relation_id: row.relation_id,
    version: Number(row.version),
    from_project_id: row.from_project_id,
    to_project_id: row.to_project_id,
    relation: normalizeProjectRelationKind(row.relation),
    superseded_by: row.superseded_by === null ? null : Number(row.superseded_by),
    superseded_at: row.superseded_at,
    created_at: row.created_at
  };
}
function projectRelationViews(relations, selfProjectId, counterparts = new Map) {
  assertCompleteStableProjectId(selfProjectId);
  const views = relations.map((relation) => {
    const outbound = relation.from_project_id === selfProjectId;
    const counterpartId = outbound ? relation.to_project_id : relation.from_project_id;
    const counterpart = counterparts.get(counterpartId);
    return {
      relation_id: relation.relation_id,
      version: relation.version,
      relation: relation.relation,
      direction: outbound ? "outbound" : "inbound",
      self_project_id: selfProjectId,
      counterpart_project_id: counterpartId,
      counterpart_slug: counterpart?.slug ?? null,
      counterpart_name: counterpart?.name ?? null,
      counterpart_status: counterpart?.status ?? null,
      created_at: relation.created_at
    };
  });
  return views.sort((a, b) => projectRelationViewKey(a).localeCompare(projectRelationViewKey(b)));
}
function projectRelationViewKey(view) {
  return canonicalJson({
    direction: view.direction,
    counterpart_project_id: view.counterpart_project_id,
    relation: view.relation,
    relation_id: view.relation_id,
    version: view.version
  });
}
function projectRelationsDigest(views) {
  const ordered = [...views].sort((a, b) => projectRelationViewKey(a).localeCompare(projectRelationViewKey(b)));
  return sha256(canonicalJson(ordered.map((view) => ({
    relation_id: view.relation_id,
    version: view.version,
    relation: view.relation,
    direction: view.direction,
    self_project_id: view.self_project_id,
    counterpart_project_id: view.counterpart_project_id,
    created_at: view.created_at
  }))));
}
function projectRelationSnapshot(project, relations) {
  return {
    project,
    relations,
    collection_digest: projectRelationsDigest(relations)
  };
}
function assertProjectRelationAcyclic(existing, candidate) {
  if (!projectRelationIsAcyclicKind(candidate.relation))
    return;
  const adjacency = new Map;
  for (const edge of existing) {
    if (!projectRelationIsAcyclicKind(edge.relation))
      continue;
    const next = adjacency.get(edge.from_project_id);
    if (next)
      next.push(edge.to_project_id);
    else
      adjacency.set(edge.from_project_id, [edge.to_project_id]);
  }
  const path = findProjectRelationPath(adjacency, candidate.to_project_id, candidate.from_project_id);
  if (path) {
    throw new Error(`project relation refuses a ${candidate.relation} cycle in the hierarchy:` + ` ${[candidate.from_project_id, ...path].join(" -> ")} closes back on '${candidate.from_project_id}'`);
  }
}
function findProjectRelationPath(adjacency, start, target) {
  if (start === target)
    return [start];
  const visited = new Set([start]);
  const queue = [{ node: start, path: [start] }];
  while (queue.length > 0) {
    const current = queue.shift();
    for (const next of adjacency.get(current.node) ?? []) {
      if (next === target)
        return [...current.path, next];
      if (visited.has(next))
        continue;
      visited.add(next);
      queue.push({ node: next, path: [...current.path, next] });
    }
  }
  return null;
}

// src/lib/env.ts
var alias = (...keys) => {
  for (const key of keys) {
    const value = process.env[key];
    if (value)
      return value;
  }
  return;
};
var env = {
  json: () => alias("HASNA_PROJECTS_JSON", "PROJECTS_JSON"),
  reportsToken: () => alias("HASNA_PROJECTS_REPORTS_TOKEN", "PROJECTS_REPORTS_TOKEN"),
  conversationsBin: () => alias("HASNA_PROJECTS_CONVERSATIONS_BIN", "PROJECTS_CONVERSATIONS_BIN"),
  agentModel: () => alias("HASNA_PROJECTS_AGENT_MODEL", "PROJECTS_AGENT_MODEL"),
  agentContextLimit: () => alias("HASNA_PROJECTS_AGENT_CONTEXT_LIMIT", "PROJECTS_AGENT_CONTEXT_LIMIT"),
  openrouterApiKey: () => alias("HASNA_PROJECTS_OPENROUTER_API_KEY", "OPENROUTER_API_KEY", "PROJECTS_OPENROUTER_API_KEY"),
  openrouterSecretKey: () => alias("HASNA_PROJECTS_OPENROUTER_SECRET_KEY", "PROJECTS_OPENROUTER_SECRET_KEY"),
  useSecrets: () => alias("HASNA_PROJECTS_USE_SECRETS", "PROJECTS_USE_SECRETS"),
  modelPricingJson: () => alias("HASNA_PROJECTS_MODEL_PRICING_JSON", "PROJECTS_MODEL_PRICING_JSON")
};

// src/lib/project-channel-guard.ts
var PROJECT_CHANNEL_INTEGRATION_KEY = "conversations_channel";
function normalizeProjectChannelName(value) {
  return value.trim().toLowerCase().replace(/[\s_]+/g, "-").replace(/[^a-z0-9.-]/g, "").replace(/-{2,}/g, "-").replace(/^[-.]+|[-.]+$/g, "");
}
var CONVERSATIONS_CLI_TIMEOUT_MS = 15000;
function conversationsCliRunner(binary) {
  const executable = binary?.trim() || env.conversationsBin()?.trim() || "conversations";
  return (args) => {
    try {
      const result = Bun.spawnSync({
        cmd: [executable, ...args],
        stdout: "pipe",
        stderr: "pipe",
        stdin: "ignore",
        timeout: CONVERSATIONS_CLI_TIMEOUT_MS
      });
      return {
        ok: result.exitCode === 0,
        stdout: Buffer.from(result.stdout).toString("utf-8"),
        stderr: Buffer.from(result.stderr).toString("utf-8")
      };
    } catch (err) {
      return { ok: false, stdout: "", stderr: err instanceof Error ? err.message : String(err) };
    }
  };
}
function conversationsChannelListResult(result) {
  if (!result.ok) {
    return { ok: false, detail: result.stderr.trim() || result.stdout.trim() || "conversations channel list failed" };
  }
  let rows;
  try {
    rows = JSON.parse(result.stdout);
  } catch {
    return { ok: false, detail: "could not parse conversations channel list JSON output" };
  }
  if (!Array.isArray(rows)) {
    return { ok: false, detail: "conversations channel list JSON output was not an array" };
  }
  const names = rows.map((row) => row && typeof row === "object" && typeof row.name === "string" ? row.name : "").filter((name) => name.length > 0);
  return { ok: true, names };
}
function conversationsChannelExistence(names, channel) {
  const target = normalizeProjectChannelName(channel);
  const exists = names.some((name) => normalizeProjectChannelName(name) === target);
  return exists ? { verdict: "exists" } : { verdict: "missing" };
}
var channelNameListCache = new Map;
function conversationsCliChannelProbe(binary) {
  const executable = binary?.trim() || env.conversationsBin()?.trim() || "conversations";
  return (channel) => {
    if (!channelNameListCache.has(executable)) {
      channelNameListCache.set(executable, conversationsChannelListResult(conversationsCliRunner(executable)(["channel", "list", "-j"])));
    }
    const cached = channelNameListCache.get(executable);
    if (!cached.ok)
      return { verdict: "unknown", detail: cached.detail };
    return conversationsChannelExistence(cached.names, channel);
  };
}
function shouldProbeConversationsChannel(envValue = process.env) {
  const flag = (envValue["HASNA_PROJECTS_CHANNEL_VERIFY"] ?? envValue["PROJECTS_CHANNEL_VERIFY"])?.trim().toLowerCase();
  if (flag) {
    if (["1", "true", "on", "yes"].includes(flag))
      return true;
    if (["0", "false", "off", "no"].includes(flag))
      return false;
  }
  if (envValue["NODE_ENV"] === "test")
    return false;
  return true;
}
function projectChannelWriteProbe(envValue = process.env) {
  return shouldProbeConversationsChannel(envValue) ? conversationsCliChannelProbe() : undefined;
}
function changedProjectChannel(next, previous) {
  const normalized = (value) => {
    const trimmed = value?.trim();
    return trimmed ? normalizeProjectChannelName(trimmed) : null;
  };
  const nextChannel = normalized(next?.[PROJECT_CHANNEL_INTEGRATION_KEY]);
  const previousChannel = normalized(previous?.[PROJECT_CHANNEL_INTEGRATION_KEY]);
  if (!nextChannel || nextChannel === previousChannel)
    return null;
  return nextChannel;
}
function assertProjectChannelWritable(channel, options = {}) {
  const target = channel?.trim();
  if (!target)
    return;
  const probe = options.probe;
  if (!probe)
    return;
  const result = probe(target);
  if (result.verdict !== "missing")
    return;
  throw new Error(`Refusing to pin integrations.${PROJECT_CHANNEL_INTEGRATION_KEY} "${target}": the conversations app has no channel with that name, ` + `so a project-channel post would fail closed (HTTP 400 "Channel \\"${target}\\" does not exist, so this message was not sent.") ` + `or land in an agent DM of the same name instead of in a channel. ` + `Create the channel first (conversations channel create ${target}) or point the project at a channel that exists ` + `(conversations channel list -j). Set HASNA_PROJECTS_CHANNEL_VERIFY=0 to skip this check.`);
}
function assertProjectChannelIntegrationWritable(next, previous, options = {}) {
  const channel = changedProjectChannel(next, previous);
  if (!channel)
    return;
  const probe = options.probe ?? projectChannelWriteProbe(options.env);
  assertProjectChannelWritable(channel, { probe });
}

// src/lib/project-registration.ts
import { join as join3, resolve as resolve3 } from "path";

// src/lib/project-store-paths.ts
import { existsSync } from "fs";
import { homedir } from "os";
import { join, resolve } from "path";
import { homedir as pathsResolverHomedir } from "os";
import { join as pathsResolverJoin } from "path";
var PATHS_RESOLVER_KIND_ENV = {
  config: "HASNA_CONFIG_HOME",
  data: "HASNA_DATA_HOME",
  state: "HASNA_STATE_HOME",
  cache: "HASNA_CACHE_HOME"
};
var PATHS_RESOLVER_APP_SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
function pathsResolverAssertApp(app) {
  if (typeof app !== "string" || app.length === 0) {
    throw new TypeError("paths: app must be a non-empty string");
  }
  if (!PATHS_RESOLVER_APP_SLUG_RE.test(app)) {
    throw new TypeError(`paths: invalid app slug "${app}" \u2014 expected lowercase kebab-case ([a-z0-9]+(-[a-z0-9]+)*)`);
  }
}
function pathsResolverAssertKind(kind) {
  if (!Object.keys(PATHS_RESOLVER_KIND_ENV).includes(kind)) {
    throw new TypeError(`paths: invalid path kind "${kind}" \u2014 expected one of ${Object.keys(PATHS_RESOLVER_KIND_ENV).join(", ")}`);
  }
}
function pathsResolverBaseDir(kind, options) {
  pathsResolverAssertKind(kind);
  const env2 = options.env ?? process.env;
  const override = env2[PATHS_RESOLVER_KIND_ENV[kind]];
  if (typeof override === "string" && override.length > 0)
    return override;
  const home = options.home ?? pathsResolverHomedir();
  const platform = options.platform ?? process.platform;
  if (platform === "darwin") {
    switch (kind) {
      case "config":
      case "data":
        return pathsResolverJoin(home, "Library", "Application Support", "Hasna");
      case "cache":
        return pathsResolverJoin(home, "Library", "Caches", "Hasna");
      case "state":
        return pathsResolverJoin(home, "Library", "Logs", "Hasna");
    }
  }
  switch (kind) {
    case "config":
      return pathsResolverJoin(home, ".config", "hasna");
    case "data":
      return pathsResolverJoin(home, ".local", "share", "hasna");
    case "state":
      return pathsResolverJoin(home, ".local", "state", "hasna");
    case "cache":
      return pathsResolverJoin(home, ".cache", "hasna");
  }
}
function pathsResolverResolve(kind, options) {
  pathsResolverAssertApp(options.app);
  const appSegment = options.internal === true ? pathsResolverJoin("internal", options.app) : options.app;
  return pathsResolverJoin(pathsResolverBaseDir(kind, options), appSegment);
}
function dataDir(options) {
  return pathsResolverResolve("data", options);
}
var PROJECTS_HOME_ENV = "HASNA_PROJECTS_HOME";
var PROJECT_WORKSPACE_ID_PATTERN = /^wks_[A-Za-z0-9_-]{1,80}$/;
function assertProjectWorkspaceId(workspaceId) {
  if (!PROJECT_WORKSPACE_ID_PATTERN.test(workspaceId)) {
    throw new Error(`Invalid workspace id for project store path: ${workspaceId}`);
  }
  return workspaceId;
}
function effectiveHome() {
  return process.env["HOME"] || process.env["USERPROFILE"] || homedir();
}
function legacyHomeDir() {
  return resolve(join(effectiveHome(), ".hasna", "projects"));
}
function resolverHome() {
  return dataDir({ app: "projects", home: process.env["HOME"] || process.env["USERPROFILE"] || undefined });
}
function adoptResolverHome(resolved, env2 = process.env) {
  const dataOverride = env2.HASNA_DATA_HOME;
  if (typeof dataOverride === "string" && dataOverride.trim().length > 0)
    return true;
  return existsSync(join(resolved, "projects.db"));
}
function getProjectsHome() {
  const configured = process.env[PROJECTS_HOME_ENV]?.trim();
  if (configured)
    return resolve(configured);
  const resolved = resolverHome();
  return adoptResolverHome(resolved) ? resolve(resolved) : legacyHomeDir();
}
function projectWorkspaceStorePath(workspaceId) {
  return resolve(join(getProjectsHome(), "workspaces", assertProjectWorkspaceId(workspaceId)));
}

// src/lib/project-management.ts
var FINANCE_PROJECT_METADATA_SCHEMA = "hasna.projects.finance_project_metadata.v1";
var FINANCE_PROJECT_METADATA_FIELDS = [
  "business_area",
  "jurisdiction",
  "legal_entities",
  "fiscal_cycle",
  "data_classification",
  "retention_policy",
  "ledger_authority",
  "evidence_store",
  "approver",
  "external_recipient_policy"
];
var FINANCE_FISCAL_CYCLES = ["monthly", "quarterly", "annual", "event-driven"];
var FINANCE_DATA_CLASSIFICATIONS = ["public", "internal", "confidential", "restricted"];
var FINANCE_JURISDICTION_PATTERN = /^[A-Z0-9][A-Z0-9._:-]{1,63}$/;
var FINANCE_METADATA_TEXT_MAX_LENGTH = 512;
var FINANCE_LEGAL_ENTITY_MAX_LENGTH = 256;
var FINANCE_LEGAL_ENTITY_MAX_ITEMS = 100;
var FINANCE_PROJECT_METADATA_CONTEXT_MAX_BYTES = 4 * 1024;
function metadataHasOwn(metadata, key) {
  return Object.prototype.hasOwnProperty.call(metadata, key);
}
function normalizedLowerToken(value) {
  if (typeof value !== "string")
    return null;
  const normalized = value.trim().toLowerCase().replace(/[_\s]+/g, "-");
  return normalized || null;
}
function hasFinanceProjectMetadataIntent(metadata) {
  return normalizedLowerToken(metadata["business_area"]) === "finance";
}
function requiredFinanceMetadataString(metadata, field) {
  const value = metadata[field];
  if (typeof value !== "string" || !value.trim()) {
    throw new Error(`Finance project metadata ${field} must be a non-empty string`);
  }
  const normalized = value.trim();
  if (normalized.length > FINANCE_METADATA_TEXT_MAX_LENGTH) {
    throw new Error(`Finance project metadata ${field} must be at most ${FINANCE_METADATA_TEXT_MAX_LENGTH} characters`);
  }
  return normalized;
}
function normalizeFinanceLegalEntities(value) {
  if (!Array.isArray(value) || value.length === 0) {
    throw new Error("Finance project metadata legal_entities must be a non-empty array of strings");
  }
  if (value.length > FINANCE_LEGAL_ENTITY_MAX_ITEMS) {
    throw new Error(`Finance project metadata legal_entities must contain at most ${FINANCE_LEGAL_ENTITY_MAX_ITEMS} items`);
  }
  const entities = [];
  const seen = new Set;
  for (const item of value) {
    if (typeof item !== "string" || !item.trim()) {
      throw new Error("Finance project metadata legal_entities must be a non-empty array of strings");
    }
    const entity = item.trim();
    if (entity.length > FINANCE_LEGAL_ENTITY_MAX_LENGTH) {
      throw new Error(`Finance project metadata legal_entities entries must be at most ${FINANCE_LEGAL_ENTITY_MAX_LENGTH} characters`);
    }
    if (seen.has(entity))
      continue;
    seen.add(entity);
    entities.push(entity);
  }
  if (entities.length === 0) {
    throw new Error("Finance project metadata legal_entities must be a non-empty array of strings");
  }
  return entities;
}
function normalizeProjectMetadata(metadata, existingMetadata) {
  const next = { ...metadata ?? {} };
  const explicitlyClearsFinance = metadataHasOwn(next, "business_area") && next["business_area"] === null;
  const isFinance = hasFinanceProjectMetadataIntent(next) || (!explicitlyClearsFinance && existingMetadata ? hasFinanceProjectMetadataIntent(existingMetadata) : false);
  if (!isFinance) {
    if (explicitlyClearsFinance)
      delete next["business_area"];
    return next;
  }
  const missing = FINANCE_PROJECT_METADATA_FIELDS.filter((field) => !metadataHasOwn(next, field));
  if (missing.length > 0) {
    throw new Error(`Finance project metadata is missing required fields: ${missing.join(", ")}`);
  }
  const businessArea = normalizedLowerToken(next["business_area"]);
  if (businessArea !== "finance") {
    throw new Error('Finance project metadata business_area must be "finance"');
  }
  const jurisdiction = requiredFinanceMetadataString(next, "jurisdiction").toUpperCase();
  if (!FINANCE_JURISDICTION_PATTERN.test(jurisdiction)) {
    throw new Error("Finance project metadata jurisdiction must be a stable 2-64 character identifier");
  }
  const fiscalCycle = normalizedLowerToken(next["fiscal_cycle"]);
  if (!fiscalCycle || !FINANCE_FISCAL_CYCLES.includes(fiscalCycle)) {
    throw new Error(`Finance project metadata fiscal_cycle must be one of: ${FINANCE_FISCAL_CYCLES.join(", ")}`);
  }
  const classification = normalizedLowerToken(next["data_classification"]);
  if (!classification || !FINANCE_DATA_CLASSIFICATIONS.includes(classification)) {
    throw new Error(`Finance project metadata data_classification must be one of: ${FINANCE_DATA_CLASSIFICATIONS.join(", ")}`);
  }
  const profile = {
    schema: FINANCE_PROJECT_METADATA_SCHEMA,
    business_area: "finance",
    jurisdiction,
    legal_entities: normalizeFinanceLegalEntities(next["legal_entities"]),
    fiscal_cycle: fiscalCycle,
    data_classification: classification,
    retention_policy: requiredFinanceMetadataString(next, "retention_policy"),
    ledger_authority: requiredFinanceMetadataString(next, "ledger_authority"),
    evidence_store: requiredFinanceMetadataString(next, "evidence_store"),
    approver: requiredFinanceMetadataString(next, "approver"),
    external_recipient_policy: requiredFinanceMetadataString(next, "external_recipient_policy")
  };
  const profileBytes = Buffer.byteLength(JSON.stringify(profile), "utf8");
  if (profileBytes > FINANCE_PROJECT_METADATA_CONTEXT_MAX_BYTES) {
    throw new Error(`Finance project metadata exceeds ${FINANCE_PROJECT_METADATA_CONTEXT_MAX_BYTES}-byte context budget`);
  }
  const { schema: _schema, ...storedProfile } = profile;
  return {
    ...next,
    ...storedProfile
  };
}

// src/lib/project-resource-links.ts
import {
  ProjectResourceLinkCollectionV1Schema,
  ProjectResourceLinkInputSchema,
  ProjectResourceLinkSchema
} from "@hasna/contracts/schemas";
var SOURCE_PACKAGE_BY_AUTHORITY = {
  todos: "@hasna/todos",
  conversations: "@hasna/conversations",
  knowledge: "@hasna/knowledge",
  mementos: "@hasna/mementos",
  orgs: "@hasna/orgs",
  contacts: "@hasna/contacts",
  files: "@hasna/files"
};
var TARGET_KINDS_BY_AUTHORITY = {
  todos: ["project", "task", "task_list", "plan"],
  conversations: ["project", "channel"],
  knowledge: ["collection", "item"],
  mementos: ["project", "item"],
  orgs: ["org", "project"],
  contacts: ["contact"],
  files: ["project"]
};
var LINK_FIELDS = new Set([
  "authority",
  "service_instance",
  "source_package",
  "target_kind",
  "locator",
  "scope",
  "labels"
]);
var LOCATOR_FIELDS = new Set(["kind", "value"]);
var LABEL_FIELDS = new Set(["name", "channel_name", "path", "tags"]);
var COMPLETE_EXTERNAL_UUID_PATTERN = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$";
var UUID_RE = new RegExp(COMPLETE_EXTERNAL_UUID_PATTERN);
var CONVERSATIONS_CHANNEL_ID_RE = /^chn_[0-9a-f]{32}$/;
var URN_RE = /^urn:[a-z0-9][a-z0-9-]{0,31}:[A-Za-z0-9._~:/?#\[\]@!$&'()*+,;=%-]+$/;
var PROJECT_RESOURCE_SERVICE_INSTANCE_URN_FORM = "urn:hasna:<authority>:service:<authority_id>:tenant:<tenant_id>:corpus:<corpus_id>";
var URN_SERVICE_INSTANCE_AUTHORITIES = [
  "todos",
  "conversations",
  "knowledge",
  "mementos",
  "orgs",
  "files"
];
var PROJECT_RESOURCE_FILES_PROJECT_URN_PREFIX = "urn:hasna:files:project:";
var FILES_PROJECT_LOCATOR_RE = /^urn:hasna:files:project:prj_[A-Za-z0-9_-]+$/;
function projectResourceLinkConversationsChannelLocatorKind(value) {
  if (UUID_RE.test(value))
    return "external_uuid";
  if (CONVERSATIONS_CHANNEL_ID_RE.test(value))
    return "conversations_channel_id";
  return null;
}
function assertClosedObject(value, allowed, label) {
  for (const key of Object.keys(value)) {
    if (!allowed.has(key))
      throw new Error(`${label} contains unknown field '${key}'`);
  }
}
function requiredString(value, label) {
  if (typeof value !== "string" || !value.trim())
    throw new Error(`${label} must be a non-empty string`);
  return value.trim();
}
function canonicalProjectResourceLinkUri(value, label) {
  if (URN_RE.test(value))
    return value;
  let url;
  try {
    url = new URL(value);
  } catch {
    throw new Error(`${label} must be a canonical https URI or URN`);
  }
  if (url.protocol !== "https:" || url.username || url.password) {
    throw new Error(`${label} must be a non-secret canonical https URI or URN`);
  }
  if (url.search || url.hash)
    throw new Error(`${label} must not contain query or fragment components`);
  return url.toString();
}
function assertProjectResourceLinkServiceInstanceWritable(authority, serviceInstance) {
  const canonical = canonicalProjectResourceLinkUri(serviceInstance, "resource link service_instance");
  if (!URN_SERVICE_INSTANCE_AUTHORITIES.includes(authority))
    return canonical;
  const segments = canonical.split(":");
  if (segments[0] === "urn") {
    if (segments[1] === "hasna" && segments[2] === authority && segments[3] === "service" && segments[4]) {
      return canonical;
    }
    throw new Error(`resource link service_instance urn must be authority-qualified as urn:hasna:${authority}:service:...; got '${canonical}'`);
  }
  throw new Error(`resource link service_instance must be the authority-qualified urn form ${PROJECT_RESOURCE_SERVICE_INSTANCE_URN_FORM}, not a bare service URL; got '${canonical}'`);
}
function assertProjectResourceLinksWritable(links) {
  for (const link of links) {
    assertProjectResourceLinkServiceInstanceWritable(link.authority, link.service_instance);
  }
}
function normalizeLabels(value) {
  if (value === undefined)
    return {};
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    throw new Error("resource link labels must be an object");
  }
  assertClosedObject(value, LABEL_FIELDS, "resource link labels");
  const raw = value;
  const labels = {};
  if (raw["name"] !== undefined)
    labels.name = requiredString(raw["name"], "resource link labels.name");
  if (raw["channel_name"] !== undefined)
    labels.channel_name = requiredString(raw["channel_name"], "resource link labels.channel_name");
  if (raw["path"] !== undefined)
    labels.path = requiredString(raw["path"], "resource link labels.path");
  if (raw["tags"] !== undefined) {
    if (!Array.isArray(raw["tags"]) || raw["tags"].some((tag) => typeof tag !== "string")) {
      throw new Error("resource link labels.tags must be an array of strings");
    }
    labels.tags = [...new Set(raw["tags"].map((tag) => tag.trim()).filter(Boolean))].sort();
  }
  return labels;
}
function normalizeProjectResourceLink(input) {
  if (!input || typeof input !== "object" || Array.isArray(input))
    throw new Error("resource link must be an object");
  assertClosedObject(input, LINK_FIELDS, "resource link");
  if (!PROJECT_RESOURCE_AUTHORITIES.includes(input.authority)) {
    throw new Error("resource link authority is unsupported");
  }
  const authority = input.authority;
  const serviceInstance = canonicalProjectResourceLinkUri(requiredString(input.service_instance, "resource link service_instance"), "resource link service_instance");
  const expectedPackage = SOURCE_PACKAGE_BY_AUTHORITY[authority];
  if (input.source_package !== expectedPackage) {
    throw new Error(`resource link source_package for ${authority} must be ${expectedPackage}`);
  }
  if (!TARGET_KINDS_BY_AUTHORITY[authority].includes(input.target_kind)) {
    throw new Error(`resource link target_kind '${input.target_kind}' is not valid for ${authority}`);
  }
  if (!input.locator || typeof input.locator !== "object" || Array.isArray(input.locator)) {
    throw new Error("resource link locator must be an object");
  }
  assertClosedObject(input.locator, LOCATOR_FIELDS, "resource link locator");
  const locatorValue = requiredString(input.locator.value, "resource link locator.value");
  let normalizedLocatorValue;
  if (input.locator.kind === "external_uuid") {
    if (projectResourceLinkConversationsChannelLocatorKind(locatorValue) !== "external_uuid") {
      throw new Error("resource link external_uuid must be a complete UUID");
    }
    normalizedLocatorValue = locatorValue.toLowerCase();
  } else if (input.locator.kind === "canonical_uri") {
    normalizedLocatorValue = canonicalProjectResourceLinkUri(locatorValue, "resource link canonical_uri");
  } else if (input.locator.kind === "conversations_channel_id") {
    if (projectResourceLinkConversationsChannelLocatorKind(locatorValue) !== "conversations_channel_id") {
      throw new Error("resource link conversations channel ID must match chn_<32hex>");
    }
    normalizedLocatorValue = locatorValue.toLowerCase();
  } else {
    throw new Error("resource link locator.kind must be external_uuid, canonical_uri, or conversations_channel_id");
  }
  const locator = {
    kind: input.locator.kind,
    value: normalizedLocatorValue
  };
  if (input.scope !== "resource" && input.scope !== "collection") {
    throw new Error("resource link scope must be resource or collection");
  }
  const labels = normalizeLabels(input.labels);
  if (locator.kind === "conversations_channel_id" && !(authority === "conversations" && input.target_kind === "channel")) {
    throw new Error("resource link conversations_channel_id is only valid for Conversations channel links");
  }
  if (input.authority === "todos" && input.target_kind === "task") {
    if (locator.kind !== "external_uuid") {
      throw new Error("Todos task links require a complete external_uuid task ID");
    }
    const taskLocator = { kind: "external_uuid", value: locator.value };
    return ProjectResourceLinkInputSchema.parse({
      ...input,
      service_instance: serviceInstance,
      locator: taskLocator,
      labels
    });
  }
  if (authority === "conversations" && input.target_kind === "channel") {
    if (locator.kind !== "external_uuid" && locator.kind !== "conversations_channel_id") {
      throw new Error("conversations channel links require an immutable external_uuid or conversations_channel_id");
    }
    if (!labels.channel_name) {
      throw new Error("conversations channel links require labels.channel_name as mutable compatibility data");
    }
  }
  if (authority === "contacts" && input.target_kind === "contact") {
    if (locator.kind !== "external_uuid") {
      throw new Error("contacts contact links require an immutable external_uuid");
    }
    const contactLocator = { kind: "external_uuid", value: locator.value };
    return ProjectResourceLinkInputSchema.parse({
      ...input,
      service_instance: serviceInstance,
      locator: contactLocator,
      labels
    });
  }
  if (authority === "files" && input.target_kind === "project") {
    if (input.scope !== "collection") {
      throw new Error("files project links require scope collection");
    }
    if (locator.kind !== "canonical_uri") {
      throw new Error(`files project links require a canonical_uri locator of the form ${PROJECT_RESOURCE_FILES_PROJECT_URN_PREFIX}<prj_id>`);
    }
    if (!FILES_PROJECT_LOCATOR_RE.test(locator.value)) {
      throw new Error(`files project links require a locator value of the form ${PROJECT_RESOURCE_FILES_PROJECT_URN_PREFIX}<prj_id>`);
    }
  }
  return ProjectResourceLinkInputSchema.parse({
    ...input,
    service_instance: serviceInstance,
    locator,
    labels
  });
}
function projectResourceLinkIdentity(input) {
  const link = normalizeProjectResourceLink({
    authority: input.authority,
    service_instance: input.service_instance,
    source_package: input.source_package,
    target_kind: input.target_kind,
    locator: input.locator,
    scope: input.scope,
    labels: input.labels
  });
  return {
    authority: link.authority,
    service_instance: link.service_instance,
    source_package: link.source_package,
    target_kind: link.target_kind,
    locator_kind: link.locator.kind,
    locator_value: link.locator.value
  };
}
function projectResourceLinkId(projectId, input) {
  return `prl_${sha256(canonicalJson({ project_id: projectId, ...projectResourceLinkIdentity(input) })).slice(0, 36)}`;
}
function normalizeProjectResourceLinks(inputs) {
  if (!Array.isArray(inputs))
    throw new Error("resource links must be an array");
  const normalized = inputs.map(normalizeProjectResourceLink);
  const seen = new Set;
  for (const link of normalized) {
    const key = canonicalJson(projectResourceLinkIdentity(link));
    if (seen.has(key))
      throw new Error(`duplicate resource link identity in request: ${key}`);
    seen.add(key);
  }
  return normalized.sort((a, b) => canonicalJson(projectResourceLinkIdentity(a)).localeCompare(canonicalJson(projectResourceLinkIdentity(b))));
}
function rowToProjectResourceLink(row) {
  const input = normalizeProjectResourceLink({
    authority: row.authority,
    service_instance: row.service_instance,
    source_package: row.source_package,
    target_kind: row.target_kind,
    locator: {
      kind: row.locator_kind,
      value: row.locator_value
    },
    scope: row.scope,
    labels: JSON.parse(row.labels_json)
  });
  const timestamp = (value) => {
    if (value.includes("T"))
      return new Date(value).toISOString();
    return new Date(`${value.replace(" ", "T")}Z`).toISOString();
  };
  return ProjectResourceLinkSchema.parse({
    ...input,
    id: row.id,
    project_id: row.project_id,
    labels: input.labels ?? {},
    created_at: timestamp(row.created_at),
    updated_at: timestamp(row.updated_at)
  });
}
function projectResourceLinksDigest(links) {
  const ordered = [...links].sort((a, b) => canonicalJson(projectResourceLinkIdentity(a)).localeCompare(canonicalJson(projectResourceLinkIdentity(b))));
  return sha256(canonicalJson(ordered.map((link) => ({
    id: link.id,
    project_id: link.project_id,
    ...projectResourceLinkIdentity(link),
    scope: link.scope,
    labels: link.labels
  }))));
}
function projectionValue(link) {
  if (link.authority === "conversations" && link.target_kind === "channel") {
    return link.labels.channel_name ?? null;
  }
  return link.locator.value;
}
var PROJECTIONS = [
  { key: "todos_project_id", match: (link) => link.authority === "todos" && link.target_kind === "project" },
  { key: "todos_task_list_id", match: (link) => link.authority === "todos" && link.target_kind === "task_list" },
  { key: "mementos_project_id", match: (link) => link.authority === "mementos" && link.target_kind === "project" },
  { key: "orgs_org_id", match: (link) => link.authority === "orgs" && link.target_kind === "org" },
  { key: "orgs_project_id", match: (link) => link.authority === "orgs" && link.target_kind === "project" },
  { key: "conversations_channel", match: (link) => link.authority === "conversations" && link.target_kind === "channel" }
];
function projectResourceLinkIntegrationProjection(integrations, beforeLinks, afterLinks) {
  const projected = { ...integrations };
  for (const projection of PROJECTIONS) {
    const before = beforeLinks.filter(projection.match);
    const after = afterLinks.filter(projection.match);
    if (after.length === 1) {
      const value = projectionValue(after[0]);
      if (value)
        projected[projection.key] = value;
      else
        delete projected[projection.key];
    } else if (after.length > 1) {
      const existingValue = projected[projection.key];
      const matches = typeof existingValue === "string" ? after.filter((link) => projectionValue(link) === existingValue) : [];
      if (matches.length !== 1)
        delete projected[projection.key];
    } else if (before.length > 0) {
      delete projected[projection.key];
    }
  }
  return projected;
}
function normalizeProjectResourceLinkIntegrations(value) {
  if (value === undefined)
    return;
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    throw new Error("resource link integrations must be an object");
  }
  const integrations = {};
  for (const [key, item] of Object.entries(value)) {
    if (!key.trim() || typeof item !== "string" || !item.trim()) {
      throw new Error("resource link integration keys and values must be non-empty strings");
    }
    integrations[key] = item;
  }
  return integrations;
}
var PROJECT_RESOURCE_LINK_INTEGRATION_KEYS = PROJECTIONS.map((projection) => projection.key);
function assertProjectResourceLinkIntegrationMutation(beforeIntegrations, proposedIntegrations, links) {
  const canonical = projectResourceLinkIntegrationProjection({}, [], links);
  for (const key of PROJECT_RESOURCE_LINK_INTEGRATION_KEYS) {
    if (beforeIntegrations[key] === proposedIntegrations[key])
      continue;
    const authoritative = canonical[key];
    if (authoritative !== undefined && authoritative !== proposedIntegrations[key]) {
      throw new Error(`integration '${key}' is a typed resource-link compatibility projection and conflicts with the existing resource link ('${authoritative}'); change it through resource-links`);
    }
  }
}
function projectResourceLinkSnapshot(project, links) {
  return {
    project,
    links,
    collection_digest: projectResourceLinksDigest(links)
  };
}
function projectResourceLinkCollection(projectId, currentRevision, links, maxItems) {
  return ProjectResourceLinkCollectionV1Schema.parse({
    schema: "hasna.project_resource_link_collection.v1",
    project_id: projectId,
    current_revision: currentRevision,
    links,
    link_count: links.length,
    max_items: maxItems,
    collection_digest: projectResourceLinksDigest(links),
    complete: true,
    truncated: false
  });
}
function assertProjectResourceLinkReadContractEquality(read) {
  const flat = {
    project_id: read.project_id,
    current_revision: read.current_revision,
    links: read.links,
    link_count: read.link_count,
    max_items: read.max_items,
    collection_digest: read.collection_digest,
    complete: read.complete,
    truncated: read.truncated
  };
  const { schema: _schema, ...contract } = ProjectResourceLinkCollectionV1Schema.parse(read.contract);
  if (canonicalJson(flat) !== canonicalJson(contract)) {
    throw new Error("project resource link contract and compatibility fields are not byte-equivalent");
  }
}

// src/lib/project-channel.ts
var PROJECT_CHANNEL_CLASSES = ["package", "product", "work-project", "initiative", "loop-lane"];
var PROJECT_CHANNEL_CLASS_INTEGRATION_KEY = "conversations_channel_class";
var WORKSPACE_KIND_CHANNEL_CLASSES = {
  "open-source": "package",
  "internal-app": "product",
  platform: "product",
  "company-website": "product",
  community: "product",
  project: "work-project",
  experiment: null,
  scaffold: null,
  docs: null,
  "remote-only": null,
  generic: null
};
function resolveProjectChannelClass(project) {
  return resolveProjectChannelClassDetailed(project).channel_class;
}
function resolveProjectChannelClassDetailed(project) {
  const fromKind = WORKSPACE_KIND_CHANNEL_CLASSES[project.kind] ?? null;
  const explicit = project.integrations?.[PROJECT_CHANNEL_CLASS_INTEGRATION_KEY]?.trim().toLowerCase();
  if (!explicit)
    return { channel_class: fromKind };
  const known = PROJECT_CHANNEL_CLASSES.find((value) => value === explicit);
  if (known)
    return { channel_class: known };
  return {
    channel_class: fromKind,
    warning: `Ignoring unknown ${PROJECT_CHANNEL_CLASS_INTEGRATION_KEY} "${explicit}" on the project record (known: ${PROJECT_CHANNEL_CLASSES.join(", ")}); using ${fromKind ?? "no class"} from kind "${project.kind}" instead.`
  };
}
function deriveProjectChannel(project) {
  const channel_class = resolveProjectChannelClass(project);
  const linked = project.integrations?.[PROJECT_CHANNEL_INTEGRATION_KEY]?.trim();
  if (linked) {
    const channel2 = normalizeProjectChannelName(linked);
    if (!channel2)
      throw new Error(`Linked conversations channel is not a valid channel name: ${linked}`);
    return { channel: channel2, channel_class, source: "integration" };
  }
  const channel = normalizeProjectChannelName(project.slug);
  if (!channel)
    throw new Error(`Project slug does not produce a valid channel name: ${project.slug}`);
  return { channel, channel_class, source: "derived" };
}

// src/lib/project-resource-link-migrations.ts
var TRANSITIONS = {
  planned: ["producer_applied", "rollback_in_progress", "rolled_back", "failed_reconcilable"],
  producer_applied: ["projects_applied", "rollback_in_progress", "rolled_back", "retained_target", "failed_reconcilable"],
  projects_applied: ["verified", "rollback_in_progress", "failed_reconcilable"],
  verified: ["rollback_in_progress", "failed_reconcilable"],
  rollback_in_progress: ["rolled_back", "retained_target", "failed_reconcilable"],
  rolled_back: [],
  retained_target: [],
  failed_reconcilable: ["rollback_in_progress"]
};
function projectResourceLinkProducerProjectSubject(project) {
  return {
    id: project.id,
    slug: project.slug,
    name: project.name,
    kind: project.kind,
    conversations_channel: deriveProjectChannel(project).channel
  };
}
function projectResourceLinkProducerEvidenceDigest(manifest, phase, producerEvidence) {
  return sha256(canonicalJson({
    manifest_id: manifest.manifest_id,
    phase,
    producer_context: manifest.links.map((item) => ({
      link_id: item.link_id,
      producer_resource_kind: item.producer_resource_kind,
      producer_binding: item.producer_binding
    })),
    producer_evidence: producerEvidence
  }));
}
function projectResourceLinkProducerAttestationId(manifestId, phase, evidenceDigest) {
  return `prlpa_${sha256(canonicalJson({
    manifest_id: manifestId,
    phase,
    evidence_digest: evidenceDigest
  })).slice(0, 36)}`;
}
function assertProjectResourceLinkProducerAttestation(manifest, phase, producerEvidence, attestation) {
  if (!attestation) {
    throw new Error(`project resource link migration ${phase} requires trusted producer receipt/readback attestation`);
  }
  const evidenceDigest = projectResourceLinkProducerEvidenceDigest(manifest, phase, producerEvidence);
  const attestationId = projectResourceLinkProducerAttestationId(manifest.manifest_id, phase, evidenceDigest);
  if (attestation.attestation_id !== attestationId || attestation.manifest_id !== manifest.manifest_id || attestation.phase !== phase || attestation.evidence_digest !== evidenceDigest) {
    throw new Error("producer attestation does not bind the exact manifest, phase, and producer evidence");
  }
  requireNonemptyProofValue(attestation.verifier, "producer attestation verifier");
  requireNonemptyProofValue(attestation.verified_at, "producer attestation verified_at");
  if (!Number.isFinite(Date.parse(attestation.verified_at))) {
    throw new Error("producer attestation verified_at must be an ISO-8601 timestamp");
  }
  return { ...attestation };
}
function migrationEvidenceWithProducerAttestation(evidence2, attestation) {
  return {
    ...evidence2,
    producer_attestation: { ...attestation }
  };
}
function requireNonemptyProofValue(value, label) {
  if (!value?.trim())
    throw new Error(`${label} must be a nonempty producer proof value`);
  return value;
}
function assertProducerBinding(item) {
  if (item.producer_binding.authority_id !== item.link.authority) {
    throw new Error("producer binding authority_id must match the resource-link authority");
  }
  requireNonemptyProofValue(item.producer_resource_kind, "producer resource_kind");
  requireNonemptyProofValue(item.producer_binding.tenant_id, "producer binding tenant_id");
  requireNonemptyProofValue(item.producer_binding.capability_digest, "producer binding capability_digest");
}
function assertUniqueReceiptIds(receiptIds, label) {
  for (const receiptId of receiptIds)
    requireNonemptyProofValue(receiptId, label);
  if (new Set(receiptIds).size !== receiptIds.length) {
    throw new Error(`${label} must not contain duplicate producer receipts`);
  }
}
function reconcileProjectResourceLinkProducerProof(manifest, evidence2, phase, terminalOutcome) {
  if (!evidence2 || evidence2.length !== manifest.links.length) {
    const label = phase === "inverse" ? "producer inverse proof" : `producer ${phase} proof`;
    throw new Error(`${label} requires exact evidence for every manifest link`);
  }
  let retainedTargetCount = 0;
  const reconciled = evidence2.map((candidate, index) => {
    const item = manifest.links[index];
    const persisted = item.producer_evidence;
    assertProducerBinding(item);
    requireNonemptyProofValue(candidate.forward_receipt_id, "producer forward receipt");
    requireNonemptyProofValue(candidate.target_revision, "producer target revision");
    requireNonemptyProofValue(candidate.target_digest, "producer target digest");
    assertUniqueReceiptIds(candidate.child_link_receipt_ids, "producer child-link receipt");
    if (phase !== "forward") {
      if (!persisted)
        throw new Error(`producer ${phase} proof has no persisted forward proof`);
      if (candidate.created_by_operation !== persisted.created_by_operation || candidate.forward_receipt_id !== persisted.forward_receipt_id || canonicalJson(candidate.child_link_receipt_ids) !== canonicalJson(persisted.child_link_receipt_ids)) {
        throw new Error(`producer ${phase} proof does not match the persisted producer receipt identity`);
      }
    }
    if (phase === "forward" || phase === "readback") {
      if (candidate.inverse_verified !== null || candidate.inverse_outcome !== null) {
        throw new Error(`producer ${phase} proof must not claim an inverse outcome`);
      }
    } else {
      if (candidate.inverse_verified !== true) {
        throw new Error("producer inverse proof requires inverse_verified=true for every manifest link");
      }
      const inverseOutcome = requireNonemptyProofValue(candidate.inverse_outcome, "producer inverse outcome");
      if (terminalOutcome === "complete" && candidate.created_by_operation && inverseOutcome !== "complete") {
        throw new Error("producer inverse proof for a created target must record inverse_outcome=complete");
      }
      if (terminalOutcome === "retained_target" && inverseOutcome === "retained_target") {
        retainedTargetCount += 1;
      }
    }
    return { ...candidate };
  });
  if (phase === "inverse" && terminalOutcome === "retained_target" && retainedTargetCount === 0) {
    throw new Error("producer inverse proof for retained_target must record a retained_target outcome");
  }
  return reconciled;
}
function projectResourceLinkMigrationManifestId(projectId, operationId, stepId, desiredCollectionDigest) {
  return `prlm_${sha256(canonicalJson({
    project_id: projectId,
    operation_id: operationId,
    step_id: stepId,
    desired_collection_digest: desiredCollectionDigest
  })).slice(0, 36)}`;
}
function projectResourceLinkMigrationEventId(manifestId, transitionVersion, toState) {
  return `prlme_${sha256(canonicalJson({
    manifest_id: manifestId,
    transition_version: transitionVersion,
    to_state: toState
  })).slice(0, 36)}`;
}
function buildProjectResourceLinkMigrationPlan(input, createdAt) {
  const normalizedInInputOrder = input.links.map((item) => normalizeProjectResourceLinks([item.link])[0]);
  const normalized = normalizeProjectResourceLinks(normalizedInInputOrder);
  if (normalized.length !== input.links.length) {
    throw new Error("project resource link migration plan lost link cardinality");
  }
  const items = input.links.map((item, index) => {
    const link = normalizedInInputOrder[index];
    if (!link)
      throw new Error("project resource link migration plan contains an ambiguous normalized identity");
    return {
      ...item,
      link,
      link_id: projectResourceLinkId(input.project_id, link),
      producer_evidence: null
    };
  });
  for (const item of items)
    assertProducerBinding(item);
  const desiredCollectionDigest = projectResourceLinksDigest(items.map((item) => ({
    ...item.link,
    id: item.link_id,
    project_id: input.project_id,
    labels: item.link.labels ?? {},
    created_at: createdAt,
    updated_at: createdAt
  })));
  return {
    schema: "projects.project_resource_link_migration_manifest.v1",
    manifest_id: projectResourceLinkMigrationManifestId(input.project_id, input.operation_id, input.step_id, desiredCollectionDigest),
    project_id: input.project_id,
    operation_id: input.operation_id,
    step_id: input.step_id,
    state: "planned",
    expected_project_revision: input.expected_project_revision,
    desired_collection_digest: desiredCollectionDigest,
    links: items,
    projects_forward_receipt_id: null,
    projects_inverse_receipt_id: null,
    projects_reference_proof: null,
    last_verified_projects_revision: null,
    last_verified_projects_digest: null,
    transition_version: 1,
    created_at: createdAt,
    updated_at: createdAt
  };
}
function assertProjectResourceLinkMigrationTransition(from, to) {
  if (!TRANSITIONS[from].includes(to)) {
    throw new Error(`project resource link migration transition ${from} -> ${to} is not allowed`);
  }
}
function applyProjectResourceLinkMigrationTransition(manifest, toState, updatedAt, updates = {}) {
  assertProjectResourceLinkMigrationTransition(manifest.state, toState);
  if (updates.producer_evidence && updates.producer_evidence.length !== manifest.links.length) {
    throw new Error("producer evidence cardinality must equal manifest links cardinality");
  }
  return {
    ...manifest,
    state: toState,
    links: updates.producer_evidence ? manifest.links.map((item, index) => ({
      ...item,
      producer_evidence: updates.producer_evidence[index]
    })) : manifest.links,
    projects_forward_receipt_id: updates.projects_forward_receipt_id === undefined ? manifest.projects_forward_receipt_id : updates.projects_forward_receipt_id,
    projects_inverse_receipt_id: updates.projects_inverse_receipt_id === undefined ? manifest.projects_inverse_receipt_id : updates.projects_inverse_receipt_id,
    projects_reference_proof: updates.projects_reference_proof === undefined ? manifest.projects_reference_proof : updates.projects_reference_proof,
    last_verified_projects_revision: updates.last_verified_projects_revision === undefined ? manifest.last_verified_projects_revision : updates.last_verified_projects_revision,
    last_verified_projects_digest: updates.last_verified_projects_digest === undefined ? manifest.last_verified_projects_digest : updates.last_verified_projects_digest,
    transition_version: manifest.transition_version + 1,
    updated_at: updatedAt
  };
}
function rowToProjectResourceLinkMigrationManifest(row) {
  return {
    schema: "projects.project_resource_link_migration_manifest.v1",
    manifest_id: row.manifest_id,
    project_id: row.project_id,
    operation_id: row.operation_id,
    step_id: row.step_id,
    state: row.state,
    expected_project_revision: row.expected_project_revision,
    desired_collection_digest: row.desired_collection_digest,
    links: JSON.parse(row.links_json),
    projects_forward_receipt_id: row.projects_forward_receipt_id,
    projects_inverse_receipt_id: row.projects_inverse_receipt_id,
    projects_reference_proof: row.projects_reference_proof_json ? JSON.parse(row.projects_reference_proof_json) : null,
    last_verified_projects_revision: row.last_verified_projects_revision,
    last_verified_projects_digest: row.last_verified_projects_digest,
    transition_version: Number(row.transition_version),
    created_at: row.created_at,
    updated_at: row.updated_at
  };
}
function migrationEvent(manifestId, transitionVersion, fromState, toState, requestDigest2, preconditionDigest2, evidence2, createdAt) {
  return {
    event_id: projectResourceLinkMigrationEventId(manifestId, transitionVersion, toState),
    manifest_id: manifestId,
    transition_version: transitionVersion,
    from_state: fromState,
    to_state: toState,
    request_digest: requestDigest2,
    precondition_digest: preconditionDigest2,
    evidence: evidence2,
    created_at: createdAt
  };
}

// src/lib/project-quarantine.ts
var PROJECT_QUARANTINE_ROUTE = "projects.duplicate-quarantine.v1";
var PROJECT_QUARANTINE_EVENT = "duplicate_project_quarantined";
var PROJECT_QUARANTINE_ROLLBACK_EVENT = "duplicate_project_quarantine_rolled_back";
var PROJECT_QUARANTINE_METADATA_KEY = "projects_duplicate_quarantine";
function workspaceLocationsDigest(locations) {
  return sha256(canonicalJson([...locations].sort((a, b) => a.id.localeCompare(b.id))));
}
function projectDigest(project, locations = []) {
  return sha256(canonicalJson({
    project: workspaceSnapshot(project),
    workspace_locations: [...locations].sort((a, b) => a.id.localeCompare(b.id))
  }));
}
function projectQuarantineSnapshot(project, resourceLinks, workspaceLocations) {
  return {
    project,
    project_digest: projectDigest(project, workspaceLocations),
    resource_links: resourceLinks,
    resource_link_collection_digest: projectResourceLinksDigest(resourceLinks),
    workspace_locations: workspaceLocations,
    workspace_location_collection_digest: workspaceLocationsDigest(workspaceLocations)
  };
}
function projectQuarantineSnapshotJson(snapshot) {
  return snapshot;
}
function parseProjectQuarantineSnapshot(value, label) {
  const snapshot = value;
  if (!snapshot?.project?.id || !Array.isArray(snapshot.resource_links) || !Array.isArray(snapshot.workspace_locations) || typeof snapshot.project_digest !== "string" || typeof snapshot.resource_link_collection_digest !== "string" || typeof snapshot.workspace_location_collection_digest !== "string") {
    throw new Error(`${label} quarantine receipt snapshot is incomplete`);
  }
  if (projectDigest(snapshot.project, snapshot.workspace_locations) !== snapshot.project_digest) {
    throw new Error(`${label} quarantine receipt project digest mismatch`);
  }
  if (projectResourceLinksDigest(snapshot.resource_links) !== snapshot.resource_link_collection_digest) {
    throw new Error(`${label} quarantine receipt resource-link digest mismatch`);
  }
  if (workspaceLocationsDigest(snapshot.workspace_locations) !== snapshot.workspace_location_collection_digest) {
    throw new Error(`${label} quarantine receipt workspace-location digest mismatch`);
  }
  return snapshot;
}
function normalizedExpectedResourceLinkIds(input) {
  const ids = input.expected_resource_link_ids.map((value) => value.trim()).sort();
  if (ids.some((value) => !value)) {
    throw new Error("project quarantine expected_resource_link_ids must be non-empty strings");
  }
  if (new Set(ids).size !== ids.length) {
    throw new Error("project quarantine expected_resource_link_ids must be unique");
  }
  if (ids.length > input.resource_link_max_items) {
    throw new Error("project quarantine expected link set exceeds resource_link_max_items");
  }
  return ids;
}
function normalizedExpectedWorkspaceLocationIds(input) {
  const ids = input.expected_workspace_location_ids.map((value) => value.trim()).sort();
  if (ids.some((value) => !value)) {
    throw new Error("project quarantine expected_workspace_location_ids must be non-empty strings");
  }
  if (new Set(ids).size !== ids.length) {
    throw new Error("project quarantine expected_workspace_location_ids must be unique");
  }
  if (ids.length > input.workspace_location_max_items) {
    throw new Error("project quarantine expected workspace-location set exceeds workspace_location_max_items");
  }
  return ids;
}
function projectQuarantineRequestDigest(input) {
  return sha256(canonicalJson({
    route: PROJECT_QUARANTINE_ROUTE,
    quarantine_name: input.quarantine_name.trim(),
    quarantine_slug: input.quarantine_slug.trim()
  }));
}
function projectQuarantinePreconditionDigest(input, expectedIds = normalizedExpectedResourceLinkIds(input), expectedLocationIds = normalizedExpectedWorkspaceLocationIds(input)) {
  return sha256(canonicalJson({
    route: PROJECT_QUARANTINE_ROUTE,
    project_id: input.project_id,
    expected_revision: input.expected_revision,
    expected_project_digest: input.expected_project_digest,
    expected_resource_link_collection_digest: input.expected_resource_link_collection_digest,
    expected_resource_link_ids: expectedIds,
    resource_link_max_items: input.resource_link_max_items,
    expected_workspace_location_collection_digest: input.expected_workspace_location_collection_digest,
    expected_workspace_location_ids: expectedLocationIds,
    workspace_location_max_items: input.workspace_location_max_items
  }));
}
function projectQuarantinePatch(input, before) {
  const quarantineName = input.quarantine_name.trim();
  const quarantineSlug = input.quarantine_slug.trim();
  if (!quarantineName)
    throw new Error("project quarantine requires a non-empty quarantine_name");
  if (!quarantineSlug)
    throw new Error("project quarantine requires a non-empty quarantine_slug");
  if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(quarantineSlug)) {
    throw new Error("project quarantine requires an already-canonical quarantine_slug");
  }
  return {
    name: quarantineName,
    slug: quarantineSlug,
    status: "archived",
    root_id: null,
    recipe_id: null,
    canonical_machine: null,
    primary_path: null,
    git_remote: null,
    s3_bucket: null,
    s3_prefix: null,
    integrations: {},
    tags: [...new Set([...before.project.tags, "duplicate-quarantine", "provenance-only"])].sort(),
    metadata: {
      ...before.project.metadata,
      [PROJECT_QUARANTINE_METADATA_KEY]: {
        schema: "hasna.projects.duplicate-quarantine.v1",
        operation_id: input.operation_id,
        step_id: input.step_id,
        original_project_digest: before.project_digest,
        original_resource_link_collection_digest: before.resource_link_collection_digest,
        original_resource_link_ids: before.resource_links.map((link) => link.id).sort(),
        original_workspace_location_collection_digest: before.workspace_location_collection_digest,
        original_workspace_location_ids: before.workspace_locations.map((location) => location.id).sort()
      }
    },
    last_opened_at: null
  };
}
function assertProjectQuarantinePreconditions(input, before) {
  const expectedIds = normalizedExpectedResourceLinkIds(input);
  const expectedLocationIds = normalizedExpectedWorkspaceLocationIds(input);
  const actualIds = before.resource_links.map((link) => link.id).sort();
  const actualLocationIds = before.workspace_locations.map((location) => location.id).sort();
  if (before.project.updated_at !== input.expected_revision)
    return "stale_revision";
  if (before.project_digest !== input.expected_project_digest)
    return "project_digest_mismatch";
  if (canonicalJson(actualIds) !== canonicalJson(expectedIds))
    return "resource_link_target_set_mismatch";
  if (before.resource_link_collection_digest !== input.expected_resource_link_collection_digest) {
    return "resource_link_collection_digest_mismatch";
  }
  if (canonicalJson(actualLocationIds) !== canonicalJson(expectedLocationIds)) {
    return "workspace_location_target_set_mismatch";
  }
  if (before.workspace_location_collection_digest !== input.expected_workspace_location_collection_digest) {
    return "workspace_location_collection_digest_mismatch";
  }
  return null;
}
function assertProjectQuarantinePostimage(input, before, after) {
  const marker = after.project.metadata[PROJECT_QUARANTINE_METADATA_KEY];
  if (after.project.status !== "archived" || after.project.name !== input.quarantine_name.trim() || after.project.slug !== input.quarantine_slug.trim() || after.project.root_id !== null || after.project.recipe_id !== null || after.project.canonical_machine !== null || after.project.primary_path !== null || after.project.git_remote !== null || after.project.s3_bucket !== null || after.project.s3_prefix !== null || Object.keys(after.project.integrations).length !== 0 || after.resource_links.length !== 0 || after.workspace_locations.length !== 0 || marker?.original_project_digest !== before.project_digest || marker?.original_resource_link_collection_digest !== before.resource_link_collection_digest || canonicalJson(marker?.original_resource_link_ids) !== canonicalJson(before.resource_links.map((link) => link.id).sort()) || marker?.original_workspace_location_collection_digest !== before.workspace_location_collection_digest || canonicalJson(marker?.original_workspace_location_ids) !== canonicalJson(before.workspace_locations.map((location) => location.id).sort())) {
    throw new Error("project quarantine exact post-write readback mismatch");
  }
}
function restoreProjectPatch(snapshot) {
  const before = snapshot.project;
  return {
    name: before.name,
    slug: before.slug,
    description: before.description,
    kind: before.kind,
    status: before.status,
    root_id: before.root_id,
    recipe_id: before.recipe_id,
    canonical_machine: before.canonical_machine,
    primary_path: before.primary_path,
    git_remote: before.git_remote,
    s3_bucket: before.s3_bucket,
    s3_prefix: before.s3_prefix,
    tags: before.tags,
    integrations: before.integrations,
    metadata: before.metadata,
    last_opened_at: before.last_opened_at
  };
}

// src/db/workspaces.ts
var nanoid2 = customAlphabet(`0123456789${"abcdefghijklmnopqrstuvwxyz"}`, 12);
function renderTemplate(template, values) {
  return template.replace(/\{([a-zA-Z0-9_]+)\}/g, (_match, key) => values[key] ?? "");
}

// src/lib/workspace-plan.ts
import { basename, dirname, isAbsolute, join as join2, resolve as resolve2, sep } from "path";
function deriveWorkspacePath(input, root, slug, id, kind) {
  if (input.primary_path)
    return resolve2(input.primary_path);
  if (!root && kind !== "remote-only")
    return projectWorkspaceStorePath(id);
  if (!root)
    return null;
  const rendered = renderTemplate(root.path_template || root.name_template || "{slug}", {
    slug,
    name: input.name,
    kind,
    root: root.slug,
    org: root.github_org
  });
  return isAbsolute(rendered) ? resolve2(rendered) : resolve2(join2(root.base_path, rendered));
}
function deriveWorkspaceRegistryFields(input, context) {
  const primary_path = deriveWorkspacePath(input, context.root, context.slug, context.id, context.kind);
  const integrations = { ...input.integrations ?? {} };
  if (!integrations.conversations_channel?.trim()) {
    try {
      integrations.conversations_channel = deriveProjectChannel({
        slug: context.slug,
        kind: context.kind,
        integrations
      }).channel;
    } catch {
      delete integrations.conversations_channel;
    }
  }
  return { primary_path, integrations };
}

// src/lib/project-registration.ts
var PROJECT_REGISTRATION_ROUTE = "projects.full-registration.v1";
var PROJECT_REGISTRATION_MAX_RECEIPTS = 32;
class ProjectRegistrationPathHandle {
  #absolutePath;
  #pathDigest;
  constructor(path) {
    this.#absolutePath = resolve3(path);
    this.#pathDigest = sha256(this.#absolutePath);
  }
  static fromPath(path) {
    if (!path?.trim())
      throw new Error("project registration requires a non-empty target path");
    return new ProjectRegistrationPathHandle(path);
  }
  get digest() {
    return this.#pathDigest;
  }
  withOwnedPath(consumer) {
    return consumer(this.#absolutePath);
  }
}
function parseJsonObjectArray(raw) {
  const parsed = JSON.parse(raw);
  if (!Array.isArray(parsed))
    throw new Error("project registration receipt array is malformed");
  return parsed;
}
function parseAuthorityReceipt(raw) {
  return raw ? JSON.parse(raw) : null;
}
function rowToReceipt(row) {
  return {
    receipt_id: row.receipt_id,
    operation_id: row.operation_id,
    sequence: row.sequence,
    step_id: row.step_id,
    authority: row.authority,
    resource_kind: row.resource_kind,
    direction: row.direction,
    idempotency_key: row.idempotency_key,
    target_id: row.target_id,
    request_digest: row.request_digest,
    precondition_digest: row.precondition_digest,
    outcome: row.outcome,
    reason: row.reason,
    result_revision: row.result_revision,
    result_digest: row.result_digest,
    duplicate_of_receipt_id: row.duplicate_of_receipt_id,
    authority_receipt: parseAuthorityReceipt(row.authority_receipt_json),
    artifacts: parseJsonObjectArray(row.artifacts_json),
    preconditions: parseJsonObjectArray(row.preconditions_json),
    rollback: parseJsonObjectArray(row.rollback_json),
    created_at: row.created_at
  };
}
function safeAuthorityReceipt(receipt) {
  if (!("resource_kind" in receipt)) {
    return {
      receipt_id: receipt.receipt_id,
      authority: receipt.authority,
      route: receipt.route,
      package_version: receipt.package_version,
      authority_id: receipt.authority_id,
      tenant_id: receipt.tenant_id,
      corpus_id: receipt.corpus_id,
      operation_id: receipt.operation_id,
      step_id: receipt.step_id,
      direction: receipt.direction,
      idempotency_key: receipt.idempotency_key,
      request_digest: receipt.request_digest,
      outcome: receipt.outcome,
      target_id: receipt.target_id,
      expected_revision: receipt.expected_revision,
      result_revision: receipt.result_revision,
      result_digest: receipt.result_digest,
      accepted_receipt_id: receipt.accepted_receipt_id,
      created_at: receipt.created_at
    };
  }
  return {
    receipt_id: receipt.receipt_id,
    authority: receipt.authority,
    route: receipt.route,
    package_version: receipt.package_version,
    authority_id: receipt.authority_id,
    tenant_id: receipt.tenant_id,
    corpus_id: receipt.corpus_id,
    operation_id: receipt.operation_id,
    step_id: receipt.step_id,
    resource_kind: receipt.resource_kind,
    direction: receipt.direction,
    idempotency_key: receipt.idempotency_key,
    request_digest: receipt.request_digest,
    precondition_digest: receipt.precondition_digest,
    outcome: receipt.outcome,
    reason: receipt.reason,
    target_id: receipt.target_id,
    result_revision: receipt.result_revision,
    result_digest: receipt.result_digest,
    duplicate_of_receipt_id: receipt.duplicate_of_receipt_id,
    accepted_receipt_id: receipt.accepted_receipt_id,
    created_by_operation: receipt.created_by_operation,
    created_at: receipt.created_at
  };
}
function receiptLogicalPayload(input) {
  return {
    operation_id: input.operation_id,
    step_id: input.step_id,
    authority: input.authority,
    resource_kind: input.resource_kind,
    direction: input.direction,
    idempotency_key: input.idempotency_key,
    target_id: input.target_id ?? null,
    request_digest: input.request_digest,
    precondition_digest: input.precondition_digest,
    outcome: input.outcome,
    reason: input.reason ?? null,
    result_revision: input.result_revision ?? null,
    result_digest: input.result_digest ?? null,
    duplicate_of_receipt_id: input.duplicate_of_receipt_id ?? null,
    authority_receipt: input.authority_receipt ? safeAuthorityReceipt(input.authority_receipt) : null,
    artifacts: input.artifacts ?? [],
    preconditions: input.preconditions ?? [],
    rollback: input.rollback ?? []
  };
}
function buildReceiptId2(input) {
  return `prr_${sha256(canonicalJson(receiptLogicalPayload(input))).slice(0, 36)}`;
}
function deriveProjectRegistrationIdempotencyKey(input) {
  return `prk_${sha256(canonicalJson({
    route: PROJECT_REGISTRATION_ROUTE,
    ...input
  })).slice(0, 48)}`;
}
function projectRegistrationManifestFromRow(row) {
  return {
    operation_id: row.operation_id,
    route: row.route,
    request_digest: row.request_digest,
    project_id: row.project_id,
    project_slug: row.project_slug,
    plan: JSON.parse(row.plan_json),
    created_at: row.created_at
  };
}
function registrationPlanMatches(stored, requestedCanonical) {
  if (stored === requestedCanonical)
    return true;
  try {
    return canonicalJson(JSON.parse(stored)) === requestedCanonical;
  } catch {
    return false;
  }
}

// src/serve/pg-store.ts
var PROJECT_RELATION_HIERARCHY_LOCK_KEY = BigInt.asIntN(64, BigInt(`0x${sha256("hasna.projects.project-relations:hierarchy-graph").slice(0, 16)}`));
function generateWorkspaceId2() {
  return `wks_${nanoid()}`;
}
function generateRootId() {
  return `root_${nanoid()}`;
}
function generateRecipeId() {
  return `rcp_${nanoid()}`;
}
function generateAgentId() {
  return `agt_${nanoid()}`;
}
function generateEventId() {
  return `evt_${nanoid()}`;
}
function slugify(name) {
  return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
}
function nowIso() {
  return new Date().toISOString().replace("T", " ").replace("Z", "");
}
function parseJson2(raw, fallback) {
  if (!raw)
    return fallback;
  try {
    return JSON.parse(raw);
  } catch {
    return fallback;
  }
}
function json(value) {
  return JSON.stringify(value ?? null);
}
function normalizeList(values) {
  return [...new Set((values ?? []).map((v) => v.trim()).filter(Boolean))];
}
function hasOwn(metadata, key) {
  return Object.prototype.hasOwnProperty.call(metadata, key);
}
function canonicalMachineFromMetadata(metadata) {
  if (!hasOwn(metadata, "canonical_machine"))
    return;
  const value = metadata["canonical_machine"];
  if (value === null)
    return null;
  if (typeof value !== "string") {
    throw new ValidationError("canonical_machine metadata must be a machine slug string");
  }
  return value.trim() || null;
}
function withoutCanonicalMachineMetadata(metadata) {
  const copy = { ...metadata };
  delete copy["canonical_machine"];
  return copy;
}
function rowToRoot(row) {
  return {
    ...row,
    tags: parseJson2(row.tags, []),
    default_kind: row.default_kind,
    repo_visibility: row.repo_visibility,
    allowed_recipes: parseJson2(row.allowed_recipes, []),
    allowed_agents: parseJson2(row.allowed_agents, []),
    metadata: parseJson2(row.metadata, {})
  };
}
function rowToAgent(row) {
  return {
    ...row,
    kind: row.kind,
    permissions: parseJson2(row.permissions, []),
    metadata: parseJson2(row.metadata, {})
  };
}
function rowToRecipe(row) {
  return {
    ...row,
    kind: row.kind,
    steps: parseJson2(row.steps, []),
    variables: parseJson2(row.variables, {}),
    default_tags: parseJson2(row.default_tags, []),
    metadata: parseJson2(row.metadata, {})
  };
}
function rowToWorkspace(row) {
  return {
    ...row,
    kind: row.kind,
    status: row.status,
    tags: parseJson2(row.tags, []),
    integrations: parseJson2(row.integrations, {}),
    metadata: parseJson2(row.metadata, {})
  };
}
function rowToWorkspaceLocation(row) {
  return {
    ...row,
    is_primary: Boolean(row.is_primary),
    exists_at_create: Boolean(row.exists_at_create),
    metadata: parseJson2(row.metadata, {})
  };
}
function projectRelationSnapshotJson(snapshot) {
  return snapshot;
}
function parseProjectRelationSnapshot(value, label) {
  const snapshot = value;
  if (!snapshot?.project?.id || !Array.isArray(snapshot.relations) || typeof snapshot.collection_digest !== "string") {
    throw new ValidationError(`${label} relation receipt snapshot is incomplete`);
  }
  return snapshot;
}
function rowToWorkspaceLock(row) {
  return {
    id: row.id,
    lock_key: row.lock_key,
    workspace_id: row.workspace_id,
    agent_id: row.agent_id,
    reason: row.reason,
    created_at: row.created_at,
    expires_at: row.expires_at
  };
}
function resourceLinkSnapshotJson(snapshot) {
  return snapshot;
}
function parseResourceLinkSnapshot(value, label) {
  const snapshot = value;
  if (!snapshot?.project?.id || !Array.isArray(snapshot.links) || typeof snapshot.collection_digest !== "string") {
    throw new ValidationError(`${label} receipt snapshot is incomplete`);
  }
  return snapshot;
}
function resourceLinkInputFromStored(link) {
  const { id: _id, project_id: _projectId, created_at: _createdAt, updated_at: _updatedAt, ...input } = link;
  return input;
}
function nextResourceLinkRevision(current) {
  const currentMs = Date.parse(current.replace(" ", "T") + "Z");
  const nowValue = nowIso();
  if (nowValue !== current)
    return nowValue;
  return Number.isFinite(currentMs) ? new Date(currentMs + 1).toISOString().replace("T", " ").replace("Z", "") : `${current}.1`;
}
function rowToEvent(row) {
  return {
    ...row,
    source: row.source,
    before_json: parseJson2(row.before_json, null),
    after_json: parseJson2(row.after_json, null),
    metadata: parseJson2(row.metadata, {})
  };
}

class NotFoundError extends Error {
  status = 404;
  constructor(message) {
    super(message);
    this.name = "NotFoundError";
  }
}

class ValidationError extends Error {
  status = 400;
  constructor(message) {
    super(message);
    this.name = "ValidationError";
  }
}

class ProjectRegistrationLedgerError extends Error {
  reason;
  status;
  constructor(reason, message, status = 409) {
    super(message);
    this.reason = reason;
    this.status = status;
    this.name = "ProjectRegistrationLedgerError";
  }
}
function pgRegistrationReceiptRow(row) {
  return {
    receipt_id: row.receipt_id,
    operation_id: row.operation_id,
    sequence: Number(row.sequence),
    step_id: row.step_id,
    authority: row.authority,
    resource_kind: row.resource_kind,
    direction: row.direction,
    idempotency_key: row.idempotency_key,
    target_id: row.target_id,
    request_digest: row.request_digest,
    precondition_digest: row.precondition_digest,
    outcome: row.outcome,
    reason: row.reason,
    result_revision: row.result_revision,
    result_digest: row.result_digest,
    duplicate_of_receipt_id: row.duplicate_of_receipt_id,
    authority_receipt_json: row.authority_receipt_json === null ? null : canonicalJson(row.authority_receipt_json),
    artifacts_json: canonicalJson(row.artifacts_json ?? []),
    preconditions_json: canonicalJson(row.preconditions_json ?? []),
    rollback_json: canonicalJson(row.rollback_json ?? []),
    created_at: row.created_at
  };
}
function assertHostedProjectResourceLinkIntegrationMutation(beforeIntegrations, proposedIntegrations, links) {
  try {
    assertProjectResourceLinkIntegrationMutation(beforeIntegrations, proposedIntegrations, links);
  } catch (error) {
    throw new ValidationError(error instanceof Error ? error.message : String(error));
  }
}
var WORKSPACE_LIST_DEFAULT_LIMIT = 100;
var WORKSPACE_LIST_MAX_LIMIT = 1000;

class ProjectsPgStore {
  db;
  producerEvidenceVerifier;
  constructor(db, producerEvidenceVerifier) {
    this.db = db;
    this.producerEvidenceVerifier = producerEvidenceVerifier;
  }
  async inTransaction(operation, fn) {
    const transaction = this.db.transaction;
    if (typeof transaction !== "function") {
      throw new ValidationError(`${operation} requires a transaction-capable Postgres client`);
    }
    return transaction.call(this.db, async (client) => fn(new ProjectsPgStore(client, this.producerEvidenceVerifier)));
  }
  async ensureUniqueSlug(table, base, excludeId) {
    const safeBase = base || "workspace";
    let candidate = safeBase;
    let suffix = 1;
    for (;; ) {
      const row = await this.db.get(`SELECT id FROM ${table} WHERE slug = $1`, [candidate]);
      if (!row || row.id === excludeId)
        return candidate;
      suffix++;
      candidate = `${safeBase}-${suffix}`;
    }
  }
  async listRoots() {
    const rows = await this.db.many("SELECT * FROM roots ORDER BY slug ASC");
    return rows.map(rowToRoot);
  }
  async getRoot(idOrSlug) {
    const row = await this.db.get("SELECT * FROM roots WHERE id = $1 OR slug = $1", [idOrSlug]);
    return row ? rowToRoot(row) : null;
  }
  async createRoot(input) {
    if (!input.name?.trim())
      throw new ValidationError("root name is required");
    if (!input.base_path?.trim())
      throw new ValidationError("root base_path is required");
    const id = generateRootId();
    const ts = nowIso();
    const slug = await this.ensureUniqueSlug("roots", input.slug ?? slugify(input.name));
    await this.db.execute(`INSERT INTO roots (
        id, slug, name, base_path, tags, default_kind, default_recipe_id,
        default_tmux_profile_id, github_org, repo_visibility, path_template,
        name_template, allowed_recipes, allowed_agents, metadata, created_at, updated_at
      ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17)`, [
      id,
      slug,
      input.name,
      input.base_path,
      json(normalizeList(input.tags)),
      input.default_kind ?? null,
      input.default_recipe_id ?? null,
      input.default_tmux_profile_id ?? null,
      input.github_org ?? null,
      input.repo_visibility ?? null,
      input.path_template ?? null,
      input.name_template ?? null,
      json(normalizeList(input.allowed_recipes)),
      json(normalizeList(input.allowed_agents)),
      json(input.metadata ?? {}),
      ts,
      ts
    ]);
    return await this.getRoot(id);
  }
  async updateRoot(idOrSlug, input) {
    const before = await this.getRoot(idOrSlug);
    if (!before)
      throw new NotFoundError(`Root not found: ${idOrSlug}`);
    const updates = [];
    const params = [];
    const set = (col, val) => {
      params.push(val);
      updates.push(`${col} = $${params.length}`);
    };
    if (input.slug !== undefined)
      set("slug", await this.ensureUniqueSlug("roots", slugify(input.slug), before.id));
    if (input.name !== undefined)
      set("name", input.name);
    if (input.base_path !== undefined)
      set("base_path", input.base_path);
    if (input.tags !== undefined)
      set("tags", json(normalizeList(input.tags)));
    if (input.default_kind !== undefined)
      set("default_kind", input.default_kind);
    if (input.github_org !== undefined)
      set("github_org", input.github_org);
    if (input.repo_visibility !== undefined)
      set("repo_visibility", input.repo_visibility);
    if (input.path_template !== undefined)
      set("path_template", input.path_template);
    if (input.name_template !== undefined)
      set("name_template", input.name_template);
    if (input.allowed_recipes !== undefined)
      set("allowed_recipes", json(normalizeList(input.allowed_recipes)));
    if (input.allowed_agents !== undefined)
      set("allowed_agents", json(normalizeList(input.allowed_agents)));
    if (input.metadata !== undefined)
      set("metadata", json(input.metadata));
    if (!updates.length)
      return before;
    set("updated_at", nowIso());
    params.push(before.id);
    await this.db.execute(`UPDATE roots SET ${updates.join(", ")} WHERE id = $${params.length}`, params);
    return await this.getRoot(before.id);
  }
  async deleteRoot(idOrSlug, detachWorkspaces = false) {
    const root = await this.getRoot(idOrSlug);
    if (!root)
      throw new NotFoundError(`Root not found: ${idOrSlug}`);
    const countRow = await this.db.get("SELECT COUNT(*)::int AS n FROM workspaces WHERE root_id = $1", [root.id]);
    const count = Number(countRow?.n ?? 0);
    if (count > 0 && !detachWorkspaces) {
      throw new ValidationError(`Root ${root.slug} is used by ${count} workspace(s); pass detach=true to clear those references before deletion.`);
    }
    if (count > 0) {
      await this.db.execute("UPDATE workspaces SET root_id = NULL, updated_at = $1 WHERE root_id = $2", [
        nowIso(),
        root.id
      ]);
    }
    await this.db.execute("DELETE FROM roots WHERE id = $1", [root.id]);
    return { root, detached_workspaces: count };
  }
  async listAgents() {
    const rows = await this.db.many("SELECT * FROM agents ORDER BY slug ASC");
    return rows.map(rowToAgent);
  }
  async getAgent(idOrSlug) {
    const row = await this.db.get("SELECT * FROM agents WHERE id = $1 OR slug = $1", [idOrSlug]);
    return row ? rowToAgent(row) : null;
  }
  async createAgent(input) {
    if (!input.name?.trim())
      throw new ValidationError("agent name is required");
    const kind = input.kind ?? "ai";
    if (!["human", "ai", "service", "cli"].includes(kind)) {
      throw new ValidationError(`invalid agent kind: ${kind}`);
    }
    const id = generateAgentId();
    const ts = nowIso();
    const slug = await this.ensureUniqueSlug("agents", input.slug ?? slugify(input.name));
    await this.db.execute(`INSERT INTO agents (id, slug, name, kind, provider, model, role, permissions, metadata, created_at, updated_at)
       VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)`, [
      id,
      slug,
      input.name,
      kind,
      input.provider ?? null,
      input.model ?? null,
      input.role ?? null,
      json(normalizeList(input.permissions)),
      json(input.metadata ?? {}),
      ts,
      ts
    ]);
    return await this.getAgent(id);
  }
  async listRecipes() {
    const rows = await this.db.many("SELECT * FROM recipes ORDER BY slug ASC");
    return rows.map(rowToRecipe);
  }
  async getRecipe(idOrSlug) {
    const row = await this.db.get("SELECT * FROM recipes WHERE id = $1 OR slug = $1", [idOrSlug]);
    return row ? rowToRecipe(row) : null;
  }
  async createRecipe(input) {
    if (!input.name?.trim())
      throw new ValidationError("recipe name is required");
    const id = generateRecipeId();
    const ts = nowIso();
    const slug = await this.ensureUniqueSlug("recipes", input.slug ?? slugify(input.name));
    await this.db.execute(`INSERT INTO recipes (id, slug, name, description, kind, version, steps, variables, default_tags, default_tmux_profile_id, metadata, created_at, updated_at)
       VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)`, [
      id,
      slug,
      input.name,
      input.description ?? null,
      input.kind ?? null,
      input.version ?? 1,
      json(input.steps ?? []),
      json(input.variables ?? {}),
      json(normalizeList(input.default_tags)),
      input.default_tmux_profile_id ?? null,
      json(input.metadata ?? {}),
      ts,
      ts
    ]);
    return await this.getRecipe(id);
  }
  workspaceFilterSql(filter) {
    const conditions = [];
    const params = [];
    const push = (clause, value) => {
      params.push(value);
      conditions.push(clause(params.length));
    };
    if (filter.status)
      push((i) => `status = $${i}`, filter.status);
    if (filter.kind)
      push((i) => `kind = $${i}`, filter.kind);
    if (filter.root_id)
      push((i) => `root_id = $${i}`, filter.root_id);
    if (filter.query) {
      const scope = filter.query_scope;
      const normalizedQuery = filter.query.toLowerCase();
      params.push(`%${scope === undefined ? normalizedQuery : normalizedQuery.replace(/[\\%_]/g, "\\$&")}%`);
      const i = params.length;
      const columns = scope === undefined ? ["name", "slug", "COALESCE(description,'')", "COALESCE(primary_path,'')", "COALESCE(tags,'')", "COALESCE(metadata,'')"] : scope === "identity" ? ["name", "slug"] : scope === "discovery" ? ["name", "slug", "COALESCE(description,'')", "COALESCE(tags,'')"] : scope === "structured" ? ["name", "slug", "COALESCE(description,'')", "COALESCE(tags,'')", "COALESCE(integrations,'')", "COALESCE(metadata,'')"] : ["name", "slug", "COALESCE(description,'')", "COALESCE(primary_path,'')", "COALESCE(tags,'')", "COALESCE(integrations,'')", "COALESCE(metadata,'')"];
      const escape = scope === undefined ? "" : " ESCAPE '\\'";
      conditions.push(`(${columns.map((column) => `lower(${column}) LIKE $${i}${escape}`).join(" OR ")})`);
    }
    if (filter.tags && filter.tags.length > 0) {
      for (const tag of filter.tags) {
        params.push(tag);
        conditions.push(`(tags::jsonb ? $${params.length})`);
      }
    }
    if (filter.exclude_eval_artifacts) {
      conditions.push(`NOT (
        slug LIKE 'eval-%'
        OR name LIKE 'Eval %'
        OR EXISTS (
          SELECT 1 FROM jsonb_array_elements_text(tags::jsonb) AS tag(value)
          WHERE tag.value = 'eval' OR tag.value LIKE 'eval-%'
        )
        OR COALESCE(metadata::jsonb -> 'eval_fixture', 'false'::jsonb) = 'true'::jsonb
        OR COALESCE(metadata::jsonb -> 'agent_eval_fixture', 'false'::jsonb) = 'true'::jsonb
      )`);
    }
    if (filter.exclude_registry_fixtures) {
      conditions.push(`NOT (tags::jsonb ? 'registry-fixture')`);
    }
    return { where: conditions.length ? `WHERE ${conditions.join(" AND ")}` : "", params };
  }
  async listWorkspaces(filter = {}) {
    const { where, params } = this.workspaceFilterSql(filter);
    params.push(Math.min(Math.max(filter.limit ?? WORKSPACE_LIST_DEFAULT_LIMIT, 1), WORKSPACE_LIST_MAX_LIMIT));
    const limitIdx = params.length;
    params.push(Math.max(filter.offset ?? 0, 0));
    const offsetIdx = params.length;
    const rows = await this.db.many(`SELECT * FROM workspaces ${where} ORDER BY name ASC, id ASC LIMIT $${limitIdx} OFFSET $${offsetIdx}`, params);
    return rows.map(rowToWorkspace);
  }
  async countWorkspaces(filter = {}) {
    const { where, params } = this.workspaceFilterSql(filter);
    const row = await this.db.get(`SELECT COUNT(*) AS n FROM workspaces ${where}`, params);
    return Number(row?.n ?? 0);
  }
  async getWorkspace(idOrSlug) {
    const row = await this.db.get("SELECT * FROM workspaces WHERE id = $1 OR slug = $1", [idOrSlug]);
    return row ? rowToWorkspace(row) : null;
  }
  async issueProductProjection(policy, principal, projectId, input) {
    return this.inTransaction("issue product projection", (tx) => issueProductProjection(tx.db, (request, started) => tx.guardedReadWorkspace(request, started), policy, principal, projectId, input));
  }
  async readProductProjection(policy, principal, projectId, receiptId, input) {
    return this.inTransaction("read product projection", (tx) => readProductProjection(tx.db, policy, principal, projectId, receiptId, input));
  }
  async guardedReadWorkspace(input, startedAtMs = Date.now()) {
    try {
      assertCompleteStableProjectId(input.project_id);
      assertPositiveBounds(input);
    } catch (err) {
      throw new ValidationError(err instanceof Error ? err.message : String(err));
    }
    const maxItems = input.resource_link_max_items ?? PROJECT_RESOURCE_LINK_DEFAULT_MAX_ITEMS;
    if (!Number.isInteger(maxItems) || maxItems <= 0) {
      throw new ValidationError("project resource link max_items must be a positive integer");
    }
    const row = await this.db.get(`SELECT w.*, COALESCE((
         SELECT jsonb_agg(links ORDER BY authority, service_instance, source_package,
                         target_kind, locator_kind, locator_value, id)
         FROM (
           SELECT * FROM project_resource_links
           WHERE project_id = w.id
           ORDER BY authority, service_instance, source_package, target_kind, locator_kind, locator_value, id
           LIMIT $2
         ) links
       ), '[]'::jsonb) AS resource_link_rows
       FROM workspaces w WHERE w.id = $1`, [input.project_id, maxItems + 1]);
    if (!row)
      throw new NotFoundError(`Workspace not found: ${input.project_id}`);
    try {
      const { resource_link_rows: linkRows, ...projectRow } = row;
      if (linkRows.length > maxItems) {
        throw new ValidationError(`project resource link collection exceeds max_items: more than ${maxItems}`);
      }
      const links = linkRows.map(rowToProjectResourceLink);
      return buildGuardedProjectReadResult(rowToWorkspace(projectRow), input, startedAtMs, {
        links,
        max_items: maxItems,
        collection_digest: projectResourceLinksDigest(links)
      });
    } catch (err) {
      throw new ValidationError(err instanceof Error ? err.message : String(err));
    }
  }
  async listProjectResourceLinks(projectId, maxItems = PROJECT_RESOURCE_LINK_DEFAULT_MAX_ITEMS) {
    assertCompleteStableProjectId(projectId);
    if (!Number.isInteger(maxItems) || maxItems <= 0) {
      throw new ValidationError("project resource link max_items must be a positive integer");
    }
    const rows = await this.db.many(`SELECT * FROM project_resource_links
       WHERE project_id = $1
       ORDER BY authority, service_instance, source_package, target_kind, locator_kind, locator_value, id
       LIMIT $2`, [projectId, maxItems + 1]);
    if (rows.length > maxItems) {
      throw new ValidationError(`project resource link collection exceeds max_items: more than ${maxItems}`);
    }
    return rows.map(rowToProjectResourceLink);
  }
  async listWorkspaceLocations(projectId) {
    const rows = await this.db.many(`SELECT * FROM workspace_locations
       WHERE workspace_id = $1
       ORDER BY is_primary DESC, created_at ASC, id ASC`, [projectId]);
    return rows.map(rowToWorkspaceLocation);
  }
  async listMachines() {
    const rows = await this.db.many("SELECT * FROM machines ORDER BY slug ASC");
    return rows.map((row) => ({
      slug: row.slug,
      status: row.status,
      role: row.role
    }));
  }
  async registrationManifestRow(operationId) {
    return this.db.get(`SELECT operation_id, route, request_digest, project_id, project_slug,
              plan_json::text AS plan_json, created_at
         FROM project_registration_manifests
        WHERE operation_id = $1`, [operationId]);
  }
  async requireRegistrationReceiptRow(row) {
    if (!row) {
      throw new ProjectRegistrationLedgerError("receipt_insert_missing", "registration receipt insert missing", 500);
    }
    return rowToReceipt(pgRegistrationReceiptRow(row));
  }
  async createProjectRegistrationManifest(input) {
    const planJson = canonicalJson(input.plan);
    const inserted = await this.db.get(`INSERT INTO project_registration_manifests (
         operation_id, route, request_digest, project_id, project_slug, plan_json, created_at
       ) VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7)
       ON CONFLICT (operation_id) DO NOTHING
       RETURNING operation_id`, [
      input.operation_id,
      PROJECT_REGISTRATION_ROUTE,
      input.request_digest,
      input.project_id,
      input.project_slug,
      planJson,
      nowIso()
    ]);
    const row = await this.registrationManifestRow(input.operation_id);
    if (!row) {
      throw new ProjectRegistrationLedgerError("manifest_insert_missing", "registration_manifest: manifest_insert_missing", 500);
    }
    if (row.route !== PROJECT_REGISTRATION_ROUTE || row.request_digest !== input.request_digest || row.project_id !== input.project_id || row.project_slug !== input.project_slug || !registrationPlanMatches(row.plan_json, planJson)) {
      throw new ProjectRegistrationLedgerError("operation_semantics_conflict", "registration_manifest: operation_semantics_conflict");
    }
    return { manifest: projectRegistrationManifestFromRow(row), created: inserted !== null };
  }
  async readProjectRegistrationManifest(operationId) {
    const row = await this.registrationManifestRow(operationId);
    return row ? projectRegistrationManifestFromRow(row) : null;
  }
  async appendProjectRegistrationReceipt(input) {
    const receiptId = buildReceiptId2(input);
    return this.inTransaction("project registration receipt append", async (store) => {
      const anchor = await store.db.get("SELECT operation_id FROM project_registration_manifests WHERE operation_id = $1 FOR UPDATE", [input.operation_id]);
      if (!anchor) {
        throw new ProjectRegistrationLedgerError("manifest_missing", `registration receipt requires the operation manifest first: ${input.operation_id}`);
      }
      const existing = await store.db.get("SELECT * FROM project_registration_receipts WHERE receipt_id = $1", [receiptId]);
      if (existing)
        return rowToReceipt(pgRegistrationReceiptRow(existing));
      if (input.outcome === "accepted") {
        const prior = await store.db.get(`SELECT * FROM project_registration_receipts
            WHERE operation_id = $1 AND step_id = $2 AND authority = $3 AND resource_kind = $4
              AND direction = $5 AND outcome = 'accepted'
            ORDER BY sequence ASC LIMIT 1`, [input.operation_id, input.step_id, input.authority, input.resource_kind, input.direction]);
        if (prior && prior.idempotency_key !== input.idempotency_key) {
          throw new ProjectRegistrationLedgerError("receipt_semantics_conflict", `project registration step already accepted with different semantics: ${input.step_id}`);
        }
      }
      const sequenceRow = await store.db.get("SELECT COALESCE(MAX(sequence), 0) + 1 AS next_sequence FROM project_registration_receipts WHERE operation_id = $1", [input.operation_id]);
      const sequence = Number(sequenceRow?.next_sequence ?? 1);
      await store.db.execute(`INSERT INTO project_registration_receipts (
           receipt_id, operation_id, sequence, step_id, authority, resource_kind,
           direction, idempotency_key, target_id, request_digest,
           precondition_digest, outcome, reason, result_revision, result_digest,
           duplicate_of_receipt_id, authority_receipt_json, artifacts_json,
           preconditions_json, rollback_json, created_at
         ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15,
                   $16, $17::jsonb, $18::jsonb, $19::jsonb, $20::jsonb, $21)`, [
        receiptId,
        input.operation_id,
        sequence,
        input.step_id,
        input.authority,
        input.resource_kind,
        input.direction,
        input.idempotency_key,
        input.target_id ?? null,
        input.request_digest,
        input.precondition_digest,
        input.outcome,
        input.reason ?? null,
        input.result_revision ?? null,
        input.result_digest ?? null,
        input.duplicate_of_receipt_id ?? null,
        input.authority_receipt ? canonicalJson(safeAuthorityReceipt(input.authority_receipt)) : null,
        canonicalJson(input.artifacts ?? []),
        canonicalJson(input.preconditions ?? []),
        canonicalJson(input.rollback ?? []),
        nowIso()
      ]);
      return store.requireRegistrationReceiptRow(await store.db.get("SELECT * FROM project_registration_receipts WHERE receipt_id = $1", [receiptId]));
    });
  }
  async lookupProjectRegistrationReceipt(input) {
    const startedAt = Date.now();
    if (input.max_items !== 1) {
      throw new ValidationError("project registration receipt lookup max_items must be exactly 1");
    }
    const rows = await this.db.many(`SELECT * FROM project_registration_receipts
        WHERE operation_id = $1 AND step_id = $2 AND direction = $3 AND idempotency_key = $4
        ORDER BY sequence ASC LIMIT 2`, [input.operation_id, input.step_id, input.direction, input.idempotency_key]);
    if (rows.length === 0) {
      throw new ProjectRegistrationLedgerError("receipt_lookup_invariant", "project registration receipt lookup expected exactly one terminal receipt, found 0");
    }
    const receipts = rows.map((row) => rowToReceipt(pgRegistrationReceiptRow(row)));
    const accepted = receipts.find((receipt2) => receipt2.outcome === "accepted");
    const duplicates = receipts.filter((receipt2) => receipt2.outcome === "duplicate_of_accepted");
    if (receipts.length > 1) {
      if (!accepted || duplicates.length !== receipts.length - 1 || duplicates.some((receipt2) => receipt2.duplicate_of_receipt_id !== accepted.receipt_id)) {
        throw new ProjectRegistrationLedgerError("receipt_lookup_invariant", `project registration receipt lookup expected exactly one terminal result, found ${receipts.length}`);
      }
    }
    const receipt = duplicates.at(-1) ?? accepted ?? receipts[0];
    return {
      receipt,
      response_control: responseControl({ receipt }, { response_byte_limit: input.response_byte_limit, time_budget_ms: input.time_budget_ms }, startedAt)
    };
  }
  async listProjectRegistrationReceipts(operationId) {
    const rows = await this.db.many(`SELECT * FROM project_registration_receipts
        WHERE operation_id = $1 ORDER BY sequence ASC LIMIT $2`, [operationId, PROJECT_REGISTRATION_MAX_RECEIPTS + 1]);
    if (rows.length > PROJECT_REGISTRATION_MAX_RECEIPTS) {
      throw new ProjectRegistrationLedgerError("receipt_population_exceeded", `project registration receipt population exceeds ${PROJECT_REGISTRATION_MAX_RECEIPTS}`);
    }
    return rows.map((row) => rowToReceipt(pgRegistrationReceiptRow(row)));
  }
  async findProjectRegistrationReceipts(input) {
    const rows = await this.db.many(`SELECT * FROM project_registration_receipts
        WHERE operation_id = $1 AND step_id = $2 AND direction = $3 AND outcome = 'accepted'
        ORDER BY sequence ASC LIMIT $4`, [input.operation_id, input.step_id, input.direction, input.limit]);
    return rows.map((row) => rowToReceipt(pgRegistrationReceiptRow(row)));
  }
  async addWorkspaceLocation(input) {
    const workspace = await this.requireWorkspace(input.workspace_id);
    const isPrimary = Boolean(input.is_primary);
    const machineId = input.machine_id?.trim();
    if (!machineId)
      throw new ValidationError("location machine must not be empty");
    const path = input.path.trim();
    if (!path)
      throw new ValidationError("location path is required");
    const id = nanoid(24);
    const ts = input.created_at ?? nowIso();
    if (isPrimary) {
      await this.db.execute("UPDATE workspace_locations SET is_primary = FALSE WHERE workspace_id = $1", [input.workspace_id]);
    }
    await this.db.execute(`INSERT INTO workspace_locations (
        id, workspace_id, path, machine_id, label, kind, is_primary, exists_at_create, metadata, created_at
      ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)
      ON CONFLICT (workspace_id, path, machine_id) DO UPDATE SET
        label = EXCLUDED.label,
        kind = EXCLUDED.kind,
        is_primary = EXCLUDED.is_primary,
        metadata = EXCLUDED.metadata`, [
      id,
      input.workspace_id,
      path,
      machineId,
      input.label ?? "main",
      input.kind ?? "local",
      isPrimary,
      false,
      json(input.metadata ?? {}),
      ts
    ]);
    if (isPrimary) {
      await this.db.execute("UPDATE workspaces SET primary_path = $1, updated_at = $2 WHERE id = $3", [
        path,
        nowIso(),
        input.workspace_id
      ]);
    }
    if (input.source || input.agent_id || input.command) {
      await this.recordEvent({
        workspace_id: input.workspace_id,
        agent_id: input.agent_id,
        event_type: "location_added",
        source: input.source ?? "system",
        command: input.command,
        after: { path, label: input.label ?? "main", machine_id: machineId, primary: isPrimary }
      });
    }
    const row = await this.db.get("SELECT * FROM workspace_locations WHERE workspace_id = $1 AND path = $2 AND machine_id = $3", [input.workspace_id, path, machineId]);
    if (!row)
      throw new Error(`Workspace location was not written: ${path}`);
    return rowToWorkspaceLocation(row);
  }
  async listWorkspaceAgents(workspaceId) {
    await this.requireWorkspace(workspaceId);
    const rows = await this.db.many(`SELECT wa.*, a.slug AS agent_slug, a.name AS agent_name, a.kind AS agent_kind,
              a.provider AS agent_provider, a.model AS agent_model, a.role AS agent_role,
              a.permissions AS agent_permissions
       FROM workspace_agents wa
       LEFT JOIN agents a ON a.id = wa.agent_id
       WHERE wa.workspace_id = $1
       ORDER BY wa.role ASC, wa.created_at ASC, wa.id ASC`, [workspaceId]);
    return rows.map((row) => this.toWorkspaceAgentAssignment(row));
  }
  toWorkspaceAgentAssignment(row) {
    return {
      id: row.id,
      workspace_id: row.workspace_id,
      agent_id: row.agent_id,
      role: row.role,
      assigned_by: row.assigned_by,
      metadata: parseJson2(row.metadata, {}),
      created_at: row.created_at,
      agent: row.agent_id ? rowToAgent({
        id: row.agent_id,
        slug: row.agent_slug ?? "",
        name: row.agent_name ?? "",
        kind: row.agent_kind ?? "ai",
        provider: row.agent_provider,
        model: row.agent_model,
        role: row.agent_role,
        permissions: row.agent_permissions ?? "[]",
        metadata: "{}",
        created_at: row.created_at,
        updated_at: row.created_at
      }) : null
    };
  }
  async assignAgentToWorkspace(input) {
    await this.requireWorkspace(input.workspace_id);
    const agent = await this.getAgent(input.agent_id);
    if (!agent)
      throw new NotFoundError(`Agent not found: ${input.agent_id}`);
    const role = input.role ?? "contributor";
    const id = nanoid(24);
    const ts = input.created_at ?? nowIso();
    await this.db.execute(`INSERT INTO workspace_agents (id, workspace_id, agent_id, role, assigned_by, metadata, created_at)
       VALUES ($1,$2,$3,$4,$5,$6,$7)
       ON CONFLICT (workspace_id, agent_id, role) DO NOTHING`, [id, input.workspace_id, agent.id, role, input.assigned_by ?? null, json(input.metadata ?? {}), ts]);
    const row = await this.db.get(`SELECT wa.*, a.slug AS agent_slug, a.name AS agent_name, a.kind AS agent_kind,
              a.provider AS agent_provider, a.model AS agent_model, a.role AS agent_role,
              a.permissions AS agent_permissions
       FROM workspace_agents wa
       LEFT JOIN agents a ON a.id = wa.agent_id
       WHERE wa.workspace_id = $1 AND wa.agent_id = $2 AND wa.role = $3`, [input.workspace_id, agent.id, role]);
    if (!row)
      throw new Error(`Workspace agent assignment was not written: ${input.workspace_id}/${agent.id}/${role}`);
    return this.toWorkspaceAgentAssignment(row);
  }
  async listLocks() {
    await this.pruneExpiredLocks();
    const rows = await this.db.many("SELECT * FROM workspace_locks ORDER BY created_at ASC, id ASC");
    return rows.map(rowToWorkspaceLock);
  }
  async acquireLock(input) {
    if (!input.lock_key?.trim())
      throw new ValidationError("lock_key is required");
    await this.pruneExpiredLocks();
    const existing = await this.db.get("SELECT * FROM workspace_locks WHERE lock_key = $1", [input.lock_key]);
    if (existing)
      throw new ValidationError(`Workspace lock already held: ${input.lock_key}`);
    const id = nanoid(24);
    const ts = input.created_at ?? nowIso();
    const expiresAt = input.ttl_seconds ? new Date(Date.now() + input.ttl_seconds * 1000).toISOString().replace("T", " ").replace("Z", "") : null;
    await this.db.execute(`INSERT INTO workspace_locks (id, lock_key, workspace_id, agent_id, reason, created_at, expires_at)
       VALUES ($1,$2,$3,$4,$5,$6,$7)`, [id, input.lock_key, input.workspace_id ?? null, input.agent_id ?? null, input.reason ?? null, ts, expiresAt]);
    const row = await this.db.get("SELECT * FROM workspace_locks WHERE id = $1", [id]);
    if (!row)
      throw new Error(`Workspace lock was not written: ${input.lock_key}`);
    return rowToWorkspaceLock(row);
  }
  async releaseLock(lockKey, lockId) {
    const existing = await this.db.get("SELECT * FROM workspace_locks WHERE lock_key = $1 AND id = $2", [lockKey, lockId]);
    if (!existing)
      return false;
    await this.db.execute("DELETE FROM workspace_locks WHERE lock_key = $1 AND id = $2", [lockKey, lockId]);
    return true;
  }
  async forceReleaseLock(lockKey) {
    const existing = await this.db.get("SELECT * FROM workspace_locks WHERE lock_key = $1", [lockKey]);
    if (!existing)
      return false;
    await this.db.execute("DELETE FROM workspace_locks WHERE lock_key = $1", [lockKey]);
    return true;
  }
  async pruneExpiredLocks() {
    await this.db.execute("DELETE FROM workspace_locks WHERE expires_at IS NOT NULL AND expires_at < $1", [nowIso()]);
  }
  async listWorkspaceLocationsBounded(projectId, maxItems) {
    if (!Number.isInteger(maxItems) || maxItems <= 0) {
      throw new ValidationError("project quarantine workspace_location_max_items must be a positive integer");
    }
    const rows = await this.db.many(`SELECT * FROM workspace_locations
       WHERE workspace_id = $1
       ORDER BY is_primary DESC, created_at ASC, id ASC
       LIMIT $2`, [projectId, maxItems + 1]);
    if (rows.length > maxItems) {
      throw new ValidationError(`project quarantine workspace-location collection exceeds max_items: more than ${maxItems}`);
    }
    return rows.map(rowToWorkspaceLocation);
  }
  async replaceWorkspaceLocations(projectId, locations) {
    await this.db.execute("DELETE FROM workspace_locations WHERE workspace_id = $1", [projectId]);
    for (const location of locations) {
      await this.db.execute(`INSERT INTO workspace_locations (
          id, workspace_id, path, machine_id, label, kind, is_primary,
          exists_at_create, metadata, created_at
        ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`, [
        location.id,
        projectId,
        location.path,
        location.machine_id,
        location.label,
        location.kind,
        location.is_primary ? 1 : 0,
        location.exists_at_create ? 1 : 0,
        json(location.metadata),
        location.created_at
      ]);
    }
  }
  async replaceProjectResourceLinksExact(projectId, links) {
    await this.db.execute("DELETE FROM project_resource_links WHERE project_id = $1", [projectId]);
    for (const link of links) {
      await this.db.execute(`INSERT INTO project_resource_links (
          id, project_id, authority, service_instance, source_package, target_kind,
          locator_kind, locator_value, scope, labels_json, created_at, updated_at
        ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)`, [
        link.id,
        projectId,
        link.authority,
        link.service_instance,
        link.source_package,
        link.target_kind,
        link.locator.kind,
        link.locator.value,
        link.scope,
        canonicalJson(link.labels),
        link.created_at,
        link.updated_at
      ]);
    }
  }
  async readProjectResourceLinks(input, startedAtMs = Date.now()) {
    assertCompleteStableProjectId(input.project_id);
    const project = await this.requireWorkspace(input.project_id);
    const links = await this.listProjectResourceLinks(input.project_id, input.max_items);
    const read = {
      ok: true,
      project_id: project.id,
      project,
      current_revision: workspaceRevision(project),
      links,
      link_count: links.length,
      max_items: input.max_items,
      collection_digest: projectResourceLinksDigest(links),
      complete: true,
      truncated: false,
      contract: projectResourceLinkCollection(project.id, workspaceRevision(project), links, input.max_items)
    };
    assertProjectResourceLinkReadContractEquality(read);
    return withResponseControl(read, input, startedAtMs, "project resource link read");
  }
  async lockProjectRelationEndpoints(projectIds) {
    for (const projectId of [...new Set(projectIds)].sort()) {
      const digest2 = sha256(`hasna.projects.project-relations:${projectId}`);
      const key = BigInt.asIntN(64, BigInt(`0x${digest2.slice(0, 16)}`));
      await this.db.query("SELECT pg_advisory_xact_lock($1)", [key]);
    }
  }
  async lockProjectRelationHierarchy() {
    await this.db.query("SELECT pg_advisory_xact_lock($1)", [PROJECT_RELATION_HIERARCHY_LOCK_KEY]);
  }
  async listProjectRelationHeads(projectId, maxItems) {
    if (!Number.isInteger(maxItems) || maxItems <= 0) {
      throw new ValidationError("project relation max_items must be a positive integer");
    }
    const rows = await this.db.many(`SELECT relation_id, version, from_project_id, to_project_id, relation,
              superseded_by, superseded_at, created_at
       FROM project_relations
       WHERE superseded_by IS NULL AND (from_project_id = $1 OR to_project_id = $1)
       ORDER BY relation, relation_id
       LIMIT $2`, [projectId, maxItems + 1]);
    if (rows.length > maxItems) {
      throw new ValidationError(`project relation collection exceeds max_items: more than ${maxItems}`);
    }
    return rows.map(rowToProjectRelation);
  }
  async projectRelationViewsFor(projectId, relations) {
    const counterpartIds = [...new Set(relations.map((relation) => relation.from_project_id === projectId ? relation.to_project_id : relation.from_project_id))].sort();
    const counterparts = new Map;
    if (counterpartIds.length > 0) {
      const placeholders = counterpartIds.map((_, index) => `$${index + 1}`).join(", ");
      const rows = await this.db.many(`SELECT id, slug, name, status FROM workspaces WHERE id IN (${placeholders})`, counterpartIds);
      for (const row of rows) {
        counterparts.set(row.id, { slug: row.slug, name: row.name, status: row.status });
      }
    }
    return projectRelationViews(relations, projectId, counterparts);
  }
  async readProjectRelations(input, startedAtMs = Date.now()) {
    try {
      assertCompleteStableProjectId(input.project_id);
      assertPositiveBounds(input);
    } catch (err) {
      throw new ValidationError(err instanceof Error ? err.message : String(err));
    }
    const project = await this.requireWorkspace(input.project_id);
    const relations = await this.projectRelationViewsFor(project.id, await this.listProjectRelationHeads(project.id, input.max_items));
    const snapshot = projectRelationSnapshot(project, relations);
    const outbound = relations.filter((relation) => relation.direction === "outbound").length;
    return withResponseControl({
      ok: true,
      project_id: project.id,
      project,
      current_revision: workspaceRevision(project),
      relations,
      outbound_count: outbound,
      inbound_count: relations.length - outbound,
      relation_count: relations.length,
      max_items: input.max_items,
      collection_digest: snapshot.collection_digest,
      complete: true,
      truncated: false
    }, input, startedAtMs, "project relation read");
  }
  async mutateProjectRelation(input) {
    return this.inTransaction("project relation mutation", (store) => store.mutateProjectRelationInCurrentTransaction(input));
  }
  async mutateProjectRelationInCurrentTransaction(input) {
    const started = Date.now();
    let toProjectId;
    let relation;
    try {
      assertCompleteStableProjectId(input.project_id);
      assertPositiveBounds(input);
      toProjectId = assertProjectRelationEndpointId(input.to_project_id, "to_project_id");
      relation = normalizeProjectRelationKind(input.relation);
      assertProjectRelationNotSelf(input.project_id, toProjectId);
      if (input.mode !== "add" && input.mode !== "supersede") {
        throw new Error(`project relation mode must be add or supersede (got '${String(input.mode)}')`);
      }
    } catch (err) {
      throw new ValidationError(err instanceof Error ? err.message : String(err));
    }
    const mode = input.mode;
    const maxItems = PROJECT_RELATION_DEFAULT_MAX_ITEMS;
    const relationId = projectRelationId(input.project_id, toProjectId);
    const reqDigest = sha256(canonicalJson({
      mode,
      relation,
      from_project_id: input.project_id,
      to_project_id: toProjectId
    }));
    const preDigest = preconditionDigest({
      project_id: input.project_id,
      expected_revision: input.expected_revision,
      ...input.expected_relation_version === undefined ? {} : { expected_relation_version: input.expected_relation_version }
    });
    const idempotencyKey = deriveGuardedIdempotencyKey({
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction: "forward",
      target_id: input.project_id,
      request_digest: reqDigest,
      precondition_digest: preDigest
    });
    await this.lockProjectRelationEndpoints([input.project_id, toProjectId]);
    if (relation !== "related_to") {
      await this.lockProjectRelationHierarchy();
    }
    const fromProject = await this.requireWorkspace(input.project_id);
    const before = projectRelationSnapshot(fromProject, await this.projectRelationViewsFor(fromProject.id, await this.listProjectRelationHeads(fromProject.id, maxItems)));
    const currentRevision = workspaceRevision(fromProject);
    const envelope = (fields) => withResponseControl({
      mode,
      idempotency_key: idempotencyKey,
      request_digest: reqDigest,
      precondition_digest: preDigest,
      project_id: input.project_id,
      expected_revision: input.expected_revision,
      current_revision: currentRevision,
      relation_id: relationId,
      ...fields
    }, input, started, "project relation mutation");
    const duplicate = await this.guardedAcceptedReceipt({
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction: "forward",
      idempotency_key: idempotencyKey,
      target_id: input.project_id
    });
    if (duplicate) {
      return envelope({
        ok: true,
        dry_run: false,
        outcome: "duplicate_of_accepted",
        before,
        after: parseProjectRelationSnapshot(duplicate.after, "accepted"),
        receipt: await this.duplicateGuardedReceipt(duplicate, fromProject, projectRelationSnapshotJson(before))
      });
    }
    const reject = async (reason) => envelope({
      ok: false,
      dry_run: false,
      outcome: "terminal_nonacceptance",
      before,
      after: null,
      receipt: await this.guardedTerminalNonacceptance({
        operation_id: input.operation_id,
        step_id: input.step_id,
        direction: "forward",
        idempotency_key: idempotencyKey,
        target_id: input.project_id,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        expected_revision: input.expected_revision,
        reason,
        before_snapshot: projectRelationSnapshotJson(before)
      })
    });
    const priorAccepted = await this.guardedAcceptedByStep({
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction: "forward",
      target_id: input.project_id
    });
    if (priorAccepted)
      return reject("changed_request_or_precondition_for_step");
    if (currentRevision !== input.expected_revision)
      return reject("stale_revision");
    let toProject;
    try {
      toProject = assertProjectRelationEndpointActive(await this.getWorkspace(toProjectId), "to_project_id", toProjectId);
      assertProjectRelationEndpointActive(fromProject, "project_id", input.project_id);
    } catch (err) {
      throw new ValidationError(err instanceof Error ? err.message : String(err));
    }
    const headRow = await this.db.get(`SELECT relation_id, version, from_project_id, to_project_id, relation,
              superseded_by, superseded_at, created_at
       FROM project_relations WHERE relation_id = $1 AND superseded_by IS NULL`, [relationId]);
    const head = headRow ? rowToProjectRelation(headRow) : null;
    if (mode === "add" && head)
      return reject("duplicate_relation_identity");
    if (mode === "supersede" && !head)
      return reject("relation_not_found");
    if (head && head.relation === relation)
      return reject("relation_unchanged");
    if (mode === "supersede") {
      if (input.expected_relation_version === undefined) {
        return reject("relation_state_precondition_required");
      }
      if (head && input.expected_relation_version !== head.version) {
        return reject("stale_relation_state");
      }
    }
    try {
      assertProjectRelationAcyclic(await this.listProjectRelationAcyclicEdges(), { from_project_id: input.project_id, to_project_id: toProjectId, relation });
    } catch (err) {
      throw new ValidationError(err instanceof Error ? err.message : String(err));
    }
    const timestamp = nowIso();
    const nextVersion = (head?.version ?? 0) + 1;
    const proposedHeads = [
      ...(await this.listProjectRelationHeads(input.project_id, maxItems)).filter((item) => item.relation_id !== relationId),
      {
        relation_id: relationId,
        version: nextVersion,
        from_project_id: input.project_id,
        to_project_id: toProjectId,
        relation,
        superseded_by: null,
        superseded_at: null,
        created_at: timestamp
      }
    ];
    const preview = projectRelationSnapshot(fromProject, await this.projectRelationViewsFor(input.project_id, proposedHeads));
    if (input.dry_run) {
      return envelope({
        ok: true,
        dry_run: true,
        outcome: "planned",
        before,
        after: preview,
        receipt: null
      });
    }
    if (timedOut(started, input.time_budget_ms)) {
      throw new ValidationError("project relation mutation time budget exceeded before write");
    }
    if (head) {
      await this.db.execute(`UPDATE project_relations SET superseded_by = $1, superseded_at = $2
         WHERE relation_id = $3 AND version = $4 AND superseded_by IS NULL`, [nextVersion, timestamp, relationId, head.version]);
    }
    await this.db.execute(`INSERT INTO project_relations (
        relation_id, version, from_project_id, to_project_id, relation,
        superseded_by, superseded_at, created_at
      ) VALUES ($1, $2, $3, $4, $5, NULL, NULL, $6)`, [relationId, nextVersion, input.project_id, toProjectId, relation, timestamp]);
    const after = projectRelationSnapshot(fromProject, await this.projectRelationViewsFor(fromProject.id, await this.listProjectRelationHeads(fromProject.id, maxItems)));
    if (after.collection_digest !== preview.collection_digest) {
      throw new ValidationError("project relation exact readback mismatch");
    }
    const receipt = await this.insertGuardedReceipt({
      receipt_id: buildReceiptId({
        operation_id: input.operation_id,
        step_id: input.step_id,
        direction: "forward",
        idempotency_key: idempotencyKey,
        outcome: "accepted",
        target_id: input.project_id
      }),
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction: "forward",
      idempotency_key: idempotencyKey,
      target_id: input.project_id,
      request_digest: reqDigest,
      precondition_digest: preDigest,
      expected_revision: input.expected_revision,
      outcome: "accepted",
      reason: null,
      result_project_id: input.project_id,
      duplicate_of_receipt_id: null,
      before: projectRelationSnapshotJson(before),
      after: projectRelationSnapshotJson(after),
      post_revision: currentRevision
    });
    await this.recordEvent({
      workspace_id: input.project_id,
      agent_id: input.agent_id,
      event_type: mode === "add" ? "project_relation_add" : "project_relation_supersede",
      source: input.source ?? "mcp",
      command: input.command,
      before: projectRelationSnapshotJson(before),
      after: projectRelationSnapshotJson(after),
      metadata: {
        receipt_id: receipt.receipt_id,
        operation_id: input.operation_id,
        step_id: input.step_id,
        idempotency_key: idempotencyKey,
        relation_id: relationId,
        relation,
        version: nextVersion,
        from_project_id: input.project_id,
        to_project_id: toProjectId,
        counterpart_slug: toProject.slug,
        collection_digest: after.collection_digest
      }
    });
    return envelope({
      ok: true,
      dry_run: false,
      outcome: "accepted",
      before,
      after,
      receipt
    });
  }
  async listProjectRelationAcyclicEdges() {
    const rows = await this.db.many(`SELECT from_project_id, to_project_id, relation FROM project_relations
       WHERE superseded_by IS NULL AND relation IN ('parent_of', 'depends_on')`);
    return rows.map((row) => ({
      from_project_id: row.from_project_id,
      to_project_id: row.to_project_id,
      relation: normalizeProjectRelationKind(row.relation)
    }));
  }
  async readDuplicateProjectQuarantinePreimage(input, startedAtMs = Date.now()) {
    try {
      assertCompleteStableProjectId(input.project_id);
      assertPositiveBounds(input);
    } catch (err) {
      throw new ValidationError(err instanceof Error ? err.message : String(err));
    }
    const project = await this.requireWorkspace(input.project_id);
    const links = await this.listProjectResourceLinks(input.project_id, input.resource_link_max_items);
    const locations = await this.listWorkspaceLocationsBounded(input.project_id, input.workspace_location_max_items);
    const snapshot = projectQuarantineSnapshot(project, links, locations);
    return withResponseControl({
      ok: true,
      project_id: project.id,
      current_revision: project.updated_at,
      snapshot,
      resource_link_count: links.length,
      workspace_location_count: locations.length,
      complete: true,
      truncated: false
    }, input, startedAtMs, "project quarantine preimage read");
  }
  async requireWorkspace(idOrSlug) {
    const ws = await this.getWorkspace(idOrSlug);
    if (!ws)
      throw new NotFoundError(`Workspace not found: ${idOrSlug}`);
    return ws;
  }
  async createWorkspace(input) {
    if (!input.name?.trim())
      throw new ValidationError("workspace name is required");
    const id = input.id ?? generateWorkspaceId2();
    const ts = nowIso();
    const requestedSlug = input.slug ?? slugify(input.name);
    const slugBase = input.require_exact_identity ? slugify(requestedSlug) : requestedSlug;
    const slug = input.require_exact_identity ? slugBase : await this.ensureUniqueSlug("workspaces", slugBase);
    const root = input.root_id ? await this.getRoot(input.root_id) : null;
    if (input.root_id && !root)
      throw new ValidationError(`Root not found: ${input.root_id}`);
    const recipe = input.recipe_id ? await this.getRecipe(input.recipe_id) : null;
    if (input.recipe_id && !recipe)
      throw new ValidationError(`Recipe not found: ${input.recipe_id}`);
    const kind = input.kind ?? recipe?.kind ?? root?.default_kind ?? "generic";
    const tags = normalizeList([...root?.tags ?? [], ...recipe?.default_tags ?? [], ...input.tags ?? []]);
    const metadata = normalizeProjectMetadata(input.metadata);
    const derived = deriveWorkspaceRegistryFields(input, { root, slug, id, kind });
    this.assertChannelIntegrationWritable(input.integrations, undefined);
    try {
      await this.db.execute(`INSERT INTO workspaces (
          id, slug, name, description, kind, status, root_id, recipe_id, primary_path,
          git_remote, s3_bucket, s3_prefix, tags, integrations, metadata, created_at, updated_at
        ) VALUES ($1,$2,$3,$4,$5,'active',$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16)`, [
        id,
        slug,
        input.name,
        input.description ?? null,
        kind,
        root?.id ?? null,
        recipe?.id ?? null,
        derived.primary_path,
        input.git_remote ?? null,
        input.s3_bucket ?? null,
        input.s3_prefix ?? null,
        json(tags),
        json(derived.integrations),
        json(metadata),
        ts,
        ts
      ]);
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      if (/duplicate key|unique/i.test(msg))
        throw new ValidationError(`workspace conflict: ${msg}`);
      throw err;
    }
    const workspace = await this.getWorkspace(id);
    await this.recordEvent({
      workspace_id: id,
      agent_id: input.agent_id,
      event_type: "created",
      source: input.source ?? "mcp",
      prompt: input.prompt,
      command: input.command,
      after: workspace,
      metadata: { root_slug: root?.slug, recipe_slug: recipe?.slug }
    });
    return workspace;
  }
  assertChannelIntegrationWritable(next, previous) {
    try {
      assertProjectChannelIntegrationWritable(next, previous);
    } catch (error) {
      throw new ValidationError(error instanceof Error ? error.message : String(error));
    }
  }
  async updateWorkspace(idOrSlug, input) {
    const before = await this.requireWorkspace(idOrSlug);
    if (input.integrations !== undefined) {
      assertHostedProjectResourceLinkIntegrationMutation(before.integrations, input.integrations, await this.listProjectResourceLinks(before.id, PROJECT_RESOURCE_LINK_DEFAULT_MAX_ITEMS));
      this.assertChannelIntegrationWritable(input.integrations, before.integrations);
    }
    const root = input.root_id ? await this.getRoot(input.root_id) : null;
    if (input.root_id && !root)
      throw new ValidationError(`Root not found: ${input.root_id}`);
    const recipe = input.recipe_id ? await this.getRecipe(input.recipe_id) : null;
    if (input.recipe_id && !recipe)
      throw new ValidationError(`Recipe not found: ${input.recipe_id}`);
    const inputMetadataMachine = input.metadata === undefined ? undefined : canonicalMachineFromMetadata(input.metadata);
    const existingMetadataMachine = canonicalMachineFromMetadata(before.metadata);
    let canonicalMachine = input.canonical_machine;
    if (canonicalMachine === undefined && inputMetadataMachine !== undefined) {
      canonicalMachine = inputMetadataMachine;
    } else if (canonicalMachine === undefined && before.canonical_machine === null && existingMetadataMachine !== undefined) {
      canonicalMachine = existingMetadataMachine;
    }
    if (typeof canonicalMachine === "string") {
      canonicalMachine = canonicalMachine.trim();
      if (!canonicalMachine)
        throw new ValidationError("Canonical machine must not be empty");
      const machine = await this.db.get("SELECT slug FROM machines WHERE slug = $1", [canonicalMachine]);
      if (!machine)
        throw new ValidationError(`Machine not found: ${canonicalMachine}`);
    }
    let metadata = input.metadata;
    if (metadata !== undefined && inputMetadataMachine !== undefined) {
      metadata = withoutCanonicalMachineMetadata(metadata);
    } else if (metadata === undefined && existingMetadataMachine !== undefined) {
      metadata = withoutCanonicalMachineMetadata(before.metadata);
    }
    if (metadata !== undefined) {
      metadata = normalizeProjectMetadata(metadata, before.metadata);
    }
    const updates = [];
    const params = [];
    const set = (col, val) => {
      params.push(val);
      updates.push(`${col} = $${params.length}`);
    };
    if (input.name !== undefined)
      set("name", input.name);
    if (input.slug !== undefined)
      set("slug", await this.ensureUniqueSlug("workspaces", slugify(input.slug), before.id));
    if (input.description !== undefined)
      set("description", input.description);
    if (input.kind !== undefined)
      set("kind", input.kind);
    if (input.status !== undefined)
      set("status", input.status);
    if (input.root_id !== undefined)
      set("root_id", input.root_id ? root.id : null);
    if (input.recipe_id !== undefined)
      set("recipe_id", input.recipe_id ? recipe.id : null);
    if (canonicalMachine !== undefined)
      set("canonical_machine", canonicalMachine);
    if (input.primary_path !== undefined)
      set("primary_path", input.primary_path ?? null);
    if (input.git_remote !== undefined)
      set("git_remote", input.git_remote);
    if (input.s3_bucket !== undefined)
      set("s3_bucket", input.s3_bucket);
    if (input.s3_prefix !== undefined)
      set("s3_prefix", input.s3_prefix);
    if (input.tags !== undefined)
      set("tags", json(normalizeList(input.tags)));
    if (input.integrations !== undefined)
      set("integrations", json(input.integrations));
    if (metadata !== undefined)
      set("metadata", json(metadata));
    if (input.last_opened_at !== undefined)
      set("last_opened_at", input.last_opened_at);
    if (updates.length > 0) {
      set("updated_at", nowIso());
      params.push(before.id);
      await this.db.execute(`UPDATE workspaces SET ${updates.join(", ")} WHERE id = $${params.length}`, params);
    }
    const after = await this.getWorkspace(before.id);
    await this.recordEvent({
      workspace_id: before.id,
      agent_id: input.agent_id,
      event_type: input.status === "deleted" ? "deleted" : "updated",
      source: input.source ?? "mcp",
      prompt: input.prompt,
      command: input.command,
      before,
      after
    });
    return after;
  }
  async assertGuardedReceiptTargetExists(targetId) {
    const target = await this.db.get("SELECT id FROM workspaces WHERE id = $1", [targetId]);
    if (!target)
      throw new Error(`guarded project mutation receipt target not found: ${targetId}`);
  }
  async insertGuardedReceipt(input) {
    const inserted = await this.db.query(`INSERT INTO guarded_project_mutation_receipts (
        receipt_id, operation_id, step_id, direction, idempotency_key, target_id,
        request_digest, precondition_digest, expected_revision, outcome, reason,
        result_project_id, duplicate_of_receipt_id, before_json, after_json, post_revision
      ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16)
      ON CONFLICT (receipt_id) DO NOTHING
      RETURNING receipt_id`, [
      input.receipt_id,
      input.operation_id,
      input.step_id,
      input.direction,
      input.idempotency_key,
      input.target_id,
      input.request_digest,
      input.precondition_digest,
      input.expected_revision,
      input.outcome,
      input.reason,
      input.result_project_id,
      input.duplicate_of_receipt_id,
      input.before === null ? null : json(input.before),
      input.after === null ? null : json(input.after),
      input.post_revision
    ]);
    const row = await this.db.get("SELECT * FROM guarded_project_mutation_receipts WHERE receipt_id = $1", [input.receipt_id]);
    if (!row)
      throw new Error(`guarded project mutation receipt readback failed: ${input.receipt_id}`);
    if (inserted.rows.length === 0)
      await this.assertGuardedReceiptTargetExists(input.target_id);
    return rowToGuardedReceipt(row);
  }
  async guardedAcceptedReceipt(input) {
    const row = await this.db.get(`SELECT * FROM guarded_project_mutation_receipts
       WHERE operation_id = $1 AND step_id = $2 AND direction = $3 AND idempotency_key = $4
         AND target_id = $5 AND outcome = 'accepted'
       ORDER BY created_at ASC, receipt_id ASC`, [input.operation_id, input.step_id, input.direction, input.idempotency_key, input.target_id]);
    return row ? rowToGuardedReceipt(row) : null;
  }
  async guardedAcceptedByStep(input) {
    const row = await this.db.get(`SELECT * FROM guarded_project_mutation_receipts
       WHERE operation_id = $1 AND step_id = $2 AND direction = $3 AND target_id = $4
         AND outcome = 'accepted'
       ORDER BY created_at ASC, receipt_id ASC`, [input.operation_id, input.step_id, input.direction, input.target_id]);
    return row ? rowToGuardedReceipt(row) : null;
  }
  async requireForwardProjectResourceLinkReceipt(receiptId, projectId) {
    const row = await this.db.get("SELECT * FROM guarded_project_mutation_receipts WHERE receipt_id = $1", [receiptId]);
    if (!row)
      throw new NotFoundError(`accepted receipt not found: ${receiptId}`);
    const accepted = rowToGuardedReceipt(row);
    if (accepted.outcome !== "accepted" || accepted.direction !== "forward" || accepted.target_id !== projectId) {
      throw new ValidationError("resource link rollback requires a forward accepted receipt for the same project id");
    }
    if (!accepted.post_revision) {
      throw new ValidationError("resource link rollback accepted receipt has no post_revision");
    }
    return accepted;
  }
  async guardedTerminalNonacceptance(input) {
    return this.insertGuardedReceipt({
      receipt_id: buildReceiptId({ ...input, outcome: "terminal_nonacceptance", suffix: input.reason }),
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction: input.direction,
      idempotency_key: input.idempotency_key,
      target_id: input.target_id,
      request_digest: input.request_digest,
      precondition_digest: input.precondition_digest,
      expected_revision: input.expected_revision,
      outcome: "terminal_nonacceptance",
      reason: input.reason,
      result_project_id: null,
      duplicate_of_receipt_id: null,
      before: input.before_snapshot ?? (input.before ? workspaceSnapshot(input.before) : null),
      after: null,
      post_revision: null
    });
  }
  async duplicateGuardedReceipt(accepted, before, beforeSnapshot) {
    const receiptId = buildReceiptId({
      operation_id: accepted.operation_id,
      step_id: accepted.step_id,
      direction: accepted.direction,
      idempotency_key: accepted.idempotency_key,
      outcome: "duplicate_of_accepted",
      target_id: accepted.target_id,
      suffix: accepted.receipt_id
    });
    const existing = await this.db.get("SELECT * FROM guarded_project_mutation_receipts WHERE receipt_id = $1", [receiptId]);
    if (existing)
      return rowToGuardedReceipt(existing);
    return this.insertGuardedReceipt({
      receipt_id: receiptId,
      operation_id: accepted.operation_id,
      step_id: accepted.step_id,
      direction: accepted.direction,
      idempotency_key: accepted.idempotency_key,
      target_id: accepted.target_id,
      request_digest: accepted.request_digest,
      precondition_digest: accepted.precondition_digest,
      expected_revision: accepted.expected_revision,
      outcome: "duplicate_of_accepted",
      reason: null,
      result_project_id: accepted.result_project_id,
      duplicate_of_receipt_id: accepted.receipt_id,
      before: beforeSnapshot ?? workspaceSnapshot(before),
      after: accepted.after,
      post_revision: accepted.post_revision
    });
  }
  async guardedConditionalUpdate(id, patch, expectedRevision, options = {}) {
    const before = await this.requireWorkspace(id);
    if (patch.integrations !== undefined) {
      this.assertChannelIntegrationWritable(patch.integrations, before.integrations);
    }
    const root = patch.root_id ? await this.getRoot(patch.root_id) : null;
    if (patch.root_id && !root)
      throw new ValidationError(`Root not found: ${patch.root_id}`);
    const recipe = patch.recipe_id ? await this.getRecipe(patch.recipe_id) : null;
    if (patch.recipe_id && !recipe)
      throw new ValidationError(`Recipe not found: ${patch.recipe_id}`);
    const metadata = patch.metadata === undefined ? undefined : normalizeProjectMetadata(patch.metadata, before.metadata);
    const updates = [];
    const params = [];
    const set = (col, val) => {
      params.push(val);
      updates.push(`${col} = $${params.length}`);
    };
    if (patch.name !== undefined)
      set("name", patch.name);
    if (patch.slug !== undefined) {
      set("slug", options.preserveExactSlug ? patch.slug : await this.ensureUniqueSlug("workspaces", slugify(patch.slug), before.id));
    }
    if (patch.description !== undefined)
      set("description", patch.description);
    if (patch.kind !== undefined)
      set("kind", patch.kind);
    if (patch.status !== undefined)
      set("status", patch.status);
    if (patch.root_id !== undefined)
      set("root_id", patch.root_id ? root.id : null);
    if (patch.recipe_id !== undefined)
      set("recipe_id", patch.recipe_id ? recipe.id : null);
    if (patch.canonical_machine !== undefined)
      set("canonical_machine", patch.canonical_machine);
    if (patch.primary_path !== undefined)
      set("primary_path", patch.primary_path ?? null);
    if (patch.git_remote !== undefined)
      set("git_remote", patch.git_remote);
    if (patch.s3_bucket !== undefined)
      set("s3_bucket", patch.s3_bucket);
    if (patch.s3_prefix !== undefined)
      set("s3_prefix", patch.s3_prefix);
    if (patch.tags !== undefined)
      set("tags", json(normalizeList(patch.tags)));
    if (patch.integrations !== undefined)
      set("integrations", json(patch.integrations));
    if (metadata !== undefined)
      set("metadata", json(metadata));
    if (patch.last_opened_at !== undefined)
      set("last_opened_at", patch.last_opened_at);
    if (!updates.length)
      return before;
    set("updated_at", nowIso());
    params.push(id);
    const idIdx = params.length;
    params.push(expectedRevision);
    const revIdx = params.length;
    const row = await this.db.get(`UPDATE workspaces SET ${updates.join(", ")}
       WHERE id = $${idIdx} AND updated_at = $${revIdx}
       RETURNING *`, params);
    return row ? rowToWorkspace(row) : null;
  }
  async mutateProjectResourceLinks(input) {
    return this.inTransaction("project resource link mutation", (store) => store.mutateProjectResourceLinksInCurrentTransaction(input, {
      forced_integrations: input.integrations
    }));
  }
  async mutateProjectResourceLinksInCurrentTransaction(input, options = {}) {
    const started = Date.now();
    try {
      assertCompleteStableProjectId(input.project_id);
      assertPositiveBounds(input);
    } catch (err) {
      throw new ValidationError(err instanceof Error ? err.message : String(err));
    }
    const maxItems = input.max_items ?? PROJECT_RESOURCE_LINK_DEFAULT_MAX_ITEMS;
    if (!Number.isInteger(maxItems) || maxItems <= 0) {
      throw new ValidationError("project resource link max_items must be a positive integer");
    }
    let normalized;
    let forcedIntegrations;
    const direction = options.direction ?? "forward";
    try {
      normalized = normalizeProjectResourceLinks(input.links);
      if (direction === "forward")
        assertProjectResourceLinksWritable(normalized);
      forcedIntegrations = normalizeProjectResourceLinkIntegrations(options.forced_integrations ?? input.integrations);
    } catch (err) {
      throw new ValidationError(err instanceof Error ? err.message : String(err));
    }
    if (normalized.length > maxItems) {
      throw new ValidationError(`project resource link request exceeds max_items: ${normalized.length} > ${maxItems}`);
    }
    const reqDigest = sha256(canonicalJson({
      mode: input.mode,
      links: normalized,
      integrations: forcedIntegrations ?? null
    }));
    const preDigest = preconditionDigest({ project_id: input.project_id, expected_revision: input.expected_revision });
    const idempotencyKey = deriveGuardedIdempotencyKey({
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction,
      target_id: input.project_id,
      request_digest: reqDigest,
      precondition_digest: preDigest
    });
    const beforeProject = await this.requireWorkspace(input.project_id);
    const beforeLinks = await this.listProjectResourceLinks(input.project_id, maxItems);
    const before = projectResourceLinkSnapshot(beforeProject, beforeLinks);
    const currentRevision = workspaceRevision(beforeProject);
    const duplicate = await this.guardedAcceptedReceipt({
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction,
      idempotency_key: idempotencyKey,
      target_id: input.project_id
    });
    if (duplicate) {
      const receipt2 = await this.duplicateGuardedReceipt(duplicate, beforeProject, resourceLinkSnapshotJson(before));
      return withResponseControl({
        ok: true,
        dry_run: false,
        outcome: "duplicate_of_accepted",
        mode: input.mode,
        idempotency_key: idempotencyKey,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        project_id: input.project_id,
        expected_revision: input.expected_revision,
        current_revision: currentRevision,
        before,
        after: parseResourceLinkSnapshot(duplicate.after, "accepted"),
        receipt: receipt2
      }, input, started, "project resource link mutation");
    }
    const priorAccepted = await this.guardedAcceptedByStep({
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction,
      target_id: input.project_id
    });
    if (priorAccepted) {
      const receipt2 = await this.guardedTerminalNonacceptance({
        operation_id: input.operation_id,
        step_id: input.step_id,
        direction,
        idempotency_key: idempotencyKey,
        target_id: input.project_id,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        expected_revision: input.expected_revision,
        reason: "changed_request_or_precondition_for_step",
        before_snapshot: resourceLinkSnapshotJson(before)
      });
      return withResponseControl({
        ok: false,
        dry_run: false,
        outcome: "terminal_nonacceptance",
        mode: input.mode,
        idempotency_key: idempotencyKey,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        project_id: input.project_id,
        expected_revision: input.expected_revision,
        current_revision: currentRevision,
        before,
        after: null,
        receipt: receipt2
      }, input, started, "project resource link mutation");
    }
    if (currentRevision !== input.expected_revision) {
      const receipt2 = await this.guardedTerminalNonacceptance({
        operation_id: input.operation_id,
        step_id: input.step_id,
        direction,
        idempotency_key: idempotencyKey,
        target_id: input.project_id,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        expected_revision: input.expected_revision,
        reason: "stale_revision",
        before_snapshot: resourceLinkSnapshotJson(before)
      });
      return withResponseControl({
        ok: false,
        dry_run: false,
        outcome: "terminal_nonacceptance",
        mode: input.mode,
        idempotency_key: idempotencyKey,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        project_id: input.project_id,
        expected_revision: input.expected_revision,
        current_revision: currentRevision,
        before,
        after: null,
        receipt: receipt2
      }, input, started, "project resource link mutation");
    }
    const beforeById = new Map(beforeLinks.map((link) => [link.id, link]));
    const preserveById = new Map((options.preserve_links ?? []).map((link) => [link.id, link]));
    const requested = normalized.map((link) => {
      const id = projectResourceLinkId(input.project_id, link);
      const existing = beforeById.get(id);
      const restored = preserveById.get(id);
      const labels = link.labels ?? {};
      return {
        id,
        project_id: input.project_id,
        ...link,
        labels,
        created_at: restored?.created_at ?? existing?.created_at ?? nowIso(),
        updated_at: restored?.updated_at ?? (existing && existing.scope === link.scope && canonicalJson(existing.labels) === canonicalJson(labels) ? existing.updated_at : nowIso())
      };
    });
    const desired = (input.mode === "add" ? [...beforeLinks, ...requested.filter((link) => !beforeById.has(link.id))] : requested).sort((a, b) => canonicalJson({
      authority: a.authority,
      service_instance: a.service_instance,
      source_package: a.source_package,
      target_kind: a.target_kind,
      locator_kind: a.locator.kind,
      locator_value: a.locator.value
    }).localeCompare(canonicalJson({
      authority: b.authority,
      service_instance: b.service_instance,
      source_package: b.source_package,
      target_kind: b.target_kind,
      locator_kind: b.locator.kind,
      locator_value: b.locator.value
    })));
    if (desired.length > maxItems) {
      throw new ValidationError(`project resource link collection exceeds max_items: ${desired.length} > ${maxItems}`);
    }
    const integrations = forcedIntegrations ?? projectResourceLinkIntegrationProjection(beforeProject.integrations, beforeLinks, desired);
    this.assertChannelIntegrationWritable(integrations, beforeProject.integrations);
    const preview = projectResourceLinkSnapshot({ ...beforeProject, integrations }, desired);
    if (input.dry_run) {
      return withResponseControl({
        ok: true,
        dry_run: true,
        outcome: "planned",
        mode: input.mode,
        idempotency_key: idempotencyKey,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        project_id: input.project_id,
        expected_revision: input.expected_revision,
        current_revision: currentRevision,
        before,
        after: preview,
        receipt: null
      }, input, started, "project resource link mutation");
    }
    if (timedOut(started, input.time_budget_ms)) {
      throw new ValidationError("project resource link mutation time budget exceeded before write");
    }
    const changed = canonicalJson(beforeLinks) !== canonicalJson(desired) || canonicalJson(beforeProject.integrations) !== canonicalJson(integrations);
    let afterProject = beforeProject;
    if (changed) {
      const desiredIds = new Set(desired.map((link) => link.id));
      for (const existing of beforeLinks) {
        if (!desiredIds.has(existing.id)) {
          await this.db.execute("DELETE FROM project_resource_links WHERE id = $1", [existing.id]);
        }
      }
      for (const link of desired) {
        const existing = beforeLinks.find((candidate) => candidate.id === link.id);
        if (existing) {
          if (existing.scope !== link.scope || canonicalJson(existing.labels) !== canonicalJson(link.labels)) {
            await this.db.execute(`UPDATE project_resource_links
               SET scope = $1, labels_json = $2, updated_at = $3
               WHERE id = $4`, [link.scope, canonicalJson(link.labels), link.updated_at, link.id]);
          }
        } else {
          await this.db.execute(`INSERT INTO project_resource_links (
              id, project_id, authority, service_instance, source_package, target_kind,
              locator_kind, locator_value, scope, labels_json, created_at, updated_at
            ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)`, [
            link.id,
            link.project_id,
            link.authority,
            link.service_instance,
            link.source_package,
            link.target_kind,
            link.locator.kind,
            link.locator.value,
            link.scope,
            canonicalJson(link.labels),
            link.created_at,
            link.updated_at
          ]);
        }
      }
      const nextRevision = nextResourceLinkRevision(currentRevision);
      const row = await this.db.get(`UPDATE workspaces SET integrations = $1, updated_at = $2
         WHERE id = $3 AND updated_at = $4
         RETURNING *`, [canonicalJson(integrations), nextRevision, input.project_id, currentRevision]);
      if (!row)
        throw new ValidationError("project resource link conditional update lost");
      afterProject = rowToWorkspace(row);
    }
    const afterLinks = await this.listProjectResourceLinks(input.project_id, maxItems);
    const after = projectResourceLinkSnapshot(afterProject, afterLinks);
    if (after.collection_digest !== projectResourceLinksDigest(desired)) {
      throw new ValidationError("project resource link exact readback mismatch");
    }
    const receipt = await this.insertGuardedReceipt({
      receipt_id: buildReceiptId({
        operation_id: input.operation_id,
        step_id: input.step_id,
        direction,
        idempotency_key: idempotencyKey,
        outcome: "accepted",
        target_id: input.project_id
      }),
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction,
      idempotency_key: idempotencyKey,
      target_id: input.project_id,
      request_digest: reqDigest,
      precondition_digest: preDigest,
      expected_revision: input.expected_revision,
      outcome: "accepted",
      reason: null,
      result_project_id: afterProject.id,
      duplicate_of_receipt_id: null,
      before: resourceLinkSnapshotJson(before),
      after: resourceLinkSnapshotJson(after),
      post_revision: workspaceRevision(afterProject)
    });
    await this.recordEvent({
      workspace_id: afterProject.id,
      agent_id: input.agent_id,
      event_type: direction === "inverse" ? "project_resource_links_rollback" : `project_resource_links_${input.mode}`,
      source: input.source ?? "mcp",
      command: input.command,
      before: resourceLinkSnapshotJson(before),
      after: resourceLinkSnapshotJson(after),
      metadata: {
        receipt_id: receipt.receipt_id,
        operation_id: input.operation_id,
        step_id: input.step_id,
        idempotency_key: idempotencyKey,
        collection_digest: after.collection_digest
      }
    });
    return withResponseControl({
      ok: true,
      dry_run: false,
      outcome: "accepted",
      mode: input.mode,
      idempotency_key: idempotencyKey,
      request_digest: reqDigest,
      precondition_digest: preDigest,
      project_id: input.project_id,
      expected_revision: input.expected_revision,
      current_revision: currentRevision,
      before,
      after,
      receipt
    }, input, started, "project resource link mutation");
  }
  async rollbackProjectResourceLinks(input) {
    return this.inTransaction("project resource link rollback", async (store) => {
      assertCompleteStableProjectId(input.project_id);
      const accepted = await store.requireForwardProjectResourceLinkReceipt(input.accepted_receipt_id, input.project_id);
      if (accepted.post_revision !== input.expected_current_revision) {
        throw new ValidationError("resource link rollback expected_current_revision must equal the accepted receipt post_revision");
      }
      const before = parseResourceLinkSnapshot(accepted.before, "accepted before");
      const after = parseResourceLinkSnapshot(accepted.after, "accepted after");
      const current = await store.readProjectResourceLinks({
        project_id: input.project_id,
        max_items: input.max_items ?? PROJECT_RESOURCE_LINK_DEFAULT_MAX_ITEMS,
        response_byte_limit: input.response_byte_limit,
        time_budget_ms: input.time_budget_ms
      });
      const priorInverse = await store.guardedAcceptedByStep({
        operation_id: input.operation_id,
        step_id: input.step_id,
        direction: "inverse",
        target_id: input.project_id
      });
      if (priorInverse) {
        const inverseBefore = parseResourceLinkSnapshot(priorInverse.before, "accepted inverse before");
        const inverseAfter = parseResourceLinkSnapshot(priorInverse.after, "accepted inverse after");
        if (priorInverse.expected_revision !== input.expected_current_revision || inverseBefore.collection_digest !== after.collection_digest || canonicalJson(inverseBefore.project.integrations) !== canonicalJson(after.project.integrations) || inverseAfter.collection_digest !== before.collection_digest || canonicalJson(inverseAfter.project.integrations) !== canonicalJson(before.project.integrations)) {
          throw new ValidationError("accepted resource link inverse receipt does not match the forward receipt");
        }
        if (!priorInverse.post_revision || current.current_revision !== priorInverse.post_revision || current.collection_digest !== inverseAfter.collection_digest || canonicalJson(current.project.integrations) !== canonicalJson(inverseAfter.project.integrations)) {
          throw new ValidationError("resource link rollback retry refuses drift after the accepted inverse");
        }
      } else if (current.current_revision !== input.expected_current_revision || current.collection_digest !== after.collection_digest) {
        throw new ValidationError("resource link rollback refuses current revision or collection digest drift");
      }
      return store.mutateProjectResourceLinksInCurrentTransaction({
        project_id: input.project_id,
        operation_id: input.operation_id,
        step_id: input.step_id,
        mode: "reconcile",
        expected_revision: input.expected_current_revision,
        links: before.links.map(resourceLinkInputFromStored),
        max_items: input.max_items,
        response_byte_limit: input.response_byte_limit,
        time_budget_ms: input.time_budget_ms,
        agent_id: input.agent_id,
        source: input.source,
        command: input.command
      }, {
        direction: "inverse",
        forced_integrations: before.project.integrations,
        preserve_links: before.links
      });
    });
  }
  async quarantineDuplicateProject(input) {
    return this.inTransaction("duplicate project quarantine", (store) => store.quarantineDuplicateProjectInCurrentTransaction(input));
  }
  async quarantineDuplicateProjectInCurrentTransaction(input) {
    const started = Date.now();
    try {
      assertCompleteStableProjectId(input.project_id);
      assertPositiveBounds(input);
      normalizedExpectedResourceLinkIds(input);
      normalizedExpectedWorkspaceLocationIds(input);
    } catch (err) {
      throw new ValidationError(err instanceof Error ? err.message : String(err));
    }
    const reqDigest = projectQuarantineRequestDigest(input);
    const preDigest = projectQuarantinePreconditionDigest(input);
    const idempotencyKey = deriveGuardedIdempotencyKey({
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction: "forward",
      target_id: input.project_id,
      request_digest: reqDigest,
      precondition_digest: preDigest
    });
    const beforeProject = await this.requireWorkspace(input.project_id);
    const beforeLinks = await this.listProjectResourceLinks(input.project_id, input.resource_link_max_items);
    const beforeLocations = await this.listWorkspaceLocationsBounded(input.project_id, input.workspace_location_max_items);
    const before = projectQuarantineSnapshot(beforeProject, beforeLinks, beforeLocations);
    const duplicate = await this.guardedAcceptedReceipt({
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction: "forward",
      idempotency_key: idempotencyKey,
      target_id: input.project_id
    });
    if (duplicate) {
      const acceptedAfter = parseProjectQuarantineSnapshot(duplicate.after, "accepted after");
      if (beforeProject.updated_at !== duplicate.post_revision || before.project_digest !== acceptedAfter.project_digest || before.resource_link_collection_digest !== acceptedAfter.resource_link_collection_digest || before.workspace_location_collection_digest !== acceptedAfter.workspace_location_collection_digest) {
        throw new ValidationError("project quarantine retry refuses drift after the accepted receipt");
      }
      if (input.dry_run) {
        return withResponseControl({
          ok: true,
          dry_run: true,
          outcome: "duplicate_of_accepted",
          idempotency_key: idempotencyKey,
          request_digest: reqDigest,
          precondition_digest: preDigest,
          project_id: input.project_id,
          expected_revision: input.expected_revision,
          current_revision: beforeProject.updated_at,
          before,
          after: acceptedAfter,
          receipt: null,
          rollback: {
            accepted_receipt_id: duplicate.receipt_id,
            expected_current_revision: duplicate.post_revision
          }
        }, input, started, "project quarantine");
      }
      const receipt2 = await this.duplicateGuardedReceipt(duplicate, beforeProject, projectQuarantineSnapshotJson(before));
      return withResponseControl({
        ok: true,
        dry_run: false,
        outcome: "duplicate_of_accepted",
        idempotency_key: idempotencyKey,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        project_id: input.project_id,
        expected_revision: input.expected_revision,
        current_revision: beforeProject.updated_at,
        before,
        after: acceptedAfter,
        receipt: receipt2,
        rollback: {
          accepted_receipt_id: duplicate.receipt_id,
          expected_current_revision: duplicate.post_revision
        }
      }, input, started, "project quarantine");
    }
    const priorAccepted = await this.guardedAcceptedByStep({
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction: "forward",
      target_id: input.project_id
    });
    if (priorAccepted) {
      if (input.dry_run) {
        return withResponseControl({
          ok: false,
          dry_run: true,
          outcome: "terminal_nonacceptance",
          idempotency_key: idempotencyKey,
          request_digest: reqDigest,
          precondition_digest: preDigest,
          project_id: input.project_id,
          expected_revision: input.expected_revision,
          current_revision: beforeProject.updated_at,
          before,
          after: null,
          receipt: null,
          rollback: null
        }, input, started, "project quarantine");
      }
      const receipt2 = await this.guardedTerminalNonacceptance({
        operation_id: input.operation_id,
        step_id: input.step_id,
        direction: "forward",
        idempotency_key: idempotencyKey,
        target_id: input.project_id,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        expected_revision: input.expected_revision,
        reason: "changed_request_or_precondition_for_step",
        before_snapshot: projectQuarantineSnapshotJson(before)
      });
      return withResponseControl({
        ok: false,
        dry_run: false,
        outcome: "terminal_nonacceptance",
        idempotency_key: idempotencyKey,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        project_id: input.project_id,
        expected_revision: input.expected_revision,
        current_revision: beforeProject.updated_at,
        before,
        after: null,
        receipt: receipt2,
        rollback: null
      }, input, started, "project quarantine");
    }
    let refusal;
    try {
      refusal = assertProjectQuarantinePreconditions(input, before);
    } catch (err) {
      throw new ValidationError(err instanceof Error ? err.message : String(err));
    }
    if (refusal) {
      if (input.dry_run) {
        return withResponseControl({
          ok: false,
          dry_run: true,
          outcome: "terminal_nonacceptance",
          idempotency_key: idempotencyKey,
          request_digest: reqDigest,
          precondition_digest: preDigest,
          project_id: input.project_id,
          expected_revision: input.expected_revision,
          current_revision: beforeProject.updated_at,
          before,
          after: null,
          receipt: null,
          rollback: null
        }, input, started, "project quarantine");
      }
      const receipt2 = await this.guardedTerminalNonacceptance({
        operation_id: input.operation_id,
        step_id: input.step_id,
        direction: "forward",
        idempotency_key: idempotencyKey,
        target_id: input.project_id,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        expected_revision: input.expected_revision,
        reason: refusal,
        before_snapshot: projectQuarantineSnapshotJson(before)
      });
      return withResponseControl({
        ok: false,
        dry_run: false,
        outcome: "terminal_nonacceptance",
        idempotency_key: idempotencyKey,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        project_id: input.project_id,
        expected_revision: input.expected_revision,
        current_revision: beforeProject.updated_at,
        before,
        after: null,
        receipt: receipt2,
        rollback: null
      }, input, started, "project quarantine");
    }
    const collision = await this.db.get("SELECT id FROM workspaces WHERE slug = $1 AND id <> $2", [slugify(input.quarantine_slug), input.project_id]);
    if (collision)
      throw new ValidationError("project quarantine slug is already owned by another project");
    const patch = projectQuarantinePatch(input, before);
    const previewProject = {
      ...beforeProject,
      ...patch,
      slug: slugify(input.quarantine_slug),
      metadata: normalizeProjectMetadata(patch.metadata, beforeProject.metadata)
    };
    const preview = projectQuarantineSnapshot(previewProject, [], []);
    assertProjectQuarantinePostimage(input, before, preview);
    if (input.dry_run) {
      return withResponseControl({
        ok: true,
        dry_run: true,
        outcome: "planned",
        idempotency_key: idempotencyKey,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        project_id: input.project_id,
        expected_revision: input.expected_revision,
        current_revision: beforeProject.updated_at,
        before,
        after: preview,
        receipt: null,
        rollback: null
      }, input, started, "project quarantine");
    }
    if (timedOut(started, input.time_budget_ms)) {
      throw new ValidationError("project quarantine time budget exceeded before write");
    }
    const afterProject = await this.guardedConditionalUpdate(input.project_id, {
      ...patch,
      agent_id: input.agent_id,
      source: input.source ?? "mcp",
      command: input.command
    }, input.expected_revision, { preserveExactSlug: true });
    if (!afterProject) {
      const fresh = await this.requireWorkspace(input.project_id);
      const freshLinks = await this.listProjectResourceLinks(input.project_id, input.resource_link_max_items);
      const freshLocations = await this.listWorkspaceLocationsBounded(input.project_id, input.workspace_location_max_items);
      const freshSnapshot = projectQuarantineSnapshot(fresh, freshLinks, freshLocations);
      const receipt2 = await this.guardedTerminalNonacceptance({
        operation_id: input.operation_id,
        step_id: input.step_id,
        direction: "forward",
        idempotency_key: idempotencyKey,
        target_id: input.project_id,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        expected_revision: input.expected_revision,
        reason: "stale_revision",
        before_snapshot: projectQuarantineSnapshotJson(freshSnapshot)
      });
      return withResponseControl({
        ok: false,
        dry_run: false,
        outcome: "terminal_nonacceptance",
        idempotency_key: idempotencyKey,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        project_id: input.project_id,
        expected_revision: input.expected_revision,
        current_revision: fresh.updated_at,
        before: freshSnapshot,
        after: null,
        receipt: receipt2,
        rollback: null
      }, input, started, "project quarantine");
    }
    await this.replaceProjectResourceLinksExact(input.project_id, []);
    await this.replaceWorkspaceLocations(input.project_id, []);
    const after = projectQuarantineSnapshot(afterProject, [], []);
    assertProjectQuarantinePostimage(input, before, after);
    const receipt = await this.insertGuardedReceipt({
      receipt_id: buildReceiptId({
        operation_id: input.operation_id,
        step_id: input.step_id,
        direction: "forward",
        idempotency_key: idempotencyKey,
        outcome: "accepted",
        target_id: input.project_id
      }),
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction: "forward",
      idempotency_key: idempotencyKey,
      target_id: input.project_id,
      request_digest: reqDigest,
      precondition_digest: preDigest,
      expected_revision: input.expected_revision,
      outcome: "accepted",
      reason: null,
      result_project_id: afterProject.id,
      duplicate_of_receipt_id: null,
      before: projectQuarantineSnapshotJson(before),
      after: projectQuarantineSnapshotJson(after),
      post_revision: afterProject.updated_at
    });
    await this.recordEvent({
      workspace_id: input.project_id,
      agent_id: input.agent_id,
      event_type: PROJECT_QUARANTINE_EVENT,
      source: input.source ?? "mcp",
      command: input.command,
      before: projectQuarantineSnapshotJson(before),
      after: projectQuarantineSnapshotJson(after),
      metadata: { receipt_id: receipt.receipt_id, operation_id: input.operation_id, step_id: input.step_id }
    });
    return withResponseControl({
      ok: true,
      dry_run: false,
      outcome: "accepted",
      idempotency_key: idempotencyKey,
      request_digest: reqDigest,
      precondition_digest: preDigest,
      project_id: input.project_id,
      expected_revision: input.expected_revision,
      current_revision: beforeProject.updated_at,
      before,
      after,
      receipt,
      rollback: { accepted_receipt_id: receipt.receipt_id, expected_current_revision: afterProject.updated_at }
    }, input, started, "project quarantine");
  }
  async rollbackDuplicateProjectQuarantine(input) {
    return this.inTransaction("duplicate project quarantine rollback", (store) => store.rollbackDuplicateProjectQuarantineInCurrentTransaction(input));
  }
  async rollbackDuplicateProjectQuarantineInCurrentTransaction(input) {
    const started = Date.now();
    try {
      assertCompleteStableProjectId(input.project_id);
      assertPositiveBounds(input);
    } catch (err) {
      throw new ValidationError(err instanceof Error ? err.message : String(err));
    }
    const row = await this.db.get("SELECT * FROM guarded_project_mutation_receipts WHERE receipt_id = $1", [input.accepted_receipt_id]);
    if (!row)
      throw new NotFoundError(`accepted quarantine receipt not found: ${input.accepted_receipt_id}`);
    const accepted = rowToGuardedReceipt(row);
    if (accepted.outcome !== "accepted" || accepted.direction !== "forward" || accepted.target_id !== input.project_id) {
      throw new ValidationError("quarantine rollback requires a forward accepted receipt for the same project id");
    }
    if (accepted.post_revision !== input.expected_current_revision) {
      throw new ValidationError("quarantine rollback expected_current_revision must equal the accepted receipt post_revision");
    }
    const acceptedBefore = parseProjectQuarantineSnapshot(accepted.before, "accepted before");
    const acceptedAfter = parseProjectQuarantineSnapshot(accepted.after, "accepted after");
    const reqDigest = sha256(canonicalJson({
      route: "projects.duplicate-quarantine.rollback.v1",
      accepted_receipt_id: accepted.receipt_id,
      restore_project_digest: acceptedBefore.project_digest,
      restore_resource_link_collection_digest: acceptedBefore.resource_link_collection_digest,
      restore_workspace_location_collection_digest: acceptedBefore.workspace_location_collection_digest
    }));
    const preDigest = preconditionDigest({
      project_id: input.project_id,
      expected_revision: input.expected_current_revision
    });
    const idempotencyKey = deriveGuardedIdempotencyKey({
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction: "inverse",
      target_id: input.project_id,
      request_digest: reqDigest,
      precondition_digest: preDigest
    });
    const currentProject = await this.requireWorkspace(input.project_id);
    const currentLinks = await this.listProjectResourceLinks(input.project_id, input.resource_link_max_items);
    const currentLocations = await this.listWorkspaceLocationsBounded(input.project_id, input.workspace_location_max_items);
    const current = projectQuarantineSnapshot(currentProject, currentLinks, currentLocations);
    const duplicate = await this.guardedAcceptedReceipt({
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction: "inverse",
      idempotency_key: idempotencyKey,
      target_id: input.project_id
    });
    if (duplicate) {
      const acceptedInverseAfter = parseProjectQuarantineSnapshot(duplicate.after, "accepted inverse after");
      if (currentProject.updated_at !== duplicate.post_revision || current.project_digest !== acceptedInverseAfter.project_digest || current.resource_link_collection_digest !== acceptedInverseAfter.resource_link_collection_digest || current.workspace_location_collection_digest !== acceptedInverseAfter.workspace_location_collection_digest) {
        throw new ValidationError("quarantine rollback retry refuses drift after the accepted inverse");
      }
      const receipt2 = await this.duplicateGuardedReceipt(duplicate, currentProject, projectQuarantineSnapshotJson(current));
      return withResponseControl({
        ok: true,
        dry_run: false,
        outcome: "duplicate_of_accepted",
        idempotency_key: idempotencyKey,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        project_id: input.project_id,
        expected_revision: input.expected_current_revision,
        current_revision: currentProject.updated_at,
        before: current,
        after: acceptedInverseAfter,
        receipt: receipt2,
        rollback: null
      }, input, started, "project quarantine rollback");
    }
    const priorInverse = await this.guardedAcceptedByStep({
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction: "inverse",
      target_id: input.project_id
    });
    if (priorInverse) {
      const receipt2 = await this.guardedTerminalNonacceptance({
        operation_id: input.operation_id,
        step_id: input.step_id,
        direction: "inverse",
        idempotency_key: idempotencyKey,
        target_id: input.project_id,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        expected_revision: input.expected_current_revision,
        reason: "changed_request_or_precondition_for_step",
        before_snapshot: projectQuarantineSnapshotJson(current)
      });
      return withResponseControl({
        ok: false,
        dry_run: false,
        outcome: "terminal_nonacceptance",
        idempotency_key: idempotencyKey,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        project_id: input.project_id,
        expected_revision: input.expected_current_revision,
        current_revision: currentProject.updated_at,
        before: current,
        after: null,
        receipt: receipt2,
        rollback: null
      }, input, started, "project quarantine rollback");
    }
    if (currentProject.updated_at !== input.expected_current_revision || current.project_digest !== acceptedAfter.project_digest || current.resource_link_collection_digest !== acceptedAfter.resource_link_collection_digest || current.workspace_location_collection_digest !== acceptedAfter.workspace_location_collection_digest) {
      throw new ValidationError("quarantine rollback refuses current project, resource-link, or path-selector drift");
    }
    if (timedOut(started, input.time_budget_ms)) {
      throw new ValidationError("project quarantine rollback time budget exceeded before write");
    }
    const afterProject = await this.guardedConditionalUpdate(input.project_id, {
      ...restoreProjectPatch(acceptedBefore),
      agent_id: input.agent_id,
      source: input.source ?? "mcp",
      command: input.command
    }, input.expected_current_revision, { preserveExactSlug: true });
    if (!afterProject)
      throw new ValidationError("quarantine rollback conditional update lost");
    await this.replaceProjectResourceLinksExact(input.project_id, acceptedBefore.resource_links);
    await this.replaceWorkspaceLocations(input.project_id, acceptedBefore.workspace_locations);
    const after = projectQuarantineSnapshot(afterProject, acceptedBefore.resource_links, acceptedBefore.workspace_locations);
    const normalizedAfter = {
      ...after.project,
      updated_at: acceptedBefore.project.updated_at
    };
    if (projectDigest(normalizedAfter, after.workspace_locations) !== acceptedBefore.project_digest || after.resource_link_collection_digest !== acceptedBefore.resource_link_collection_digest || after.workspace_location_collection_digest !== acceptedBefore.workspace_location_collection_digest) {
      throw new ValidationError("quarantine rollback exact inverse readback mismatch");
    }
    const receipt = await this.insertGuardedReceipt({
      receipt_id: buildReceiptId({
        operation_id: input.operation_id,
        step_id: input.step_id,
        direction: "inverse",
        idempotency_key: idempotencyKey,
        outcome: "accepted",
        target_id: input.project_id
      }),
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction: "inverse",
      idempotency_key: idempotencyKey,
      target_id: input.project_id,
      request_digest: reqDigest,
      precondition_digest: preDigest,
      expected_revision: input.expected_current_revision,
      outcome: "accepted",
      reason: null,
      result_project_id: afterProject.id,
      duplicate_of_receipt_id: null,
      before: projectQuarantineSnapshotJson(current),
      after: projectQuarantineSnapshotJson(after),
      post_revision: afterProject.updated_at
    });
    await this.recordEvent({
      workspace_id: input.project_id,
      agent_id: input.agent_id,
      event_type: PROJECT_QUARANTINE_ROLLBACK_EVENT,
      source: input.source ?? "mcp",
      command: input.command,
      before: projectQuarantineSnapshotJson(current),
      after: projectQuarantineSnapshotJson(after),
      metadata: {
        receipt_id: receipt.receipt_id,
        accepted_receipt_id: accepted.receipt_id,
        operation_id: input.operation_id,
        step_id: input.step_id
      }
    });
    return withResponseControl({
      ok: true,
      dry_run: false,
      outcome: "accepted",
      idempotency_key: idempotencyKey,
      request_digest: reqDigest,
      precondition_digest: preDigest,
      project_id: input.project_id,
      expected_revision: input.expected_current_revision,
      current_revision: currentProject.updated_at,
      before: current,
      after,
      receipt,
      rollback: null
    }, input, started, "project quarantine rollback");
  }
  async resourceLinkMigrationManifest(projectId, manifestId) {
    const row = await this.db.get(`SELECT * FROM project_resource_link_migration_manifests
       WHERE manifest_id = $1 AND project_id = $2`, [manifestId, projectId]);
    if (!row)
      throw new NotFoundError(`project resource link migration manifest not found: ${manifestId}`);
    return rowToProjectResourceLinkMigrationManifest(row);
  }
  async resourceLinkMigrationEvents(manifestId) {
    return (await this.boundedResourceLinkMigrationEvents(manifestId, PROJECT_RESOURCE_LINK_DEFAULT_MAX_ITEMS)).events;
  }
  async boundedResourceLinkMigrationEvents(manifestId, maxItems) {
    if (!Number.isInteger(maxItems) || maxItems <= 0) {
      throw new ValidationError("project resource link migration event max_items must be a positive integer");
    }
    const rows = await this.db.many(`SELECT event_id, manifest_id, transition_version, from_state, to_state,
              request_digest, precondition_digest, evidence_json, created_at
       FROM project_resource_link_migration_events
       WHERE manifest_id = $1
       ORDER BY transition_version ASC
       LIMIT $2`, [manifestId, maxItems + 1]);
    const truncated = rows.length > maxItems;
    return {
      events: rows.slice(0, maxItems).map((row) => ({
        event_id: String(row["event_id"]),
        manifest_id: String(row["manifest_id"]),
        transition_version: Number(row["transition_version"]),
        from_state: row["from_state"] === null ? null : row["from_state"],
        to_state: row["to_state"],
        request_digest: String(row["request_digest"]),
        precondition_digest: String(row["precondition_digest"]),
        evidence: parseJson2(String(row["evidence_json"]), {}),
        created_at: String(row["created_at"])
      })),
      complete: !truncated,
      truncated
    };
  }
  async insertResourceLinkMigrationEvent(event) {
    await this.db.execute(`INSERT INTO project_resource_link_migration_events (
        event_id, manifest_id, transition_version, from_state, to_state,
        request_digest, precondition_digest, evidence_json, created_at
      ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)`, [
      event.event_id,
      event.manifest_id,
      event.transition_version,
      event.from_state,
      event.to_state,
      event.request_digest,
      event.precondition_digest,
      json(event.evidence),
      event.created_at
    ]);
  }
  async persistResourceLinkMigrationTransition(before, after, evidence2) {
    const row = await this.db.get(`UPDATE project_resource_link_migration_manifests
       SET state = $1, links_json = $2, projects_forward_receipt_id = $3,
           projects_inverse_receipt_id = $4, projects_reference_proof_json = $5,
           last_verified_projects_revision = $6, last_verified_projects_digest = $7,
           transition_version = $8, updated_at = $9
       WHERE manifest_id = $10 AND project_id = $11 AND transition_version = $12
       RETURNING manifest_id`, [
      after.state,
      json(after.links),
      after.projects_forward_receipt_id,
      after.projects_inverse_receipt_id,
      after.projects_reference_proof === null ? null : json(after.projects_reference_proof),
      after.last_verified_projects_revision,
      after.last_verified_projects_digest,
      after.transition_version,
      after.updated_at,
      after.manifest_id,
      after.project_id,
      before.transition_version
    ]);
    if (!row)
      throw new ValidationError("project resource link migration transition CAS lost");
    await this.insertResourceLinkMigrationEvent(migrationEvent(after.manifest_id, after.transition_version, before.state, after.state, sha256(canonicalJson(evidence2)), sha256(canonicalJson({
      manifest_id: before.manifest_id,
      transition_version: before.transition_version,
      state: before.state
    })), evidence2, after.updated_at));
  }
  async planProjectResourceLinkMigration(input) {
    const started = Date.now();
    assertCompleteStableProjectId(input.project_id);
    const project = await this.requireWorkspace(input.project_id);
    if (workspaceRevision(project) !== input.expected_project_revision) {
      throw new ValidationError("project resource link migration plan refuses a stale project revision");
    }
    const maxItems = input.max_items ?? PROJECT_RESOURCE_LINK_DEFAULT_MAX_ITEMS;
    if (input.links.length > maxItems) {
      throw new ValidationError("project resource link migration plan exceeds max_items");
    }
    const ts = nowIso();
    const candidate = buildProjectResourceLinkMigrationPlan(input, ts);
    const existing = await this.db.get(`SELECT * FROM project_resource_link_migration_manifests
       WHERE project_id = $1 AND operation_id = $2 AND step_id = $3`, [input.project_id, input.operation_id, input.step_id]);
    if (existing) {
      const manifest = rowToProjectResourceLinkMigrationManifest(existing);
      if (manifest.manifest_id !== candidate.manifest_id) {
        throw new ValidationError("project resource link migration step already has a different accepted manifest");
      }
      return withResponseControl({
        ok: true,
        outcome: "duplicate_of_accepted",
        manifest,
        events: await this.resourceLinkMigrationEvents(manifest.manifest_id)
      }, input, started, "project resource link migration plan");
    }
    await this.inTransaction("project resource link migration plan", async (store) => {
      await store.db.execute(`INSERT INTO project_resource_link_migration_manifests (
          manifest_id, project_id, operation_id, step_id, state,
          expected_project_revision, desired_collection_digest, links_json,
          transition_version, created_at, updated_at
        ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)`, [
        candidate.manifest_id,
        candidate.project_id,
        candidate.operation_id,
        candidate.step_id,
        candidate.state,
        candidate.expected_project_revision,
        candidate.desired_collection_digest,
        json(candidate.links),
        candidate.transition_version,
        candidate.created_at,
        candidate.updated_at
      ]);
      await store.insertResourceLinkMigrationEvent(migrationEvent(candidate.manifest_id, candidate.transition_version, null, "planned", sha256(canonicalJson(input.links)), sha256(canonicalJson({
        project_id: input.project_id,
        expected_project_revision: input.expected_project_revision
      })), { link_ids: candidate.links.map((item) => item.link_id) }, ts));
    });
    return withResponseControl({
      ok: true,
      outcome: "accepted",
      manifest: candidate,
      events: await this.resourceLinkMigrationEvents(candidate.manifest_id)
    }, input, started, "project resource link migration plan");
  }
  async readProjectResourceLinkMigration(input) {
    const started = Date.now();
    const manifest = await this.resourceLinkMigrationManifest(input.project_id, input.manifest_id);
    const boundedEvents = await this.boundedResourceLinkMigrationEvents(manifest.manifest_id, input.max_items ?? PROJECT_RESOURCE_LINK_DEFAULT_MAX_ITEMS);
    return withResponseControl({
      ok: true,
      outcome: "accepted",
      manifest,
      events: boundedEvents.events
    }, input, started, "project resource link migration read", boundedEvents);
  }
  async advanceProjectResourceLinkMigration(input) {
    const started = Date.now();
    const before = await this.resourceLinkMigrationManifest(input.project_id, input.manifest_id);
    if (before.transition_version !== input.expected_transition_version) {
      throw new ValidationError("project resource link migration advance transition_version is stale");
    }
    if (before.state === input.next_state) {
      return withResponseControl({
        ok: true,
        outcome: "duplicate_of_accepted",
        manifest: before,
        events: await this.resourceLinkMigrationEvents(before.manifest_id)
      }, input, started, "project resource link migration advance");
    }
    let producerEvidence = input.producer_evidence;
    let producerAttestation;
    if (input.next_state === "producer_applied") {
      try {
        producerEvidence = reconcileProjectResourceLinkProducerProof(before, input.producer_evidence, "forward");
      } catch (error) {
        throw new ValidationError(error instanceof Error ? error.message : String(error));
      }
    }
    if (input.next_state === "projects_applied") {
      if (!input.projects_forward_receipt_id) {
        throw new ValidationError("projects_applied requires a Projects forward receipt");
      }
      const row = await this.db.get("SELECT * FROM guarded_project_mutation_receipts WHERE receipt_id = $1", [input.projects_forward_receipt_id]);
      if (!row)
        throw new NotFoundError("Projects forward receipt not found");
      const receipt = rowToGuardedReceipt(row);
      const snapshot = parseResourceLinkSnapshot(receipt.after, "Projects forward");
      const ids = new Set(snapshot.links.map((link) => link.id));
      if (receipt.outcome !== "accepted" || receipt.direction !== "forward" || receipt.target_id !== input.project_id || snapshot.collection_digest !== before.desired_collection_digest || before.links.some((item) => !ids.has(item.link_id))) {
        throw new ValidationError("Projects forward receipt does not prove the manifest collection");
      }
    }
    if (input.next_state === "verified") {
      try {
        producerEvidence = reconcileProjectResourceLinkProducerProof(before, input.producer_evidence, "readback");
        const trustedProject = await this.getWorkspace(input.project_id);
        if (!trustedProject)
          throw new Error(`Project not found: ${input.project_id}`);
        producerAttestation = assertProjectResourceLinkProducerAttestation(before, "readback", producerEvidence, await this.producerEvidenceVerifier?.({
          manifest: before,
          trusted_project: projectResourceLinkProducerProjectSubject(trustedProject),
          phase: "readback",
          producer_evidence: producerEvidence,
          transition_evidence: input.evidence,
          response_byte_limit: input.response_byte_limit,
          time_budget_ms: input.time_budget_ms
        }));
      } catch (error) {
        throw new ValidationError(error instanceof Error ? error.message : String(error));
      }
      const read = await this.readProjectResourceLinks({
        project_id: input.project_id,
        max_items: Math.max(PROJECT_RESOURCE_LINK_DEFAULT_MAX_ITEMS, before.links.length),
        response_byte_limit: input.response_byte_limit,
        time_budget_ms: input.time_budget_ms
      });
      if (read.collection_digest !== before.desired_collection_digest || input.last_verified_projects_revision !== read.current_revision || input.last_verified_projects_digest !== read.collection_digest) {
        throw new ValidationError("verified transition requires a current complete Projects readback");
      }
    }
    const after = applyProjectResourceLinkMigrationTransition(before, input.next_state, nowIso(), {
      producer_evidence: producerEvidence,
      projects_forward_receipt_id: input.projects_forward_receipt_id,
      last_verified_projects_revision: input.last_verified_projects_revision,
      last_verified_projects_digest: input.last_verified_projects_digest
    });
    const transitionEvidence = producerAttestation ? migrationEvidenceWithProducerAttestation(input.evidence, producerAttestation) : input.evidence;
    await this.inTransaction("project resource link migration advance", (store) => store.persistResourceLinkMigrationTransition(before, after, transitionEvidence));
    return withResponseControl({
      ok: true,
      outcome: "accepted",
      manifest: after,
      events: await this.resourceLinkMigrationEvents(after.manifest_id)
    }, input, started, "project resource link migration advance");
  }
  async rollbackProjectResourceLinkMigration(input) {
    const started = Date.now();
    let before = await this.resourceLinkMigrationManifest(input.project_id, input.manifest_id);
    if (["rolled_back", "retained_target"].includes(before.state)) {
      return withResponseControl({
        ok: true,
        outcome: "duplicate_of_accepted",
        manifest: before,
        events: await this.resourceLinkMigrationEvents(before.manifest_id)
      }, input, started, "project resource link migration rollback");
    }
    if (before.transition_version !== input.expected_transition_version) {
      throw new ValidationError("project resource link migration rollback transition_version is stale");
    }
    let proof = before.projects_reference_proof;
    let inverseReceiptId = before.projects_inverse_receipt_id;
    const establishingProjectsReferenceProof = proof === null;
    if (establishingProjectsReferenceProof && input.producer_outcome !== "pending") {
      throw new ValidationError("first migration rollback call must use producer_outcome=pending so Projects reference proof is persisted before producer compensation");
    }
    const linkIds = before.links.map((item) => item.link_id);
    if (!proof) {
      if (before.projects_forward_receipt_id) {
        const forwardReceipt = await this.requireForwardProjectResourceLinkReceipt(before.projects_forward_receipt_id, input.project_id);
        const inverse = await this.rollbackProjectResourceLinks({
          project_id: input.project_id,
          operation_id: `${before.operation_id}:migration-rollback`,
          step_id: `${before.step_id}:projects-reference`,
          accepted_receipt_id: before.projects_forward_receipt_id,
          expected_current_revision: forwardReceipt.post_revision,
          max_items: input.max_items,
          response_byte_limit: input.response_byte_limit,
          time_budget_ms: input.time_budget_ms,
          agent_id: input.agent_id,
          source: input.source,
          command: input.command
        });
        const verified = await this.readProjectResourceLinks({
          project_id: input.project_id,
          max_items: input.max_items ?? PROJECT_RESOURCE_LINK_DEFAULT_MAX_ITEMS,
          response_byte_limit: input.response_byte_limit,
          time_budget_ms: input.time_budget_ms
        });
        if (verified.links.some((link) => linkIds.includes(link.id))) {
          throw new ValidationError("Projects inverse did not remove every manifest reference");
        }
        if (!["accepted", "duplicate_of_accepted"].includes(inverse.outcome)) {
          throw new ValidationError("Projects inverse was not accepted");
        }
        inverseReceiptId = inverse.receipt?.duplicate_of_receipt_id ?? inverse.receipt?.receipt_id ?? null;
        if (!inverseReceiptId)
          throw new ValidationError("Projects inverse did not return an accepted receipt");
        proof = {
          kind: "accepted_inverse",
          forward_receipt_id: before.projects_forward_receipt_id,
          inverse_receipt_id: inverseReceiptId,
          verified_revision: verified.current_revision,
          collection_digest: verified.collection_digest,
          link_ids_checked: linkIds,
          complete: true,
          truncated: false,
          request_digest: inverse.request_digest,
          precondition_digest: inverse.precondition_digest
        };
      } else {
        const current = await this.readProjectResourceLinks({
          project_id: input.project_id,
          max_items: input.max_items ?? PROJECT_RESOURCE_LINK_DEFAULT_MAX_ITEMS,
          response_byte_limit: input.response_byte_limit,
          time_budget_ms: input.time_budget_ms
        });
        if (current.links.some((link) => linkIds.includes(link.id))) {
          throw new ValidationError("ambiguous Projects state: manifest links exist without a matching accepted forward receipt");
        }
        proof = {
          kind: "no_projects_write",
          verified_revision: current.current_revision,
          collection_digest: current.collection_digest,
          link_ids_checked: linkIds,
          complete: true,
          truncated: false,
          request_digest: sha256(canonicalJson({ manifest_id: before.manifest_id, link_ids: linkIds })),
          precondition_digest: sha256(canonicalJson({
            revision: current.current_revision,
            collection_digest: current.collection_digest
          }))
        };
      }
    }
    if (before.state !== "rollback_in_progress") {
      const inProgress = applyProjectResourceLinkMigrationTransition(before, "rollback_in_progress", nowIso(), {
        projects_inverse_receipt_id: inverseReceiptId,
        projects_reference_proof: proof,
        last_verified_projects_revision: proof.verified_revision,
        last_verified_projects_digest: proof.collection_digest
      });
      await this.inTransaction("project resource link migration rollback proof", (store) => store.persistResourceLinkMigrationTransition(before, inProgress, input.evidence));
      before = inProgress;
    }
    if (input.producer_outcome === "pending") {
      return withResponseControl({
        ok: true,
        outcome: "accepted",
        manifest: before,
        events: await this.resourceLinkMigrationEvents(before.manifest_id)
      }, input, started, "project resource link migration rollback");
    }
    const nextState = input.producer_outcome === "complete" ? "rolled_back" : input.producer_outcome === "retained_target" ? "retained_target" : "failed_reconcilable";
    let terminalProducerEvidence = input.producer_evidence;
    let producerAttestation;
    if (nextState === "rolled_back" || nextState === "retained_target") {
      try {
        terminalProducerEvidence = reconcileProjectResourceLinkProducerProof(before, input.producer_evidence, "inverse", nextState === "rolled_back" ? "complete" : "retained_target");
        const phase = nextState === "rolled_back" ? "inverse_complete" : "inverse_retained_target";
        const trustedProject = await this.getWorkspace(input.project_id);
        if (!trustedProject)
          throw new Error(`Project not found: ${input.project_id}`);
        producerAttestation = assertProjectResourceLinkProducerAttestation(before, phase, terminalProducerEvidence, await this.producerEvidenceVerifier?.({
          manifest: before,
          trusted_project: projectResourceLinkProducerProjectSubject(trustedProject),
          phase,
          producer_evidence: terminalProducerEvidence,
          transition_evidence: input.evidence,
          response_byte_limit: input.response_byte_limit,
          time_budget_ms: input.time_budget_ms
        }));
      } catch (error) {
        throw new ValidationError(error instanceof Error ? error.message : String(error));
      }
    }
    const after = applyProjectResourceLinkMigrationTransition(before, nextState, nowIso(), {
      producer_evidence: terminalProducerEvidence,
      projects_inverse_receipt_id: inverseReceiptId,
      projects_reference_proof: proof,
      last_verified_projects_revision: proof.verified_revision,
      last_verified_projects_digest: proof.collection_digest
    });
    const transitionEvidence = producerAttestation ? migrationEvidenceWithProducerAttestation(input.evidence, producerAttestation) : input.evidence;
    await this.inTransaction("project resource link migration rollback", (store) => store.persistResourceLinkMigrationTransition(before, after, transitionEvidence));
    return withResponseControl({
      ok: true,
      outcome: "accepted",
      manifest: after,
      events: await this.resourceLinkMigrationEvents(after.manifest_id)
    }, input, started, "project resource link migration rollback");
  }
  async guardedUpdateWorkspace(input) {
    return this.inTransaction("guarded project metadata mutation", (store) => store.guardedUpdateWorkspaceInCurrentTransaction(input));
  }
  async guardedUpdateWorkspaceInCurrentTransaction(input) {
    const started = Date.now();
    assertCompleteStableProjectId(input.project_id);
    const direction = input.direction ?? "forward";
    const reqDigest = requestDigest(input.patch);
    const preDigest = preconditionDigest({ project_id: input.project_id, expected_revision: input.expected_revision });
    const idempotencyKey = deriveGuardedIdempotencyKey({
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction,
      target_id: input.project_id,
      request_digest: reqDigest,
      precondition_digest: preDigest
    });
    const before = await this.requireWorkspace(input.project_id);
    const normalizedPatch = input.patch.metadata === undefined ? input.patch : {
      ...input.patch,
      metadata: normalizeProjectMetadata(input.patch.metadata, before.metadata)
    };
    if (input.patch.integrations !== undefined) {
      assertHostedProjectResourceLinkIntegrationMutation(before.integrations, input.patch.integrations, await this.listProjectResourceLinks(input.project_id, PROJECT_RESOURCE_LINK_DEFAULT_MAX_ITEMS));
      this.assertChannelIntegrationWritable(input.patch.integrations, before.integrations);
    }
    const currentRevision = workspaceRevision(before);
    const duplicate = await this.guardedAcceptedReceipt({ operation_id: input.operation_id, step_id: input.step_id, direction, idempotency_key: idempotencyKey, target_id: input.project_id });
    if (duplicate) {
      const duplicateReceipt = await this.duplicateGuardedReceipt(duplicate, before);
      const result2 = {
        ok: true,
        dry_run: false,
        outcome: "duplicate_of_accepted",
        idempotency_key: idempotencyKey,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        project_id: input.project_id,
        expected_revision: input.expected_revision,
        current_revision: currentRevision,
        before,
        after: duplicate.after,
        receipt: duplicateReceipt
      };
      return withResponseControl(result2, input, started);
    }
    const priorAccepted = await this.guardedAcceptedByStep({ operation_id: input.operation_id, step_id: input.step_id, direction, target_id: input.project_id });
    if (priorAccepted) {
      const receipt2 = await this.guardedTerminalNonacceptance({ operation_id: input.operation_id, step_id: input.step_id, direction, idempotency_key: idempotencyKey, target_id: input.project_id, request_digest: reqDigest, precondition_digest: preDigest, expected_revision: input.expected_revision, reason: "changed_request_or_precondition_for_step", before });
      const result2 = { ok: false, dry_run: false, outcome: "terminal_nonacceptance", idempotency_key: idempotencyKey, request_digest: reqDigest, precondition_digest: preDigest, project_id: input.project_id, expected_revision: input.expected_revision, current_revision: currentRevision, before, after: null, receipt: receipt2 };
      return withResponseControl(result2, input, started);
    }
    if (currentRevision !== input.expected_revision) {
      const receipt2 = await this.guardedTerminalNonacceptance({ operation_id: input.operation_id, step_id: input.step_id, direction, idempotency_key: idempotencyKey, target_id: input.project_id, request_digest: reqDigest, precondition_digest: preDigest, expected_revision: input.expected_revision, reason: "stale_revision", before });
      const result2 = { ok: false, dry_run: false, outcome: "terminal_nonacceptance", idempotency_key: idempotencyKey, request_digest: reqDigest, precondition_digest: preDigest, project_id: input.project_id, expected_revision: input.expected_revision, current_revision: currentRevision, before, after: null, receipt: receipt2 };
      return withResponseControl(result2, input, started);
    }
    if (input.dry_run) {
      const after2 = { ...before, ...normalizedPatch };
      const result2 = { ok: true, dry_run: true, outcome: "planned", idempotency_key: idempotencyKey, request_digest: reqDigest, precondition_digest: preDigest, project_id: input.project_id, expected_revision: input.expected_revision, current_revision: currentRevision, before, after: after2, receipt: null };
      return withResponseControl(result2, input, started);
    }
    if (timedOut(started, input.time_budget_ms))
      throw new ValidationError("guarded mutation time budget exceeded before write");
    const after = await this.guardedConditionalUpdate(input.project_id, {
      ...normalizedPatch,
      agent_id: input.agent_id ?? input.patch.agent_id,
      source: input.source ?? input.patch.source ?? "mcp",
      command: input.command ?? input.patch.command
    }, input.expected_revision);
    if (!after) {
      const fresh = await this.requireWorkspace(input.project_id);
      const receipt2 = await this.guardedTerminalNonacceptance({ operation_id: input.operation_id, step_id: input.step_id, direction, idempotency_key: idempotencyKey, target_id: input.project_id, request_digest: reqDigest, precondition_digest: preDigest, expected_revision: input.expected_revision, reason: "stale_revision", before: fresh });
      const result2 = { ok: false, dry_run: false, outcome: "terminal_nonacceptance", idempotency_key: idempotencyKey, request_digest: reqDigest, precondition_digest: preDigest, project_id: input.project_id, expected_revision: input.expected_revision, current_revision: workspaceRevision(fresh), before: fresh, after: null, receipt: receipt2 };
      return withResponseControl(result2, input, started);
    }
    const receipt = await this.insertGuardedReceipt({
      receipt_id: buildReceiptId({ operation_id: input.operation_id, step_id: input.step_id, direction, idempotency_key: idempotencyKey, outcome: "accepted", target_id: input.project_id }),
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction,
      idempotency_key: idempotencyKey,
      target_id: input.project_id,
      request_digest: reqDigest,
      precondition_digest: preDigest,
      expected_revision: input.expected_revision,
      outcome: "accepted",
      reason: null,
      result_project_id: after.id,
      duplicate_of_receipt_id: null,
      before: workspaceSnapshot(before),
      after: workspaceSnapshot(after),
      post_revision: workspaceRevision(after)
    });
    await this.recordEvent({ workspace_id: after.id, agent_id: input.agent_id, event_type: direction === "inverse" ? "guarded_metadata_mutation_rollback" : "guarded_metadata_mutation", source: input.source ?? "mcp", command: input.command, before, after, metadata: { receipt_id: receipt.receipt_id, operation_id: input.operation_id, step_id: input.step_id, idempotency_key: idempotencyKey } });
    const result = { ok: true, dry_run: false, outcome: "accepted", idempotency_key: idempotencyKey, request_digest: reqDigest, precondition_digest: preDigest, project_id: input.project_id, expected_revision: input.expected_revision, current_revision: currentRevision, before, after, receipt };
    return withResponseControl(result, input, started);
  }
  async lookupGuardedWorkspaceMutationReceipt(input) {
    const started = Date.now();
    assertCompleteStableProjectId(input.project_id);
    if (input.max_items !== 1)
      throw new ValidationError("guarded receipt lookup max_items must be exactly 1");
    const rows = await this.db.many(`SELECT * FROM guarded_project_mutation_receipts
       WHERE operation_id = $1 AND step_id = $2 AND direction = $3 AND idempotency_key = $4 AND target_id = $5
       ORDER BY created_at ASC, receipt_id ASC
       LIMIT 2`, [input.operation_id, input.step_id, input.direction, input.idempotency_key, input.project_id]);
    if (rows.length === 0)
      throw new ValidationError("guarded receipt lookup expected exactly one terminal receipt, found 0");
    const receipts = rows.map(rowToGuardedReceipt);
    const accepted = receipts.find((receipt2) => receipt2.outcome === "accepted");
    const duplicates = receipts.filter((receipt2) => receipt2.outcome === "duplicate_of_accepted");
    if (receipts.length > 1) {
      if (!accepted || duplicates.length !== receipts.length - 1 || duplicates.some((receipt2) => receipt2.duplicate_of_receipt_id !== accepted.receipt_id)) {
        throw new ValidationError(`guarded receipt lookup expected exactly one terminal result, found ${receipts.length}`);
      }
    }
    const receipt = duplicates.at(-1) ?? accepted ?? receipts[0];
    return withResponseControl({ receipt }, input, started);
  }
  async rollbackGuardedWorkspaceMutation(input) {
    return this.inTransaction("guarded project metadata rollback", (store) => store.rollbackGuardedWorkspaceMutationInCurrentTransaction(input));
  }
  async rollbackGuardedWorkspaceMutationInCurrentTransaction(input) {
    assertCompleteStableProjectId(input.project_id);
    const row = await this.db.get("SELECT * FROM guarded_project_mutation_receipts WHERE receipt_id = $1", [input.accepted_receipt_id]);
    if (!row)
      throw new NotFoundError(`accepted receipt not found: ${input.accepted_receipt_id}`);
    const accepted = rowToGuardedReceipt(row);
    if (accepted.outcome !== "accepted" || accepted.direction !== "forward" || accepted.target_id !== input.project_id) {
      throw new ValidationError("rollback requires a forward accepted receipt for the same project id");
    }
    if (accepted.post_revision !== input.expected_current_revision) {
      throw new ValidationError("rollback expected_current_revision must equal the accepted receipt post_revision");
    }
    const before = accepted.before;
    if (!before)
      throw new ValidationError("accepted receipt has no before snapshot");
    return this.guardedUpdateWorkspaceInCurrentTransaction({
      project_id: input.project_id,
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction: "inverse",
      expected_revision: input.expected_current_revision,
      patch: {
        name: before.name,
        slug: before.slug,
        description: before.description,
        kind: before.kind,
        status: before.status,
        root_id: before.root_id,
        recipe_id: before.recipe_id,
        canonical_machine: before.canonical_machine,
        primary_path: before.primary_path,
        git_remote: before.git_remote,
        s3_bucket: before.s3_bucket,
        s3_prefix: before.s3_prefix,
        tags: before.tags,
        integrations: before.integrations,
        metadata: before.metadata,
        last_opened_at: before.last_opened_at
      },
      response_byte_limit: input.response_byte_limit,
      time_budget_ms: input.time_budget_ms,
      agent_id: input.agent_id,
      source: input.source ?? "mcp",
      command: input.command
    });
  }
  async archiveWorkspace(idOrSlug, input = {}) {
    return this.updateWorkspace(idOrSlug, { ...input, status: "archived" });
  }
  async unarchiveWorkspace(idOrSlug, input = {}) {
    return this.updateWorkspace(idOrSlug, { ...input, status: "active" });
  }
  async deleteWorkspace(idOrSlug, input = {}) {
    const before = await this.requireWorkspace(idOrSlug);
    if (!input.hard) {
      const workspace = await this.updateWorkspace(before.id, { ...input, status: "deleted" });
      return { workspace, hard: false };
    }
    await this.recordEvent({
      workspace_id: before.id,
      agent_id: input.agent_id,
      event_type: "deleted",
      source: input.source ?? "mcp",
      prompt: input.prompt,
      command: input.command,
      before,
      metadata: { hard: true }
    });
    await this.db.execute("DELETE FROM workspaces WHERE id = $1", [before.id]);
    return { workspace: before, hard: true };
  }
  async listWorkspaceEvents(workspaceId, limit = 200) {
    const rows = await this.db.many("SELECT * FROM workspace_events WHERE workspace_id = $1 ORDER BY created_at DESC LIMIT $2", [workspaceId, Math.min(Math.max(limit, 1), 1000)]);
    return rows.map(rowToEvent);
  }
  async recordEvent(input) {
    const id = generateEventId();
    const agent = input.agent_id ? await this.getAgent(input.agent_id) : null;
    if (input.agent_id && !agent) {
      throw new NotFoundError(`Agent not found: ${input.agent_id}`);
    }
    await this.db.execute(`INSERT INTO workspace_events (
        id, workspace_id, agent_id, event_type, source, prompt, command,
        before_json, after_json, metadata, created_at
      ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)`, [
      id,
      input.workspace_id ?? null,
      agent?.id ?? null,
      input.event_type,
      input.source,
      input.prompt ?? null,
      input.command ?? null,
      input.before === undefined ? null : json(input.before),
      input.after === undefined ? null : json(input.after),
      json(input.metadata ?? {}),
      nowIso()
    ]);
    const row = await this.db.get("SELECT * FROM workspace_events WHERE id = $1", [id]);
    return rowToEvent(row);
  }
  async ping() {
    const row = await this.db.get("SELECT 1 AS ok");
    return row?.ok === 1;
  }
}

// src/serve/app.ts
import {
  verifyApiKey
} from "@hasna/contracts/auth";

// src/serve/projection-openapi.ts
var ref = (name) => ({ $ref: `#/components/schemas/${name}` });
var string = { type: "string" };
var digest2 = { type: "string", pattern: "^[a-f0-9]{64}$" };
var object = (properties, required = Object.keys(properties)) => ({ type: "object", additionalProperties: false, properties, required });
var bounds2 = {
  response_byte_limit: { type: "integer", minimum: 1024, maximum: 1048576 },
  time_budget_ms: { type: "integer", minimum: 1, maximum: 30000 }
};
var pointer = object({ kind: string, id: string, name: string, uri: string, externalId: string, sourcePackage: string, tags: { type: "array", items: string } }, ["kind", "id", "tags"]);
var actor = object({ kind: string, id: string, name: string, provider: string, accountId: string, machineId: string }, ["kind", "id"]);
var evidence2 = object({ id: string, kind: string, uri: string, sha256: string, summary: string }, ["id"]);
var projectionOpenApiSchemas = {
  ProductProjectionIssue: object({
    request_id: { type: "string", format: "uuid" },
    expected_revision: { type: "string", minLength: 1, maxLength: 200 },
    project_digest: digest2,
    resource_link_collection_digest: digest2,
    resource_link_max_items: { type: "integer", minimum: 1, maximum: 1000 },
    ...bounds2
  }),
  ProductProjection: object({
    schema: { type: "string", enum: ["hasna.product_projection.v1"] },
    id: string,
    createdAt: string,
    producer: actor,
    digest: string,
    revision: { type: "integer" },
    sourceRevision: { type: "integer" },
    sourceProjectRef: pointer,
    slug: string,
    displayName: string,
    repositoryRef: pointer,
    workspaceRef: pointer,
    lifecycle: { type: "string", enum: ["draft", "active", "paused", "archived"] },
    ownerRefs: { type: "array", items: actor },
    projectedAt: string,
    sourceEvidenceRefs: { type: "array", items: evidence2 }
  }),
  ProductProjectionReceipt: object({
    schema: { type: "string", enum: ["projects.product_projection_receipt.v1"] },
    receipt_id: string,
    project_id: string,
    tenant_id: string,
    issued_revision: { type: "integer" },
    issued_at: string,
    request: ref("ProductProjectionIssue"),
    request_digest: digest2,
    subject: object({ app: string, tenant_id: string, agent: string, kid: string }),
    policy: object({ id: string, revision: { type: "integer" }, digest: digest2, authority: string }),
    source: object({
      project: ref("Workspace"),
      revision: string,
      project_digest: digest2,
      resource_links: { type: "array", items: ref("ProjectResourceLink") },
      resource_link_collection_digest: digest2
    }),
    projection: ref("ProductProjection")
  })
};
var project = { name: "id", in: "path", required: true, schema: string };
var result = (status) => ({
  [status]: { description: "Exact immutable historical receipt; no execution authority", content: { "application/json": { schema: ref("ProductProjectionReceipt") } } },
  "400": { description: "Invalid request" },
  "403": { description: "Missing policy or subject authority" },
  "409": { description: "Source/idempotency conflict" },
  "422": { description: "Bounds or unrepresentable source" }
});
var projectionOpenApiPaths = {
  "/v1/projects/{id}/product-projections": { post: {
    operationId: "issueProductProjection",
    summary: "Issue an immutable factual ProductProjection (server policy required)",
    parameters: [project],
    requestBody: { required: true, content: { "application/json": { schema: ref("ProductProjectionIssue") } } },
    responses: result("201")
  } },
  "/v1/projects/{id}/product-projections/{receiptId}": { get: {
    operationId: "readProductProjection",
    summary: "Read one authorized immutable ProductProjection receipt",
    parameters: [
      project,
      { name: "receiptId", in: "path", required: true, schema: { type: "string", pattern: "^ppr_[a-f0-9]{64}$" } },
      ...Object.entries(bounds2).map(([name, schema]) => ({ name, in: "query", required: true, schema }))
    ],
    responses: result("200")
  } }
};

// src/serve/openapi.ts
function buildOpenApiSpec(version) {
  const ID_PARAM = {
    name: "id",
    in: "path",
    required: true,
    description: "Resource id or slug",
    schema: { type: "string" }
  };
  const EXACT_PROJECT_ID_PARAM = {
    name: "id",
    in: "path",
    required: true,
    description: "Complete stable project id beginning with wks_; slugs and partial ids are refused",
    schema: { type: "string", pattern: COMPLETE_STABLE_PROJECT_ID_PATTERN }
  };
  const OPERATION_ID_PARAM = {
    name: "operation_id",
    in: "path",
    required: true,
    description: "The full-registration operation id whose immutable history is addressed",
    schema: { type: "string" }
  };
  const ref2 = (name) => ({ $ref: `#/components/schemas/${name}` });
  const jsonBody = (schemaName, required = true) => ({
    required,
    content: { "application/json": { schema: ref2(schemaName) } }
  });
  const jsonResp = (schemaName, description = "OK") => ({
    description,
    content: { "application/json": { schema: ref2(schemaName) } }
  });
  const projectResourceLinkInputBranch = (authority, sourcePackage, targetKinds, locator = ref2("ProjectResourcePortableLocator"), labels = ref2("ProjectResourceLinkLabels"), scopes = ["resource", "collection"]) => ({
    type: "object",
    additionalProperties: false,
    properties: {
      authority: { type: "string", enum: [authority] },
      service_instance: { type: "string" },
      source_package: { type: "string", enum: [sourcePackage] },
      target_kind: { type: "string", enum: targetKinds },
      locator,
      scope: { type: "string", enum: scopes },
      labels
    },
    required: ["authority", "service_instance", "source_package", "target_kind", "locator", "scope"]
  });
  const projectResourceLinkBranch = (authority, sourcePackage, targetKinds, locator = ref2("ProjectResourcePortableLocator"), labels = ref2("ProjectResourceLinkLabels"), scopes = ["resource", "collection"]) => {
    const input = projectResourceLinkInputBranch(authority, sourcePackage, targetKinds, locator, labels, scopes);
    return {
      ...input,
      properties: {
        ...input.properties,
        id: { type: "string" },
        project_id: { type: "string" },
        labels,
        created_at: { type: "string" },
        updated_at: { type: "string" }
      },
      required: [...input.required, "id", "project_id", "labels", "created_at", "updated_at"]
    };
  };
  return {
    openapi: "3.1.0",
    info: {
      title: "Projects API",
      version,
      description: "HTTP API for @hasna/projects (workspace/project management). Reads and writes go directly to PostgreSQL. All /v1 routes require an API key (x-api-key or Authorization: Bearer)."
    },
    servers: [{ url: "/" }],
    components: {
      securitySchemes: {
        apiKey: { type: "apiKey", in: "header", name: "x-api-key" }
      },
      schemas: {
        ...projectionOpenApiSchemas,
        ProjectRegistrationManifestCreate: {
          type: "object",
          properties: {
            operation_id: { type: "string" },
            request_digest: { type: "string" },
            project_id: { type: "string" },
            project_slug: { type: "string" },
            plan: { type: "object", additionalProperties: true }
          },
          required: ["operation_id", "request_digest", "project_id", "project_slug", "plan"]
        },
        ProjectRegistrationManifest: {
          type: "object",
          properties: {
            operation_id: { type: "string" },
            route: { type: "string" },
            request_digest: { type: "string" },
            project_id: { type: "string" },
            project_slug: { type: "string" },
            plan: { type: "object", additionalProperties: true },
            created_at: { type: "string" }
          },
          required: [
            "operation_id",
            "route",
            "request_digest",
            "project_id",
            "project_slug",
            "plan",
            "created_at"
          ]
        },
        ProjectRegistrationManifestResult: {
          type: "object",
          properties: {
            manifest: ref2("ProjectRegistrationManifest"),
            created: { type: "boolean" }
          },
          required: ["manifest", "created"]
        },
        ProjectRegistrationManifestRead: {
          type: "object",
          properties: {
            manifest: { anyOf: [ref2("ProjectRegistrationManifest"), { type: "null" }] }
          },
          required: ["manifest"]
        },
        ProjectRegistrationReceiptAppend: {
          type: "object",
          properties: {
            operation_id: { type: "string" },
            step_id: { type: "string" },
            authority: { type: "string" },
            resource_kind: { type: "string" },
            direction: { type: "string", enum: ["forward", "inverse"] },
            idempotency_key: { type: "string" },
            target_id: { type: "string", nullable: true },
            request_digest: { type: "string" },
            precondition_digest: { type: "string" },
            outcome: { type: "string", enum: ["accepted", "duplicate_of_accepted", "terminal_nonacceptance"] },
            reason: { type: "string", nullable: true },
            result_revision: { type: "string", nullable: true },
            result_digest: { type: "string", nullable: true },
            duplicate_of_receipt_id: { type: "string", nullable: true },
            authority_receipt: { type: "object", additionalProperties: true, nullable: true },
            artifacts: { type: "array", items: { type: "object", additionalProperties: true } },
            preconditions: { type: "array", items: { type: "object", additionalProperties: true } },
            rollback: { type: "array", items: { type: "object", additionalProperties: true } }
          },
          required: [
            "operation_id",
            "step_id",
            "authority",
            "resource_kind",
            "direction",
            "idempotency_key",
            "request_digest",
            "precondition_digest",
            "outcome"
          ]
        },
        ProjectRegistrationReceipt: {
          type: "object",
          properties: {
            receipt_id: { type: "string" },
            operation_id: { type: "string" },
            sequence: { type: "integer" },
            step_id: { type: "string" },
            authority: { type: "string" },
            resource_kind: { type: "string" },
            direction: { type: "string", enum: ["forward", "inverse"] },
            idempotency_key: { type: "string" },
            target_id: { type: "string", nullable: true },
            request_digest: { type: "string" },
            precondition_digest: { type: "string" },
            outcome: { type: "string", enum: ["accepted", "duplicate_of_accepted", "terminal_nonacceptance"] },
            reason: { type: "string", nullable: true },
            result_revision: { type: "string", nullable: true },
            result_digest: { type: "string", nullable: true },
            duplicate_of_receipt_id: { type: "string", nullable: true },
            authority_receipt: { type: "object", additionalProperties: true, nullable: true },
            artifacts: { type: "array", items: { type: "object", additionalProperties: true } },
            preconditions: { type: "array", items: { type: "object", additionalProperties: true } },
            rollback: { type: "array", items: { type: "object", additionalProperties: true } },
            created_at: { type: "string" }
          },
          required: [
            "receipt_id",
            "operation_id",
            "sequence",
            "step_id",
            "authority",
            "resource_kind",
            "direction",
            "idempotency_key",
            "target_id",
            "request_digest",
            "precondition_digest",
            "outcome",
            "reason",
            "result_revision",
            "result_digest",
            "duplicate_of_receipt_id",
            "authority_receipt",
            "artifacts",
            "preconditions",
            "rollback",
            "created_at"
          ]
        },
        ProjectRegistrationReceiptResult: {
          type: "object",
          properties: { receipt: ref2("ProjectRegistrationReceipt") },
          required: ["receipt"]
        },
        ProjectRegistrationReceiptLookup: {
          type: "object",
          properties: {
            receipt: ref2("ProjectRegistrationReceipt"),
            response_control: { type: "object", additionalProperties: true }
          },
          required: ["receipt", "response_control"]
        },
        ProjectRegistrationReceiptList: {
          type: "object",
          properties: {
            receipts: { type: "array", items: ref2("ProjectRegistrationReceipt") }
          },
          required: ["receipts"]
        },
        Root: {
          type: "object",
          properties: {
            id: { type: "string" },
            slug: { type: "string" },
            name: { type: "string" },
            base_path: { type: "string" },
            tags: { type: "array", items: { type: "string" } },
            default_kind: { type: "string", nullable: true },
            repo_visibility: { type: "string", nullable: true },
            allowed_recipes: { type: "array", items: { type: "string" } },
            allowed_agents: { type: "array", items: { type: "string" } },
            metadata: { type: "object", additionalProperties: true },
            created_at: { type: "string" },
            updated_at: { type: "string" }
          },
          required: ["id", "slug", "name", "base_path"]
        },
        CreateRoot: {
          type: "object",
          properties: {
            name: { type: "string" },
            base_path: { type: "string" },
            slug: { type: "string" },
            tags: { type: "array", items: { type: "string" } },
            default_kind: { type: "string" },
            repo_visibility: { type: "string", enum: ["public", "private"] },
            github_org: { type: "string" },
            metadata: { type: "object", additionalProperties: true }
          },
          required: ["name", "base_path"]
        },
        UpdateRoot: {
          type: "object",
          properties: {
            name: { type: "string" },
            base_path: { type: "string" },
            slug: { type: "string" },
            tags: { type: "array", items: { type: "string" } },
            default_kind: { type: "string" },
            repo_visibility: { type: "string", enum: ["public", "private"] },
            github_org: { type: "string" },
            metadata: { type: "object", additionalProperties: true }
          }
        },
        Agent: {
          type: "object",
          properties: {
            id: { type: "string" },
            slug: { type: "string" },
            name: { type: "string" },
            kind: { type: "string", enum: ["human", "ai", "service", "cli"] },
            provider: { type: "string", nullable: true },
            model: { type: "string", nullable: true },
            role: { type: "string", nullable: true },
            permissions: { type: "array", items: { type: "string" } },
            metadata: { type: "object", additionalProperties: true },
            created_at: { type: "string" },
            updated_at: { type: "string" }
          },
          required: ["id", "slug", "name", "kind"]
        },
        CreateAgent: {
          type: "object",
          properties: {
            name: { type: "string" },
            kind: { type: "string", enum: ["human", "ai", "service", "cli"] },
            slug: { type: "string" },
            provider: { type: "string" },
            model: { type: "string" },
            role: { type: "string" },
            permissions: { type: "array", items: { type: "string" } },
            metadata: { type: "object", additionalProperties: true }
          },
          required: ["name"]
        },
        Recipe: {
          type: "object",
          properties: {
            id: { type: "string" },
            slug: { type: "string" },
            name: { type: "string" },
            description: { type: "string", nullable: true },
            kind: { type: "string", nullable: true },
            version: { type: "integer" },
            steps: { type: "array", items: { type: "object", additionalProperties: true } },
            default_tags: { type: "array", items: { type: "string" } },
            metadata: { type: "object", additionalProperties: true },
            created_at: { type: "string" },
            updated_at: { type: "string" }
          },
          required: ["id", "slug", "name"]
        },
        CreateRecipe: {
          type: "object",
          properties: {
            name: { type: "string" },
            slug: { type: "string" },
            description: { type: "string" },
            kind: { type: "string" },
            version: { type: "integer" },
            steps: { type: "array", items: { type: "object", additionalProperties: true } },
            default_tags: { type: "array", items: { type: "string" } },
            metadata: { type: "object", additionalProperties: true }
          },
          required: ["name"]
        },
        Workspace: {
          type: "object",
          properties: {
            id: { type: "string" },
            slug: { type: "string" },
            name: { type: "string" },
            description: { type: "string", nullable: true },
            kind: { type: "string" },
            status: { type: "string", enum: ["active", "archived", "deleted"] },
            root_id: { type: "string", nullable: true },
            recipe_id: { type: "string", nullable: true },
            canonical_machine: { type: "string", nullable: true },
            primary_path: { type: "string", nullable: true },
            git_remote: { type: "string", nullable: true },
            s3_bucket: { type: "string", nullable: true },
            s3_prefix: { type: "string", nullable: true },
            tags: { type: "array", items: { type: "string" } },
            integrations: { type: "object", additionalProperties: { type: "string" } },
            metadata: { type: "object", additionalProperties: true },
            last_opened_at: { type: "string", nullable: true },
            created_at: { type: "string" },
            updated_at: { type: "string" },
            synced_at: { type: "string", nullable: true }
          },
          required: [
            "id",
            "slug",
            "name",
            "kind",
            "status",
            "s3_bucket",
            "s3_prefix",
            "last_opened_at",
            "synced_at"
          ]
        },
        CreateWorkspace: {
          type: "object",
          properties: {
            name: { type: "string" },
            slug: { type: "string" },
            description: { type: "string" },
            kind: { type: "string" },
            root_id: { type: "string" },
            recipe_id: { type: "string" },
            primary_path: { type: "string" },
            git_remote: { type: "string" },
            tags: { type: "array", items: { type: "string" } },
            integrations: { type: "object", additionalProperties: true },
            metadata: { type: "object", additionalProperties: true },
            agent_id: { type: "string" }
          },
          required: ["name"]
        },
        UpdateWorkspace: {
          type: "object",
          properties: {
            name: { type: "string" },
            slug: { type: "string" },
            description: { type: "string", nullable: true },
            kind: { type: "string" },
            status: { type: "string", enum: ["active", "archived", "deleted"] },
            root_id: { type: "string", nullable: true },
            recipe_id: { type: "string", nullable: true },
            canonical_machine: { type: "string", nullable: true },
            primary_path: { type: "string", nullable: true },
            git_remote: { type: "string", nullable: true },
            tags: { type: "array", items: { type: "string" } },
            integrations: { type: "object", additionalProperties: true },
            metadata: { type: "object", additionalProperties: true },
            last_opened_at: { type: "string", nullable: true },
            agent_id: { type: "string" }
          }
        },
        WorkspaceEvent: {
          type: "object",
          properties: {
            id: { type: "string" },
            workspace_id: { type: "string", nullable: true },
            agent_id: { type: "string", nullable: true },
            event_type: { type: "string" },
            source: { type: "string" },
            metadata: { type: "object", additionalProperties: true },
            created_at: { type: "string" }
          },
          required: ["id", "event_type", "source"]
        },
        WorkspaceList: {
          type: "object",
          description: "A single page of projects. `count` is the page length; `total` is how many rows match the filter. When `has_more` is true the caller must request the next page with `offset` \u2014 a full page is otherwise indistinguishable from the last one.",
          properties: {
            filter_contract: { type: "string", enum: ["projects.list.v2"], description: "Present on current producers so compact clients can fail closed against servers that ignore additive filters." },
            applied_filters: {
              type: "object",
              additionalProperties: false,
              properties: {
                query_scope: { type: "string", enum: ["legacy", "identity", "discovery", "structured", "all"] },
                tags: { type: "array", items: { type: "string" } },
                exclude_evals: { type: "boolean" },
                exclude_registry_fixtures: { type: "boolean" }
              },
              required: ["query_scope", "tags", "exclude_evals", "exclude_registry_fixtures"]
            },
            workspaces: { type: "array", items: ref2("Workspace") },
            count: { type: "integer", description: "Rows in this page." },
            total: { type: "integer", description: "Rows matching the filter, ignoring limit/offset." },
            offset: { type: "integer", description: "Offset this page starts at." },
            limit: { type: "integer", description: "Effective per-page limit after server clamping." },
            has_more: { type: "boolean", description: "More rows exist past this page." },
            complete: { type: "boolean", description: "True only when this page proves the complete matching population." }
          },
          required: ["workspaces", "count", "total", "offset", "limit", "has_more", "complete"]
        },
        GuardedResponseControl: {
          type: "object",
          properties: {
            response_byte_limit: { type: "integer", minimum: 1 },
            time_budget_ms: { type: "integer", minimum: 1 },
            response_bytes: { type: "integer", minimum: 1 },
            elapsed_ms: { type: "integer", minimum: 0 },
            complete: { type: "boolean", const: true },
            truncated: { type: "boolean", const: false }
          },
          required: [
            "response_byte_limit",
            "time_budget_ms",
            "response_bytes",
            "elapsed_ms",
            "complete",
            "truncated"
          ]
        },
        GuardedProjectRead: {
          type: "object",
          properties: {
            ok: { type: "boolean", const: true },
            project_id: { type: "string" },
            project: ref2("Workspace"),
            current_revision: { type: "string" },
            resource_links: { type: "array", items: ref2("ProjectResourceLink") },
            resource_link_count: { type: "integer", minimum: 0 },
            resource_link_max_items: { type: "integer", minimum: 1 },
            resource_link_collection_digest: { type: "string" },
            response_control: ref2("GuardedResponseControl")
          },
          required: [
            "ok",
            "project_id",
            "project",
            "current_revision",
            "resource_links",
            "resource_link_count",
            "resource_link_max_items",
            "resource_link_collection_digest",
            "response_control"
          ]
        },
        ProjectResourceLinkLabels: {
          type: "object",
          additionalProperties: false,
          properties: {
            name: { type: "string" },
            channel_name: { type: "string" },
            path: { type: "string" },
            tags: { type: "array", items: { type: "string" } }
          }
        },
        ProjectResourceConversationsChannelLabels: {
          type: "object",
          additionalProperties: false,
          properties: {
            name: { type: "string" },
            channel_name: { type: "string" },
            path: { type: "string" },
            tags: { type: "array", items: { type: "string" } }
          },
          required: ["channel_name"]
        },
        ProjectResourceExternalUuidLocator: {
          type: "object",
          additionalProperties: false,
          properties: {
            kind: { type: "string", enum: ["external_uuid"] },
            value: { type: "string", pattern: COMPLETE_EXTERNAL_UUID_PATTERN }
          },
          required: ["kind", "value"]
        },
        ProjectResourceCanonicalUriLocator: {
          type: "object",
          additionalProperties: false,
          properties: {
            kind: { type: "string", enum: ["canonical_uri"] },
            value: { type: "string" }
          },
          required: ["kind", "value"]
        },
        ProjectResourceConversationsChannelLocator: {
          type: "object",
          additionalProperties: false,
          properties: {
            kind: { type: "string", enum: ["conversations_channel_id"] },
            value: { type: "string", pattern: "^chn_[0-9a-f]{32}$" }
          },
          required: ["kind", "value"]
        },
        ProjectResourceLinkLocator: {
          oneOf: [
            ref2("ProjectResourceExternalUuidLocator"),
            ref2("ProjectResourceCanonicalUriLocator"),
            ref2("ProjectResourceConversationsChannelLocator")
          ]
        },
        ProjectResourcePortableLocator: {
          oneOf: [
            ref2("ProjectResourceExternalUuidLocator"),
            ref2("ProjectResourceCanonicalUriLocator")
          ]
        },
        ProjectResourceConversationsChannelLinkLocator: {
          oneOf: [
            ref2("ProjectResourceExternalUuidLocator"),
            ref2("ProjectResourceConversationsChannelLocator")
          ]
        },
        ProjectResourceLinkInput: {
          oneOf: [
            projectResourceLinkInputBranch("todos", "@hasna/todos", ["project", "task_list", "plan"]),
            projectResourceLinkInputBranch("todos", "@hasna/todos", ["task"], ref2("ProjectResourceExternalUuidLocator")),
            projectResourceLinkInputBranch("conversations", "@hasna/conversations", ["project"]),
            projectResourceLinkInputBranch("conversations", "@hasna/conversations", ["channel"], ref2("ProjectResourceConversationsChannelLinkLocator"), ref2("ProjectResourceConversationsChannelLabels")),
            projectResourceLinkInputBranch("knowledge", "@hasna/knowledge", ["collection", "item"]),
            projectResourceLinkInputBranch("mementos", "@hasna/mementos", ["project", "item"]),
            projectResourceLinkInputBranch("orgs", "@hasna/orgs", ["org", "project"]),
            projectResourceLinkInputBranch("contacts", "@hasna/contacts", ["contact"], ref2("ProjectResourceExternalUuidLocator")),
            projectResourceLinkInputBranch("files", "@hasna/files", ["project"], ref2("ProjectResourceCanonicalUriLocator"), ref2("ProjectResourceLinkLabels"), ["collection"])
          ]
        },
        ProjectResourceLink: {
          oneOf: [
            projectResourceLinkBranch("todos", "@hasna/todos", ["project", "task_list", "plan"]),
            projectResourceLinkBranch("todos", "@hasna/todos", ["task"], ref2("ProjectResourceExternalUuidLocator")),
            projectResourceLinkBranch("conversations", "@hasna/conversations", ["project"]),
            projectResourceLinkBranch("conversations", "@hasna/conversations", ["channel"], ref2("ProjectResourceConversationsChannelLinkLocator"), ref2("ProjectResourceConversationsChannelLabels")),
            projectResourceLinkBranch("knowledge", "@hasna/knowledge", ["collection", "item"]),
            projectResourceLinkBranch("mementos", "@hasna/mementos", ["project", "item"]),
            projectResourceLinkBranch("orgs", "@hasna/orgs", ["org", "project"]),
            projectResourceLinkBranch("contacts", "@hasna/contacts", ["contact"], ref2("ProjectResourceExternalUuidLocator")),
            projectResourceLinkBranch("files", "@hasna/files", ["project"], ref2("ProjectResourceCanonicalUriLocator"), ref2("ProjectResourceLinkLabels"), ["collection"])
          ]
        },
        ProjectResourceLinkCollectionV1: {
          type: "object",
          additionalProperties: false,
          properties: {
            schema: { type: "string", enum: ["hasna.project_resource_link_collection.v1"] },
            project_id: { type: "string" },
            current_revision: { type: "string" },
            links: { type: "array", items: ref2("ProjectResourceLink") },
            link_count: { type: "integer", minimum: 0 },
            max_items: { type: "integer", minimum: 1 },
            collection_digest: { type: "string" },
            complete: { type: "boolean", enum: [true] },
            truncated: { type: "boolean", enum: [false] }
          },
          required: [
            "schema",
            "project_id",
            "current_revision",
            "links",
            "link_count",
            "max_items",
            "collection_digest",
            "complete",
            "truncated"
          ]
        },
        ProjectResourceLinkSnapshot: {
          type: "object",
          properties: {
            project: ref2("Workspace"),
            links: { type: "array", items: ref2("ProjectResourceLink") },
            collection_digest: { type: "string" }
          },
          required: ["project", "links", "collection_digest"]
        },
        ProjectResourceLinkRead: {
          type: "object",
          properties: {
            ok: { type: "boolean", const: true },
            project_id: { type: "string" },
            project: ref2("Workspace"),
            current_revision: { type: "string" },
            links: { type: "array", items: ref2("ProjectResourceLink") },
            link_count: { type: "integer", minimum: 0 },
            max_items: { type: "integer", minimum: 1 },
            collection_digest: { type: "string" },
            complete: { type: "boolean", const: true },
            truncated: { type: "boolean", const: false },
            contract: ref2("ProjectResourceLinkCollectionV1"),
            response_control: ref2("GuardedResponseControl")
          },
          required: [
            "ok",
            "project_id",
            "project",
            "current_revision",
            "links",
            "link_count",
            "max_items",
            "collection_digest",
            "complete",
            "truncated",
            "contract",
            "response_control"
          ]
        },
        ProjectResourceLinkMutationRequest: {
          type: "object",
          properties: {
            operation_id: { type: "string" },
            step_id: { type: "string" },
            mode: { type: "string", enum: ["add", "reconcile"] },
            expected_revision: { type: "string" },
            links: { type: "array", items: ref2("ProjectResourceLinkInput") },
            integrations: { type: "object", additionalProperties: true },
            max_items: { type: "integer", minimum: 1 },
            dry_run: { type: "boolean" },
            agent_id: { type: "string" },
            source: { type: "string" },
            command: { type: "string" },
            response_byte_limit: { type: "integer", minimum: 1 },
            time_budget_ms: { type: "integer", minimum: 1 }
          },
          required: [
            "operation_id",
            "step_id",
            "expected_revision",
            "links",
            "response_byte_limit",
            "time_budget_ms"
          ]
        },
        ProjectResourceLinkMutationResult: {
          type: "object",
          properties: {
            ok: { type: "boolean" },
            dry_run: { type: "boolean" },
            outcome: { type: "string", enum: ["accepted", "duplicate_of_accepted", "terminal_nonacceptance", "planned"] },
            mode: { type: "string", enum: ["add", "reconcile"] },
            idempotency_key: { type: "string" },
            request_digest: { type: "string" },
            precondition_digest: { type: "string" },
            project_id: { type: "string" },
            expected_revision: { type: "string" },
            current_revision: { type: "string" },
            before: ref2("ProjectResourceLinkSnapshot"),
            after: { anyOf: [ref2("ProjectResourceLinkSnapshot"), { type: "null" }] },
            receipt: { anyOf: [ref2("GuardedProjectMutationReceipt"), { type: "null" }] },
            response_control: ref2("GuardedResponseControl")
          },
          required: [
            "ok",
            "dry_run",
            "outcome",
            "mode",
            "idempotency_key",
            "request_digest",
            "precondition_digest",
            "project_id",
            "expected_revision",
            "current_revision",
            "before",
            "after",
            "receipt",
            "response_control"
          ]
        },
        ProjectRelation: {
          type: "object",
          additionalProperties: false,
          properties: {
            relation_id: { type: "string" },
            version: { type: "integer", minimum: 1 },
            relation: { type: "string", enum: ["parent_of", "depends_on", "related_to"] },
            direction: { type: "string", enum: ["outbound", "inbound"] },
            self_project_id: { type: "string" },
            counterpart_project_id: { type: "string" },
            counterpart_slug: { anyOf: [{ type: "string" }, { type: "null" }] },
            counterpart_name: { anyOf: [{ type: "string" }, { type: "null" }] },
            counterpart_status: { anyOf: [{ type: "string" }, { type: "null" }] },
            created_at: { type: "string" }
          },
          required: [
            "relation_id",
            "version",
            "relation",
            "direction",
            "self_project_id",
            "counterpart_project_id",
            "counterpart_slug",
            "counterpart_name",
            "counterpart_status",
            "created_at"
          ]
        },
        ProjectRelationSnapshot: {
          type: "object",
          properties: {
            project: ref2("Workspace"),
            relations: { type: "array", items: ref2("ProjectRelation") },
            collection_digest: { type: "string" }
          },
          required: ["project", "relations", "collection_digest"]
        },
        ProjectRelationRead: {
          type: "object",
          properties: {
            ok: { type: "boolean", const: true },
            project_id: { type: "string" },
            project: ref2("Workspace"),
            current_revision: { type: "string" },
            relations: { type: "array", items: ref2("ProjectRelation") },
            outbound_count: { type: "integer", minimum: 0 },
            inbound_count: { type: "integer", minimum: 0 },
            relation_count: { type: "integer", minimum: 0 },
            max_items: { type: "integer", minimum: 1 },
            collection_digest: { type: "string" },
            complete: { type: "boolean", const: true },
            truncated: { type: "boolean", const: false },
            response_control: ref2("GuardedResponseControl")
          },
          required: [
            "ok",
            "project_id",
            "project",
            "current_revision",
            "relations",
            "outbound_count",
            "inbound_count",
            "relation_count",
            "max_items",
            "collection_digest",
            "complete",
            "truncated",
            "response_control"
          ]
        },
        ProjectRelationMutationRequest: {
          type: "object",
          properties: {
            operation_id: { type: "string" },
            step_id: { type: "string" },
            mode: { type: "string", enum: ["add", "supersede"] },
            to_project_id: { type: "string" },
            relation: { type: "string", enum: ["parent_of", "depends_on", "related_to"] },
            expected_revision: { type: "string" },
            expected_relation_version: {
              type: "integer",
              minimum: 1,
              description: "The live relation version the caller observed. A relation write never advances the project row, so " + "expected_revision alone cannot detect that another caller already superseded the same ordered pair. " + "Required for supersede: without it the write is refused as relation_state_precondition_required, and " + "one whose observed version is no longer the live head as stale_relation_state."
            },
            dry_run: { type: "boolean" },
            agent_id: { type: "string" },
            source: { type: "string" },
            command: { type: "string" },
            response_byte_limit: { type: "integer", minimum: 1 },
            time_budget_ms: { type: "integer", minimum: 1 }
          },
          required: [
            "operation_id",
            "step_id",
            "to_project_id",
            "relation",
            "expected_revision",
            "response_byte_limit",
            "time_budget_ms"
          ]
        },
        ProjectRelationMutationResult: {
          type: "object",
          properties: {
            ok: { type: "boolean" },
            dry_run: { type: "boolean" },
            outcome: { type: "string", enum: ["accepted", "duplicate_of_accepted", "terminal_nonacceptance", "planned"] },
            mode: { type: "string", enum: ["add", "supersede"] },
            idempotency_key: { type: "string" },
            request_digest: { type: "string" },
            precondition_digest: { type: "string" },
            project_id: { type: "string" },
            expected_revision: { type: "string" },
            current_revision: { type: "string" },
            relation_id: { type: "string" },
            before: ref2("ProjectRelationSnapshot"),
            after: { anyOf: [ref2("ProjectRelationSnapshot"), { type: "null" }] },
            receipt: { anyOf: [ref2("GuardedProjectMutationReceipt"), { type: "null" }] },
            response_control: ref2("GuardedResponseControl")
          },
          required: [
            "ok",
            "dry_run",
            "outcome",
            "mode",
            "idempotency_key",
            "request_digest",
            "precondition_digest",
            "project_id",
            "expected_revision",
            "current_revision",
            "relation_id",
            "before",
            "after",
            "receipt",
            "response_control"
          ]
        },
        WorkspaceLocation: {
          type: "object",
          additionalProperties: false,
          properties: {
            id: { type: "string" },
            workspace_id: { type: "string" },
            path: { type: "string" },
            machine_id: { type: "string" },
            label: { type: "string" },
            kind: { type: "string" },
            is_primary: { type: "boolean" },
            exists_at_create: { type: "boolean" },
            metadata: { type: "object", additionalProperties: true },
            created_at: { type: "string" }
          },
          required: [
            "id",
            "workspace_id",
            "path",
            "machine_id",
            "label",
            "kind",
            "is_primary",
            "exists_at_create",
            "metadata",
            "created_at"
          ]
        },
        AddWorkspaceLocation: {
          type: "object",
          additionalProperties: false,
          properties: {
            path: { type: "string" },
            machine_id: { type: "string" },
            label: { type: "string" },
            kind: { type: "string" },
            is_primary: { type: "boolean" },
            metadata: { type: "object", additionalProperties: true }
          },
          required: ["path"]
        },
        WorkspaceAgentAssignment: {
          type: "object",
          additionalProperties: false,
          properties: {
            id: { type: "string" },
            workspace_id: { type: "string" },
            agent_id: { type: "string" },
            role: { type: "string" },
            assigned_by: { type: "string", nullable: true },
            metadata: { type: "object", additionalProperties: true },
            created_at: { type: "string" },
            agent: ref2("Agent")
          },
          required: ["id", "workspace_id", "agent_id", "role", "metadata", "created_at"]
        },
        AssignWorkspaceAgent: {
          type: "object",
          additionalProperties: false,
          properties: {
            agent_id: { type: "string" },
            role: { type: "string" },
            assigned_by: { type: "string" },
            metadata: { type: "object", additionalProperties: true }
          },
          required: ["agent_id"]
        },
        WorkspaceLock: {
          type: "object",
          additionalProperties: false,
          properties: {
            id: { type: "string" },
            lock_key: { type: "string" },
            workspace_id: { type: "string", nullable: true },
            agent_id: { type: "string", nullable: true },
            reason: { type: "string", nullable: true },
            created_at: { type: "string" },
            expires_at: { type: "string", nullable: true }
          },
          required: ["id", "lock_key", "created_at"]
        },
        AcquireWorkspaceLock: {
          type: "object",
          additionalProperties: false,
          properties: {
            lock_key: { type: "string" },
            workspace_id: { type: "string" },
            agent_id: { type: "string" },
            reason: { type: "string" },
            ttl_seconds: { type: "integer" }
          },
          required: ["lock_key"]
        },
        ProjectQuarantineSnapshot: {
          type: "object",
          additionalProperties: false,
          properties: {
            project: ref2("Workspace"),
            project_digest: { type: "string" },
            resource_links: { type: "array", items: ref2("ProjectResourceLink") },
            resource_link_collection_digest: { type: "string" },
            workspace_locations: { type: "array", items: ref2("WorkspaceLocation") },
            workspace_location_collection_digest: { type: "string" }
          },
          required: [
            "project",
            "project_digest",
            "resource_links",
            "resource_link_collection_digest",
            "workspace_locations",
            "workspace_location_collection_digest"
          ]
        },
        ProjectQuarantineRead: {
          type: "object",
          additionalProperties: false,
          properties: {
            ok: { type: "boolean", const: true },
            project_id: { type: "string" },
            current_revision: { type: "string" },
            snapshot: ref2("ProjectQuarantineSnapshot"),
            resource_link_count: { type: "integer", minimum: 0 },
            workspace_location_count: { type: "integer", minimum: 0 },
            complete: { type: "boolean", const: true },
            truncated: { type: "boolean", const: false },
            response_control: ref2("GuardedResponseControl")
          },
          required: [
            "ok",
            "project_id",
            "current_revision",
            "snapshot",
            "resource_link_count",
            "workspace_location_count",
            "complete",
            "truncated",
            "response_control"
          ]
        },
        ProjectQuarantineRequest: {
          type: "object",
          additionalProperties: false,
          properties: {
            operation_id: { type: "string" },
            step_id: { type: "string" },
            expected_revision: { type: "string" },
            expected_project_digest: { type: "string" },
            expected_resource_link_collection_digest: { type: "string" },
            expected_resource_link_ids: { type: "array", items: { type: "string" } },
            resource_link_max_items: { type: "integer", minimum: 1 },
            expected_workspace_location_collection_digest: { type: "string" },
            expected_workspace_location_ids: { type: "array", items: { type: "string" } },
            workspace_location_max_items: { type: "integer", minimum: 1 },
            quarantine_name: { type: "string", minLength: 1 },
            quarantine_slug: { type: "string", pattern: "^[a-z0-9]+(?:-[a-z0-9]+)*$" },
            dry_run: { type: "boolean" },
            agent_id: { type: "string" },
            source: { type: "string" },
            command: { type: "string" },
            response_byte_limit: { type: "integer", minimum: 1 },
            time_budget_ms: { type: "integer", minimum: 1 }
          },
          required: [
            "operation_id",
            "step_id",
            "expected_revision",
            "expected_project_digest",
            "expected_resource_link_collection_digest",
            "expected_resource_link_ids",
            "resource_link_max_items",
            "expected_workspace_location_collection_digest",
            "expected_workspace_location_ids",
            "workspace_location_max_items",
            "quarantine_name",
            "quarantine_slug",
            "response_byte_limit",
            "time_budget_ms"
          ]
        },
        ProjectQuarantineRollbackRequest: {
          type: "object",
          additionalProperties: false,
          properties: {
            operation_id: { type: "string" },
            step_id: { type: "string" },
            accepted_receipt_id: { type: "string" },
            expected_current_revision: { type: "string" },
            resource_link_max_items: { type: "integer", minimum: 1 },
            workspace_location_max_items: { type: "integer", minimum: 1 },
            agent_id: { type: "string" },
            source: { type: "string" },
            command: { type: "string" },
            response_byte_limit: { type: "integer", minimum: 1 },
            time_budget_ms: { type: "integer", minimum: 1 }
          },
          required: [
            "operation_id",
            "step_id",
            "accepted_receipt_id",
            "expected_current_revision",
            "resource_link_max_items",
            "workspace_location_max_items",
            "response_byte_limit",
            "time_budget_ms"
          ]
        },
        ProjectQuarantineResult: {
          type: "object",
          additionalProperties: false,
          properties: {
            ok: { type: "boolean" },
            dry_run: { type: "boolean" },
            outcome: { type: "string", enum: ["accepted", "duplicate_of_accepted", "terminal_nonacceptance", "planned"] },
            idempotency_key: { type: "string" },
            request_digest: { type: "string" },
            precondition_digest: { type: "string" },
            project_id: { type: "string" },
            expected_revision: { type: "string" },
            current_revision: { type: "string" },
            before: ref2("ProjectQuarantineSnapshot"),
            after: { anyOf: [ref2("ProjectQuarantineSnapshot"), { type: "null" }] },
            receipt: { anyOf: [ref2("GuardedProjectMutationReceipt"), { type: "null" }] },
            rollback: {
              anyOf: [
                {
                  type: "object",
                  additionalProperties: false,
                  properties: {
                    accepted_receipt_id: { type: "string" },
                    expected_current_revision: { type: "string" }
                  },
                  required: ["accepted_receipt_id", "expected_current_revision"]
                },
                { type: "null" }
              ]
            },
            response_control: ref2("GuardedResponseControl")
          },
          required: [
            "ok",
            "dry_run",
            "outcome",
            "idempotency_key",
            "request_digest",
            "precondition_digest",
            "project_id",
            "expected_revision",
            "current_revision",
            "before",
            "after",
            "receipt",
            "rollback",
            "response_control"
          ]
        },
        ContactProjectMembershipSnapshot: {
          type: "object",
          additionalProperties: false,
          properties: {
            contact_id: { type: "string" },
            project_id: { type: "string" },
            linked: { type: "boolean" },
            version: { type: "string" }
          },
          required: ["contact_id", "project_id", "linked", "version"]
        },
        ProjectContactLinkEvidence: {
          type: "object",
          additionalProperties: false,
          properties: {
            system: { type: "string", enum: ["contacts", "projects"] },
            step_id: { type: "string" },
            outcome: { type: "string" },
            receipt_id: { type: ["string", "null"] },
            compensated: { type: "boolean" }
          },
          required: ["system", "step_id", "outcome", "receipt_id", "compensated"]
        },
        ProjectContactLinkMutationRequest: {
          type: "object",
          additionalProperties: false,
          properties: {
            operation_id: { type: "string" },
            labels: ref2("ProjectResourceLinkLabels"),
            max_items: { type: "integer", minimum: 1 },
            response_byte_limit: { type: "integer", minimum: 1 },
            time_budget_ms: { type: "integer", minimum: 1 }
          },
          required: ["operation_id", "max_items", "response_byte_limit", "time_budget_ms"]
        },
        ProjectContactLinkMutationResult: {
          type: "object",
          additionalProperties: false,
          properties: {
            ok: { type: "boolean", const: true },
            outcome: { type: "string", enum: ["accepted", "duplicate_of_accepted"] },
            authority: { type: "string", const: "contacts" },
            project_id: { type: "string" },
            contact_id: { type: "string" },
            membership: ref2("ContactProjectMembershipSnapshot"),
            project_link: { anyOf: [ref2("ProjectResourceLink"), { type: "null" }] },
            evidence: { type: "array", items: ref2("ProjectContactLinkEvidence") },
            response_control: ref2("GuardedResponseControl")
          },
          required: [
            "ok",
            "outcome",
            "authority",
            "project_id",
            "contact_id",
            "membership",
            "project_link",
            "evidence",
            "response_control"
          ]
        },
        ProjectContactLinkListResult: {
          type: "object",
          additionalProperties: false,
          properties: {
            ok: { type: "boolean", const: true },
            authority: { type: "string", const: "contacts" },
            project_id: { type: "string" },
            membership_revision: { type: "string" },
            project_revision: { type: "string" },
            contact_ids: { type: "array", items: { type: "string" } },
            synchronized_contact_ids: { type: "array", items: { type: "string" } },
            missing_project_link_contact_ids: { type: "array", items: { type: "string" } },
            stale_project_link_contact_ids: { type: "array", items: { type: "string" } },
            project_links: { type: "array", items: ref2("ProjectResourceLink") },
            response_control: ref2("GuardedResponseControl")
          },
          required: [
            "ok",
            "authority",
            "project_id",
            "membership_revision",
            "project_revision",
            "contact_ids",
            "synchronized_contact_ids",
            "missing_project_link_contact_ids",
            "stale_project_link_contact_ids",
            "project_links",
            "response_control"
          ]
        },
        ProjectResourceLinkRollbackRequest: {
          type: "object",
          properties: {
            operation_id: { type: "string" },
            step_id: { type: "string" },
            accepted_receipt_id: { type: "string" },
            expected_current_revision: { type: "string" },
            max_items: { type: "integer", minimum: 1 },
            agent_id: { type: "string" },
            source: { type: "string" },
            command: { type: "string" },
            response_byte_limit: { type: "integer", minimum: 1 },
            time_budget_ms: { type: "integer", minimum: 1 }
          },
          required: [
            "operation_id",
            "step_id",
            "accepted_receipt_id",
            "expected_current_revision",
            "response_byte_limit",
            "time_budget_ms"
          ]
        },
        ProjectResourceLinkProducerBinding: {
          type: "object",
          additionalProperties: false,
          properties: {
            authority_id: { type: "string" },
            tenant_id: { type: "string" },
            corpus_id: { anyOf: [{ type: "string" }, { type: "null" }] },
            capability_digest: { type: "string" }
          },
          required: ["authority_id", "tenant_id", "corpus_id", "capability_digest"]
        },
        ProjectResourceLinkProducerEvidence: {
          type: "object",
          additionalProperties: false,
          properties: {
            created_by_operation: { type: "boolean" },
            forward_receipt_id: { anyOf: [{ type: "string" }, { type: "null" }] },
            child_link_receipt_ids: { type: "array", items: { type: "string" } },
            target_revision: { type: "string" },
            target_digest: { type: "string" },
            inverse_verified: { anyOf: [{ type: "boolean" }, { type: "null" }] },
            inverse_outcome: { anyOf: [{ type: "string" }, { type: "null" }] }
          },
          required: [
            "created_by_operation",
            "forward_receipt_id",
            "child_link_receipt_ids",
            "target_revision",
            "target_digest",
            "inverse_verified",
            "inverse_outcome"
          ]
        },
        ProjectResourceLinkMigrationItemInput: {
          type: "object",
          additionalProperties: false,
          properties: {
            link: ref2("ProjectResourceLinkInput"),
            producer_resource_kind: { type: "string" },
            producer_binding: ref2("ProjectResourceLinkProducerBinding")
          },
          required: ["link", "producer_resource_kind", "producer_binding"]
        },
        ProjectResourceLinkMigrationItem: {
          type: "object",
          additionalProperties: false,
          properties: {
            link: ref2("ProjectResourceLinkInput"),
            link_id: { type: "string", pattern: "^prl_" },
            producer_resource_kind: { type: "string" },
            producer_binding: ref2("ProjectResourceLinkProducerBinding"),
            producer_evidence: {
              anyOf: [ref2("ProjectResourceLinkProducerEvidence"), { type: "null" }]
            }
          },
          required: [
            "link",
            "link_id",
            "producer_resource_kind",
            "producer_binding",
            "producer_evidence"
          ]
        },
        ProjectResourceLinkProjectsReferenceProof: {
          oneOf: [
            {
              type: "object",
              additionalProperties: false,
              properties: {
                kind: { type: "string", enum: ["accepted_inverse"] },
                forward_receipt_id: { type: "string" },
                inverse_receipt_id: { type: "string" },
                verified_revision: { type: "string" },
                collection_digest: { type: "string" },
                link_ids_checked: { type: "array", items: { type: "string" } },
                complete: { type: "boolean", enum: [true] },
                truncated: { type: "boolean", enum: [false] },
                request_digest: { type: "string" },
                precondition_digest: { type: "string" }
              },
              required: [
                "kind",
                "forward_receipt_id",
                "inverse_receipt_id",
                "verified_revision",
                "collection_digest",
                "link_ids_checked",
                "complete",
                "truncated",
                "request_digest",
                "precondition_digest"
              ]
            },
            {
              type: "object",
              additionalProperties: false,
              properties: {
                kind: { type: "string", enum: ["no_projects_write"] },
                verified_revision: { type: "string" },
                collection_digest: { type: "string" },
                link_ids_checked: { type: "array", items: { type: "string" } },
                complete: { type: "boolean", enum: [true] },
                truncated: { type: "boolean", enum: [false] },
                request_digest: { type: "string" },
                precondition_digest: { type: "string" }
              },
              required: [
                "kind",
                "verified_revision",
                "collection_digest",
                "link_ids_checked",
                "complete",
                "truncated",
                "request_digest",
                "precondition_digest"
              ]
            }
          ]
        },
        ProjectResourceLinkMigrationManifestV1: {
          type: "object",
          additionalProperties: false,
          properties: {
            schema: { type: "string", enum: ["projects.project_resource_link_migration_manifest.v1"] },
            manifest_id: { type: "string", pattern: "^prlm_" },
            project_id: { type: "string" },
            operation_id: { type: "string" },
            step_id: { type: "string" },
            state: {
              type: "string",
              enum: [
                "planned",
                "producer_applied",
                "projects_applied",
                "verified",
                "rollback_in_progress",
                "rolled_back",
                "retained_target",
                "failed_reconcilable"
              ]
            },
            expected_project_revision: { type: "string" },
            desired_collection_digest: { type: "string" },
            links: { type: "array", items: ref2("ProjectResourceLinkMigrationItem") },
            projects_forward_receipt_id: { anyOf: [{ type: "string" }, { type: "null" }] },
            projects_inverse_receipt_id: { anyOf: [{ type: "string" }, { type: "null" }] },
            projects_reference_proof: {
              anyOf: [ref2("ProjectResourceLinkProjectsReferenceProof"), { type: "null" }]
            },
            last_verified_projects_revision: { anyOf: [{ type: "string" }, { type: "null" }] },
            last_verified_projects_digest: { anyOf: [{ type: "string" }, { type: "null" }] },
            transition_version: { type: "integer", minimum: 1 },
            created_at: { type: "string" },
            updated_at: { type: "string" }
          },
          required: [
            "schema",
            "manifest_id",
            "project_id",
            "operation_id",
            "step_id",
            "state",
            "expected_project_revision",
            "desired_collection_digest",
            "links",
            "projects_forward_receipt_id",
            "projects_inverse_receipt_id",
            "projects_reference_proof",
            "last_verified_projects_revision",
            "last_verified_projects_digest",
            "transition_version",
            "created_at",
            "updated_at"
          ]
        },
        ProjectResourceLinkMigrationEvent: {
          type: "object",
          additionalProperties: false,
          properties: {
            event_id: { type: "string", pattern: "^prlme_" },
            manifest_id: { type: "string", pattern: "^prlm_" },
            transition_version: { type: "integer", minimum: 1 },
            from_state: { anyOf: [{ type: "string" }, { type: "null" }] },
            to_state: { type: "string" },
            request_digest: { type: "string" },
            precondition_digest: { type: "string" },
            evidence: { type: "object", additionalProperties: true },
            created_at: { type: "string" }
          },
          required: [
            "event_id",
            "manifest_id",
            "transition_version",
            "from_state",
            "to_state",
            "request_digest",
            "precondition_digest",
            "evidence",
            "created_at"
          ]
        },
        ProjectResourceLinkMigrationPlanRequest: {
          type: "object",
          additionalProperties: false,
          properties: {
            operation_id: { type: "string" },
            step_id: { type: "string" },
            expected_project_revision: { type: "string" },
            links: { type: "array", items: ref2("ProjectResourceLinkMigrationItemInput") },
            max_items: { type: "integer", minimum: 1 },
            response_byte_limit: { type: "integer", minimum: 1 },
            time_budget_ms: { type: "integer", minimum: 1 }
          },
          required: [
            "operation_id",
            "step_id",
            "expected_project_revision",
            "links",
            "response_byte_limit",
            "time_budget_ms"
          ]
        },
        ProjectResourceLinkMigrationAdvanceRequest: {
          type: "object",
          additionalProperties: false,
          properties: {
            expected_transition_version: { type: "integer", minimum: 1 },
            next_state: {
              type: "string",
              enum: ["producer_applied", "projects_applied", "verified", "failed_reconcilable"]
            },
            max_items: { type: "integer", minimum: 1 },
            producer_evidence: {
              type: "array",
              items: ref2("ProjectResourceLinkProducerEvidence")
            },
            projects_forward_receipt_id: { type: "string" },
            last_verified_projects_revision: { type: "string" },
            last_verified_projects_digest: { type: "string" },
            evidence: { type: "object", additionalProperties: true },
            response_byte_limit: { type: "integer", minimum: 1 },
            time_budget_ms: { type: "integer", minimum: 1 }
          },
          required: [
            "expected_transition_version",
            "next_state",
            "evidence",
            "response_byte_limit",
            "time_budget_ms"
          ]
        },
        ProjectResourceLinkMigrationRollbackRequest: {
          type: "object",
          additionalProperties: false,
          properties: {
            expected_transition_version: { type: "integer", minimum: 1 },
            max_items: { type: "integer", minimum: 1 },
            producer_outcome: {
              type: "string",
              enum: ["pending", "complete", "retained_target", "failed_reconcilable"]
            },
            producer_evidence: {
              type: "array",
              items: ref2("ProjectResourceLinkProducerEvidence")
            },
            evidence: { type: "object", additionalProperties: true },
            agent_id: { type: "string" },
            source: { type: "string" },
            command: { type: "string" },
            response_byte_limit: { type: "integer", minimum: 1 },
            time_budget_ms: { type: "integer", minimum: 1 }
          },
          required: [
            "expected_transition_version",
            "producer_outcome",
            "evidence",
            "response_byte_limit",
            "time_budget_ms"
          ]
        },
        ProjectResourceLinkMigrationResult: {
          type: "object",
          additionalProperties: false,
          properties: {
            ok: { type: "boolean" },
            outcome: {
              type: "string",
              enum: ["accepted", "duplicate_of_accepted", "terminal_nonacceptance"]
            },
            manifest: ref2("ProjectResourceLinkMigrationManifestV1"),
            events: { type: "array", items: ref2("ProjectResourceLinkMigrationEvent") },
            response_control: ref2("GuardedResponseControl")
          },
          required: ["ok", "outcome", "manifest", "events", "response_control"]
        },
        GuardedProjectMutationReceipt: {
          type: "object",
          properties: {
            receipt_id: { type: "string" },
            operation_id: { type: "string" },
            step_id: { type: "string" },
            direction: { type: "string", enum: ["forward", "inverse"] },
            idempotency_key: { type: "string" },
            target_id: { type: "string" },
            request_digest: { type: "string" },
            precondition_digest: { type: "string" },
            expected_revision: { type: "string" },
            outcome: { type: "string", enum: ["accepted", "duplicate_of_accepted", "terminal_nonacceptance"] },
            reason: { type: "string", nullable: true },
            result_project_id: { type: "string", nullable: true },
            duplicate_of_receipt_id: { type: "string", nullable: true },
            before: { type: "object", additionalProperties: true, nullable: true },
            after: { type: "object", additionalProperties: true, nullable: true },
            post_revision: { type: "string", nullable: true },
            created_at: { type: "string" }
          },
          required: [
            "receipt_id",
            "operation_id",
            "step_id",
            "direction",
            "idempotency_key",
            "target_id",
            "request_digest",
            "precondition_digest",
            "expected_revision",
            "outcome",
            "reason",
            "result_project_id",
            "duplicate_of_receipt_id",
            "before",
            "after",
            "post_revision",
            "created_at"
          ]
        },
        GuardedProjectMutationRequest: {
          type: "object",
          properties: {
            operation_id: { type: "string" },
            step_id: { type: "string" },
            direction: { type: "string", enum: ["forward", "inverse"] },
            expected_revision: { type: "string" },
            patch: ref2("UpdateWorkspace"),
            dry_run: { type: "boolean" },
            agent_id: { type: "string" },
            source: { type: "string" },
            command: { type: "string" },
            response_byte_limit: { type: "integer", minimum: 1 },
            time_budget_ms: { type: "integer", minimum: 1 }
          },
          required: ["operation_id", "step_id", "expected_revision", "patch", "response_byte_limit", "time_budget_ms"]
        },
        GuardedProjectMutationResult: {
          type: "object",
          properties: {
            ok: { type: "boolean" },
            dry_run: { type: "boolean" },
            outcome: { type: "string", enum: ["accepted", "duplicate_of_accepted", "terminal_nonacceptance", "planned"] },
            idempotency_key: { type: "string" },
            request_digest: { type: "string" },
            precondition_digest: { type: "string" },
            project_id: { type: "string" },
            expected_revision: { type: "string" },
            current_revision: { type: "string" },
            before: ref2("Workspace"),
            after: { anyOf: [ref2("Workspace"), { type: "null" }] },
            receipt: { anyOf: [ref2("GuardedProjectMutationReceipt"), { type: "null" }] },
            response_control: ref2("GuardedResponseControl")
          },
          required: [
            "ok",
            "dry_run",
            "outcome",
            "idempotency_key",
            "request_digest",
            "precondition_digest",
            "project_id",
            "expected_revision",
            "current_revision",
            "before",
            "after",
            "receipt",
            "response_control"
          ]
        },
        GuardedProjectMutationReceiptLookup: {
          type: "object",
          properties: {
            receipt: ref2("GuardedProjectMutationReceipt"),
            response_control: ref2("GuardedResponseControl")
          },
          required: ["receipt", "response_control"]
        },
        GuardedProjectMutationRollbackRequest: {
          type: "object",
          properties: {
            operation_id: { type: "string" },
            step_id: { type: "string" },
            accepted_receipt_id: { type: "string" },
            expected_current_revision: { type: "string" },
            agent_id: { type: "string" },
            source: { type: "string" },
            command: { type: "string" },
            response_byte_limit: { type: "integer", minimum: 1 },
            time_budget_ms: { type: "integer", minimum: 1 }
          },
          required: [
            "operation_id",
            "step_id",
            "accepted_receipt_id",
            "expected_current_revision",
            "response_byte_limit",
            "time_budget_ms"
          ]
        },
        RootList: {
          type: "object",
          properties: { roots: { type: "array", items: ref2("Root") }, count: { type: "integer" } },
          required: ["roots", "count"]
        },
        AgentList: {
          type: "object",
          properties: { agents: { type: "array", items: ref2("Agent") }, count: { type: "integer" } },
          required: ["agents", "count"]
        },
        RecipeList: {
          type: "object",
          properties: { recipes: { type: "array", items: ref2("Recipe") }, count: { type: "integer" } },
          required: ["recipes", "count"]
        },
        Machine: {
          type: "object",
          properties: {
            slug: { type: "string" },
            status: { type: "string" },
            role: { type: "string", enum: ["mirror-hub", "assignable", "avoid"] }
          },
          required: ["slug", "status", "role"]
        },
        MachineList: {
          type: "object",
          properties: { machines: { type: "array", items: ref2("Machine") }, count: { type: "integer" } },
          required: ["machines", "count"]
        },
        EventList: {
          type: "object",
          properties: { events: { type: "array", items: ref2("WorkspaceEvent") }, count: { type: "integer" } },
          required: ["events", "count"]
        },
        LocationList: {
          type: "object",
          properties: { locations: { type: "array", items: ref2("WorkspaceLocation") }, count: { type: "integer" } },
          required: ["locations", "count"]
        },
        LocationAdded: {
          type: "object",
          properties: { project: ref2("Workspace"), location: ref2("WorkspaceLocation") },
          required: ["project", "location"]
        },
        AgentAssignmentList: {
          type: "object",
          properties: { assignments: { type: "array", items: ref2("WorkspaceAgentAssignment") }, count: { type: "integer" } },
          required: ["assignments", "count"]
        },
        AgentAssignment: {
          type: "object",
          properties: { assignment: ref2("WorkspaceAgentAssignment") },
          required: ["assignment"]
        },
        LockList: {
          type: "object",
          properties: { locks: { type: "array", items: ref2("WorkspaceLock") }, count: { type: "integer" } },
          required: ["locks", "count"]
        },
        LockRelease: {
          type: "object",
          properties: { released: { type: "boolean" } },
          required: ["released"]
        },
        RecordEvent: {
          type: "object",
          properties: {
            event_type: { type: "string" },
            source: { type: "string" },
            agent_id: { type: "string" },
            prompt: { type: "string" },
            command: { type: "string" },
            before: { type: "object", additionalProperties: true, nullable: true },
            after: { type: "object", additionalProperties: true, nullable: true },
            metadata: { type: "object", additionalProperties: true }
          },
          required: ["event_type"]
        },
        EventRecorded: {
          type: "object",
          properties: { event: ref2("WorkspaceEvent") },
          required: ["event"]
        },
        DeleteResult: {
          type: "object",
          properties: { deleted: { type: "boolean" }, hard: { type: "boolean" }, id: { type: "string" } },
          required: ["deleted"]
        },
        Health: {
          type: "object",
          properties: { status: { type: "string" }, version: { type: "string" } },
          required: ["status", "version"]
        },
        LegacyVersionResponse: {
          type: "object",
          description: "Compatibility response for /version.",
          properties: {
            status: { type: "string" },
            version: { type: "string" }
          },
          required: ["status", "version"]
        },
        Error: {
          type: "object",
          properties: { error: { type: "string" }, reason: { type: "string" } },
          required: ["error"]
        }
      }
    },
    security: [{ apiKey: [] }],
    paths: {
      ...projectionOpenApiPaths,
      "/health": {
        get: {
          operationId: "getHealth",
          summary: "Liveness probe",
          security: [],
          responses: { "200": jsonResp("Health") }
        }
      },
      "/ready": {
        get: {
          operationId: "getReady",
          summary: "Readiness probe (checks DB connectivity)",
          security: [],
          responses: { "200": jsonResp("Health"), "503": jsonResp("Health", "Not ready") }
        }
      },
      "/version": {
        get: {
          operationId: "getVersion",
          summary: "Service version",
          security: [],
          responses: { "200": jsonResp("LegacyVersionResponse") }
        }
      },
      "/v1/projects": {
        get: {
          operationId: "listProjects",
          summary: "List projects (workspaces)",
          parameters: [
            { name: "status", in: "query", required: false, schema: { type: "string" } },
            { name: "kind", in: "query", required: false, schema: { type: "string" } },
            { name: "root_id", in: "query", required: false, schema: { type: "string" } },
            { name: "query", in: "query", required: false, schema: { type: "string", maxLength: 512 } },
            { name: "query_scope", in: "query", required: false, schema: { type: "string", enum: ["identity", "discovery", "structured", "all"] } },
            { name: "tag", in: "query", required: false, schema: { type: "string", maxLength: 128 } },
            { name: "tags", in: "query", required: false, style: "form", explode: true, schema: { type: "array", maxItems: 50, items: { type: "string", maxLength: 128 } } },
            { name: "exclude_evals", in: "query", required: false, schema: { type: "boolean", default: false } },
            { name: "include_fixtures", in: "query", required: false, schema: { type: "boolean", default: false } },
            {
              name: "limit",
              in: "query",
              required: false,
              description: `Rows per page (default ${WORKSPACE_LIST_DEFAULT_LIMIT}, clamped to ${WORKSPACE_LIST_MAX_LIMIT}). A larger value is clamped, not honoured \u2014 page with offset and read has_more.`,
              schema: { type: "integer" }
            },
            { name: "offset", in: "query", required: false, schema: { type: "integer" } }
          ],
          responses: { "200": jsonResp("WorkspaceList") }
        },
        post: {
          operationId: "createProject",
          summary: "Create a project (workspace)",
          requestBody: jsonBody("CreateWorkspace"),
          responses: { "201": jsonResp("Workspace", "Created"), "400": jsonResp("Error", "Invalid") }
        }
      },
      "/v1/projects/{id}": {
        get: {
          operationId: "getProject",
          summary: "Get a project by id or slug",
          parameters: [ID_PARAM],
          responses: { "200": jsonResp("Workspace"), "404": jsonResp("Error", "Not found") }
        },
        patch: {
          operationId: "updateProject",
          summary: "Update a project",
          parameters: [ID_PARAM],
          requestBody: jsonBody("UpdateWorkspace"),
          responses: { "200": jsonResp("Workspace"), "404": jsonResp("Error", "Not found") }
        },
        delete: {
          operationId: "deleteProject",
          summary: "Delete a project (soft by default, ?hard=true for hard delete)",
          parameters: [
            ID_PARAM,
            { name: "hard", in: "query", required: false, schema: { type: "boolean" } }
          ],
          responses: { "200": jsonResp("DeleteResult"), "404": jsonResp("Error", "Not found") }
        }
      },
      "/v1/projects/{id}/guarded-metadata": {
        get: {
          operationId: "guardedReadProject",
          summary: "Read one project by exact stable id with bounded complete JSON and its current mutation revision",
          parameters: [
            EXACT_PROJECT_ID_PARAM,
            {
              name: "response_byte_limit",
              in: "query",
              required: true,
              schema: { type: "integer", minimum: 1 }
            },
            {
              name: "time_budget_ms",
              in: "query",
              required: true,
              schema: { type: "integer", minimum: 1 }
            },
            {
              name: "resource_link_max_items",
              in: "query",
              required: false,
              schema: { type: "integer", minimum: 1, default: 1000 }
            }
          ],
          responses: {
            "200": jsonResp("GuardedProjectRead"),
            "400": jsonResp("Error", "Invalid target or budget"),
            "404": jsonResp("Error", "Not found")
          }
        },
        post: {
          operationId: "guardedUpdateProject",
          summary: "Conditionally update one exact project and return a deterministic terminal receipt",
          parameters: [EXACT_PROJECT_ID_PARAM],
          requestBody: jsonBody("GuardedProjectMutationRequest"),
          responses: {
            "200": jsonResp("GuardedProjectMutationResult"),
            "400": jsonResp("Error", "Invalid target, precondition, or budget"),
            "404": jsonResp("Error", "Not found")
          }
        }
      },
      "/v1/projects/{id}/guarded-metadata/receipts": {
        get: {
          operationId: "lookupGuardedProjectMutationReceipt",
          summary: "Look up exactly one terminal guarded mutation receipt",
          parameters: [
            EXACT_PROJECT_ID_PARAM,
            { name: "operation_id", in: "query", required: true, schema: { type: "string" } },
            { name: "step_id", in: "query", required: true, schema: { type: "string" } },
            { name: "direction", in: "query", required: true, schema: { type: "string", enum: ["forward", "inverse"] } },
            { name: "idempotency_key", in: "query", required: true, schema: { type: "string" } },
            { name: "max_items", in: "query", required: true, schema: { type: "integer", const: 1 } },
            { name: "response_byte_limit", in: "query", required: true, schema: { type: "integer", minimum: 1 } },
            { name: "time_budget_ms", in: "query", required: true, schema: { type: "integer", minimum: 1 } }
          ],
          responses: {
            "200": jsonResp("GuardedProjectMutationReceiptLookup"),
            "400": jsonResp("Error", "Invalid lookup or terminal cardinality"),
            "404": jsonResp("Error", "Not found")
          }
        }
      },
      "/v1/projects/{id}/guarded-metadata/rollback": {
        post: {
          operationId: "rollbackGuardedProjectMutation",
          summary: "Conditionally roll back one accepted guarded mutation receipt",
          parameters: [EXACT_PROJECT_ID_PARAM],
          requestBody: jsonBody("GuardedProjectMutationRollbackRequest"),
          responses: {
            "200": jsonResp("GuardedProjectMutationResult"),
            "400": jsonResp("Error", "Invalid receipt, precondition, or budget"),
            "404": jsonResp("Error", "Not found")
          }
        }
      },
      "/v1/projects/{id}/resource-links": {
        get: {
          operationId: "readProjectResourceLinks",
          summary: "Read the complete typed project resource-link collection under explicit bounds",
          parameters: [
            EXACT_PROJECT_ID_PARAM,
            { name: "max_items", in: "query", required: true, schema: { type: "integer", minimum: 1 } },
            { name: "response_byte_limit", in: "query", required: true, schema: { type: "integer", minimum: 1 } },
            { name: "time_budget_ms", in: "query", required: true, schema: { type: "integer", minimum: 1 } }
          ],
          responses: {
            "200": jsonResp("ProjectResourceLinkRead"),
            "400": jsonResp("Error", "Invalid target or collection bound"),
            "404": jsonResp("Error", "Not found")
          }
        }
      },
      "/v1/projects/{id}/resource-links/add": {
        post: {
          operationId: "addProjectResourceLinks",
          summary: "Idempotently add typed resource links under a project revision CAS",
          parameters: [EXACT_PROJECT_ID_PARAM],
          requestBody: jsonBody("ProjectResourceLinkMutationRequest"),
          responses: {
            "200": jsonResp("ProjectResourceLinkMutationResult"),
            "400": jsonResp("Error", "Invalid link, revision, digest, or bound"),
            "404": jsonResp("Error", "Not found")
          }
        }
      },
      "/v1/projects/{id}/resource-links/reconcile": {
        post: {
          operationId: "reconcileProjectResourceLinks",
          summary: "Reconcile the complete typed resource-link collection under a project revision CAS",
          parameters: [EXACT_PROJECT_ID_PARAM],
          requestBody: jsonBody("ProjectResourceLinkMutationRequest"),
          responses: {
            "200": jsonResp("ProjectResourceLinkMutationResult"),
            "400": jsonResp("Error", "Invalid link, revision, digest, or bound"),
            "404": jsonResp("Error", "Not found")
          }
        }
      },
      "/v1/projects/{id}/resource-links/rollback": {
        post: {
          operationId: "rollbackProjectResourceLinks",
          summary: "Restore the exact pre-mutation typed resource-link collection from an accepted receipt",
          parameters: [EXACT_PROJECT_ID_PARAM],
          requestBody: jsonBody("ProjectResourceLinkRollbackRequest"),
          responses: {
            "200": jsonResp("ProjectResourceLinkMutationResult"),
            "400": jsonResp("Error", "Invalid receipt, revision, digest, or bound"),
            "404": jsonResp("Error", "Not found")
          }
        }
      },
      "/v1/projects/{id}/relations": {
        get: {
          operationId: "readProjectRelations",
          summary: "Read one project's complete two-sided typed relation collection under explicit bounds",
          parameters: [
            EXACT_PROJECT_ID_PARAM,
            { name: "max_items", in: "query", required: true, schema: { type: "integer", minimum: 1 } },
            { name: "response_byte_limit", in: "query", required: true, schema: { type: "integer", minimum: 1 } },
            { name: "time_budget_ms", in: "query", required: true, schema: { type: "integer", minimum: 1 } }
          ],
          responses: {
            "200": jsonResp("ProjectRelationRead"),
            "400": jsonResp("Error", "Invalid target or collection bound"),
            "404": jsonResp("Error", "Not found")
          }
        }
      },
      "/v1/projects/{id}/relations/add": {
        post: {
          operationId: "addProjectRelation",
          summary: "Declare the first typed relation for one ordered pair of Projects identities under a project revision CAS",
          parameters: [EXACT_PROJECT_ID_PARAM],
          requestBody: jsonBody("ProjectRelationMutationRequest"),
          responses: {
            "200": jsonResp("ProjectRelationMutationResult"),
            "400": jsonResp("Error", "Invalid relation, endpoint, revision, or bound"),
            "404": jsonResp("Error", "Not found")
          }
        }
      },
      "/v1/projects/{id}/relations/supersede": {
        post: {
          operationId: "supersedeProjectRelation",
          summary: "Replace the declared typed relation of one ordered pair, preserving the retired version",
          parameters: [EXACT_PROJECT_ID_PARAM],
          requestBody: jsonBody("ProjectRelationMutationRequest"),
          responses: {
            "200": jsonResp("ProjectRelationMutationResult"),
            "400": jsonResp("Error", "Invalid relation, endpoint, revision, or bound"),
            "404": jsonResp("Error", "Not found")
          }
        }
      },
      "/v1/projects/{id}/duplicate-quarantine": {
        get: {
          operationId: "readDuplicateProjectQuarantinePreimage",
          summary: "Read the exact complete project, resource-link, and path-selector preimage for quarantine",
          parameters: [
            EXACT_PROJECT_ID_PARAM,
            { name: "resource_link_max_items", in: "query", required: true, schema: { type: "integer", minimum: 1 } },
            { name: "workspace_location_max_items", in: "query", required: true, schema: { type: "integer", minimum: 1 } },
            { name: "response_byte_limit", in: "query", required: true, schema: { type: "integer", minimum: 1 } },
            { name: "time_budget_ms", in: "query", required: true, schema: { type: "integer", minimum: 1 } }
          ],
          responses: {
            "200": jsonResp("ProjectQuarantineRead"),
            "400": jsonResp("Error", "Invalid target or incomplete collection bound"),
            "404": jsonResp("Error", "Not found")
          }
        },
        post: {
          operationId: "quarantineDuplicateProject",
          summary: "Atomically retire duplicate selectors and links while retaining reversible provenance",
          parameters: [EXACT_PROJECT_ID_PARAM],
          requestBody: jsonBody("ProjectQuarantineRequest"),
          responses: {
            "200": jsonResp("ProjectQuarantineResult"),
            "400": jsonResp("Error", "Invalid precondition, target set, digest, or collection bound"),
            "404": jsonResp("Error", "Not found")
          }
        }
      },
      "/v1/projects/{id}/duplicate-quarantine/rollback": {
        post: {
          operationId: "rollbackDuplicateProjectQuarantine",
          summary: "Restore the exact project metadata, resource links, and path selectors from the accepted receipt",
          parameters: [EXACT_PROJECT_ID_PARAM],
          requestBody: jsonBody("ProjectQuarantineRollbackRequest"),
          responses: {
            "200": jsonResp("ProjectQuarantineResult"),
            "400": jsonResp("Error", "Invalid receipt, revision, digest, or post-write state"),
            "404": jsonResp("Error", "Not found")
          }
        }
      },
      "/v1/projects/{id}/resource-link-migrations/plan": {
        post: {
          operationId: "planProjectResourceLinkMigration",
          summary: "Persist a durable resource-link migration manifest before any authority write",
          parameters: [EXACT_PROJECT_ID_PARAM],
          requestBody: jsonBody("ProjectResourceLinkMigrationPlanRequest"),
          responses: {
            "200": jsonResp("ProjectResourceLinkMigrationResult"),
            "400": jsonResp("Error", "Invalid link, authority binding, revision, or bound"),
            "404": jsonResp("Error", "Not found")
          }
        }
      },
      "/v1/projects/{id}/resource-link-migrations/{manifestId}": {
        get: {
          operationId: "readProjectResourceLinkMigration",
          summary: "Read one durable migration manifest and its complete immutable event history",
          parameters: [
            EXACT_PROJECT_ID_PARAM,
            { name: "manifestId", in: "path", required: true, schema: { type: "string", pattern: "^prlm_" } },
            { name: "max_items", in: "query", required: true, schema: { type: "integer", minimum: 1 } },
            { name: "response_byte_limit", in: "query", required: true, schema: { type: "integer", minimum: 1 } },
            { name: "time_budget_ms", in: "query", required: true, schema: { type: "integer", minimum: 1 } }
          ],
          responses: {
            "200": jsonResp("ProjectResourceLinkMigrationResult"),
            "400": jsonResp("Error", "Invalid manifest target or bound"),
            "404": jsonResp("Error", "Not found")
          }
        }
      },
      "/v1/projects/{id}/resource-link-migrations/{manifestId}/advance": {
        post: {
          operationId: "advanceProjectResourceLinkMigration",
          summary: "CAS-advance a manifest after reconciling exact producer or Projects evidence",
          parameters: [
            EXACT_PROJECT_ID_PARAM,
            { name: "manifestId", in: "path", required: true, schema: { type: "string", pattern: "^prlm_" } }
          ],
          requestBody: jsonBody("ProjectResourceLinkMigrationAdvanceRequest"),
          responses: {
            "200": jsonResp("ProjectResourceLinkMigrationResult"),
            "400": jsonResp("Error", "Invalid transition, receipt, readback, or bound"),
            "404": jsonResp("Error", "Not found")
          }
        }
      },
      "/v1/projects/{id}/resource-link-migrations/{manifestId}/rollback": {
        post: {
          operationId: "rollbackProjectResourceLinkMigration",
          summary: "Remove Projects references first, persist proof, then record producer rollback outcome",
          parameters: [
            EXACT_PROJECT_ID_PARAM,
            { name: "manifestId", in: "path", required: true, schema: { type: "string", pattern: "^prlm_" } }
          ],
          requestBody: jsonBody("ProjectResourceLinkMigrationRollbackRequest"),
          responses: {
            "200": jsonResp("ProjectResourceLinkMigrationResult"),
            "400": jsonResp("Error", "Ambiguous state, failed reference proof, stale transition, or bound"),
            "404": jsonResp("Error", "Not found")
          }
        }
      },
      "/v1/projects/{id}/contacts": {
        get: {
          operationId: "listProjectContacts",
          summary: "List Contacts-authoritative project memberships and compare synchronized Project resource links",
          parameters: [
            EXACT_PROJECT_ID_PARAM,
            { name: "max_items", in: "query", required: true, schema: { type: "integer", minimum: 1 } },
            { name: "response_byte_limit", in: "query", required: true, schema: { type: "integer", minimum: 1 } },
            { name: "time_budget_ms", in: "query", required: true, schema: { type: "integer", minimum: 1 } }
          ],
          responses: {
            "200": jsonResp("ProjectContactLinkListResult"),
            "400": jsonResp("Error", "Invalid target or collection bound"),
            "404": jsonResp("Error", "Not found"),
            "503": jsonResp("Error", "Contacts authority is not configured")
          }
        }
      },
      "/v1/projects/{id}/contacts/{contact_id}/attach": {
        post: {
          operationId: "attachProjectContact",
          summary: "Attach a Contact through Contacts-authoritative compensation-safe coordination",
          parameters: [
            EXACT_PROJECT_ID_PARAM,
            { name: "contact_id", in: "path", required: true, schema: { type: "string", pattern: COMPLETE_EXTERNAL_UUID_PATTERN } }
          ],
          requestBody: jsonBody("ProjectContactLinkMutationRequest"),
          responses: {
            "200": jsonResp("ProjectContactLinkMutationResult"),
            "400": jsonResp("Error", "Invalid target, operation, or bound"),
            "404": jsonResp("Error", "Not found"),
            "409": jsonResp("Error", "Contacts or Projects compare-and-swap conflict"),
            "503": jsonResp("Error", "Contacts authority is not configured")
          }
        }
      },
      "/v1/projects/{id}/contacts/{contact_id}/detach": {
        post: {
          operationId: "detachProjectContact",
          summary: "Detach a Contact through Contacts-authoritative compensation-safe coordination",
          parameters: [
            EXACT_PROJECT_ID_PARAM,
            { name: "contact_id", in: "path", required: true, schema: { type: "string", pattern: COMPLETE_EXTERNAL_UUID_PATTERN } }
          ],
          requestBody: jsonBody("ProjectContactLinkMutationRequest"),
          responses: {
            "200": jsonResp("ProjectContactLinkMutationResult"),
            "400": jsonResp("Error", "Invalid target, operation, or bound"),
            "404": jsonResp("Error", "Not found"),
            "409": jsonResp("Error", "Contacts or Projects compare-and-swap conflict"),
            "503": jsonResp("Error", "Contacts authority is not configured")
          }
        }
      },
      "/v1/projects/{id}/archive": {
        post: {
          operationId: "archiveProject",
          summary: "Archive a project",
          parameters: [ID_PARAM],
          responses: { "200": jsonResp("Workspace"), "404": jsonResp("Error", "Not found") }
        }
      },
      "/v1/projects/{id}/unarchive": {
        post: {
          operationId: "unarchiveProject",
          summary: "Unarchive a project",
          parameters: [ID_PARAM],
          responses: { "200": jsonResp("Workspace"), "404": jsonResp("Error", "Not found") }
        }
      },
      "/v1/projects/{id}/events": {
        get: {
          operationId: "listProjectEvents",
          summary: "List a project's events",
          parameters: [ID_PARAM, { name: "limit", in: "query", required: false, schema: { type: "integer" } }],
          responses: { "200": jsonResp("EventList"), "404": jsonResp("Error", "Not found") }
        },
        post: {
          operationId: "recordProjectEvent",
          summary: "Record a custom audit event for a project",
          parameters: [ID_PARAM],
          requestBody: jsonBody("RecordEvent"),
          responses: { "201": jsonResp("EventRecorded", "Created"), "400": jsonResp("Error", "Invalid"), "404": jsonResp("Error", "Not found") }
        }
      },
      "/v1/projects/{id}/locations": {
        get: {
          operationId: "listProjectLocations",
          summary: "List a project's registered folder locations",
          parameters: [ID_PARAM],
          responses: { "200": jsonResp("LocationList"), "404": jsonResp("Error", "Not found") }
        },
        post: {
          operationId: "addProjectLocation",
          summary: "Register an extra folder location for a project",
          parameters: [ID_PARAM],
          requestBody: jsonBody("AddWorkspaceLocation"),
          responses: { "201": jsonResp("LocationAdded", "Created"), "400": jsonResp("Error", "Invalid"), "404": jsonResp("Error", "Not found") }
        }
      },
      "/v1/projects/{id}/agents": {
        get: {
          operationId: "listProjectAgents",
          summary: "List a project's agent assignments",
          parameters: [ID_PARAM],
          responses: { "200": jsonResp("AgentAssignmentList"), "404": jsonResp("Error", "Not found") }
        },
        post: {
          operationId: "assignProjectAgent",
          summary: "Assign a registered agent to a project role",
          parameters: [ID_PARAM],
          requestBody: jsonBody("AssignWorkspaceAgent"),
          responses: { "201": jsonResp("AgentAssignment", "Created"), "400": jsonResp("Error", "Invalid"), "404": jsonResp("Error", "Not found") }
        }
      },
      "/v1/locks": {
        get: {
          operationId: "listLocks",
          summary: "List active project mutation locks",
          responses: { "200": jsonResp("LockList") }
        },
        post: {
          operationId: "acquireLock",
          summary: "Acquire a project mutation lock",
          requestBody: jsonBody("AcquireWorkspaceLock"),
          responses: { "201": jsonResp("Lock", "Created"), "400": jsonResp("Error", "Invalid or held") }
        }
      },
      "/v1/locks/{key}": {
        delete: {
          operationId: "releaseLock",
          summary: "Release a project mutation lock (holder-scoped by lock id; key-only DELETE is the force path)",
          parameters: [{
            name: "key",
            in: "path",
            required: true,
            description: "Lock key",
            schema: { type: "string" }
          }, {
            name: "lock_id",
            in: "query",
            required: false,
            description: "The acquired lock's unique id. When present, releases ONLY that holder's row (a stale holder cannot delete a successor's lock). When absent, the delete is the named force-release path used by the admin unlock verbs.",
            schema: { type: "string" }
          }],
          responses: { "200": jsonResp("LockRelease"), "404": jsonResp("Error", "Not found") }
        }
      },
      "/v1/roots": {
        get: {
          operationId: "listRoots",
          summary: "List roots",
          responses: { "200": jsonResp("RootList") }
        },
        post: {
          operationId: "createRoot",
          summary: "Create a root",
          requestBody: jsonBody("CreateRoot"),
          responses: { "201": jsonResp("Root", "Created"), "400": jsonResp("Error", "Invalid") }
        }
      },
      "/v1/roots/{id}": {
        get: {
          operationId: "getRoot",
          summary: "Get a root by id or slug",
          parameters: [ID_PARAM],
          responses: { "200": jsonResp("Root"), "404": jsonResp("Error", "Not found") }
        },
        patch: {
          operationId: "updateRoot",
          summary: "Update a root",
          parameters: [ID_PARAM],
          requestBody: jsonBody("UpdateRoot"),
          responses: { "200": jsonResp("Root"), "404": jsonResp("Error", "Not found") }
        },
        delete: {
          operationId: "deleteRoot",
          summary: "Delete a root",
          parameters: [
            ID_PARAM,
            { name: "detach", in: "query", required: false, schema: { type: "boolean" } }
          ],
          responses: { "200": jsonResp("DeleteResult"), "404": jsonResp("Error", "Not found") }
        }
      },
      "/v1/agents": {
        get: {
          operationId: "listAgents",
          summary: "List agents",
          responses: { "200": jsonResp("AgentList") }
        },
        post: {
          operationId: "createAgent",
          summary: "Create an agent",
          requestBody: jsonBody("CreateAgent"),
          responses: { "201": jsonResp("Agent", "Created"), "400": jsonResp("Error", "Invalid") }
        }
      },
      "/v1/agents/{id}": {
        get: {
          operationId: "getAgent",
          summary: "Get an agent by id or slug",
          parameters: [ID_PARAM],
          responses: { "200": jsonResp("Agent"), "404": jsonResp("Error", "Not found") }
        }
      },
      "/v1/machines": {
        get: {
          operationId: "listMachines",
          summary: "List canonical machines in the registry",
          responses: { "200": jsonResp("MachineList") }
        }
      },
      "/v1/recipes": {
        get: {
          operationId: "listRecipes",
          summary: "List recipes",
          responses: { "200": jsonResp("RecipeList") }
        },
        post: {
          operationId: "createRecipe",
          summary: "Create a recipe",
          requestBody: jsonBody("CreateRecipe"),
          responses: { "201": jsonResp("Recipe", "Created"), "400": jsonResp("Error", "Invalid") }
        }
      },
      "/v1/recipes/{id}": {
        get: {
          operationId: "getRecipe",
          summary: "Get a recipe by id or slug",
          parameters: [ID_PARAM],
          responses: { "200": jsonResp("Recipe"), "404": jsonResp("Error", "Not found") }
        }
      },
      "/v1/project-registration/manifests": {
        post: {
          operationId: "createProjectRegistrationManifest",
          summary: "Create or read the immutable manifest for one full-registration operation",
          requestBody: jsonBody("ProjectRegistrationManifestCreate"),
          responses: {
            "200": jsonResp("ProjectRegistrationManifestResult"),
            "400": jsonResp("Error", "Invalid"),
            "409": jsonResp("Error", "The operation id already has a manifest with different semantics")
          }
        }
      },
      "/v1/project-registration/manifests/{operation_id}": {
        get: {
          operationId: "readProjectRegistrationManifest",
          summary: "Read one operation's registration manifest",
          parameters: [OPERATION_ID_PARAM],
          responses: { "200": jsonResp("ProjectRegistrationManifestRead") }
        }
      },
      "/v1/project-registration/receipts": {
        get: {
          operationId: "lookupProjectRegistrationReceipt",
          summary: "Look up the single terminal receipt for one registration step",
          parameters: [
            { name: "operation_id", in: "query", required: true, schema: { type: "string" } },
            { name: "step_id", in: "query", required: true, schema: { type: "string" } },
            { name: "direction", in: "query", required: true, schema: { type: "string", enum: ["forward", "inverse"] } },
            { name: "idempotency_key", in: "query", required: true, schema: { type: "string" } },
            { name: "max_items", in: "query", required: true, schema: { type: "integer", enum: [1] } },
            { name: "response_byte_limit", in: "query", required: true, schema: { type: "integer", minimum: 1 } },
            { name: "time_budget_ms", in: "query", required: true, schema: { type: "integer", minimum: 1 } }
          ],
          responses: {
            "200": jsonResp("ProjectRegistrationReceiptLookup"),
            "409": jsonResp("Error", "The step does not resolve to exactly one terminal receipt")
          }
        },
        post: {
          operationId: "appendProjectRegistrationReceipt",
          summary: "Append one immutable registration receipt (idempotent by content)",
          requestBody: jsonBody("ProjectRegistrationReceiptAppend"),
          responses: {
            "200": jsonResp("ProjectRegistrationReceiptResult"),
            "400": jsonResp("Error", "Invalid"),
            "409": jsonResp("Error", "The step was already accepted with different semantics")
          }
        }
      },
      "/v1/project-registration/operations/{operation_id}/receipts": {
        get: {
          operationId: "listProjectRegistrationReceipts",
          summary: "List an operation's receipts in sequence order, or its accepted step receipts",
          parameters: [
            OPERATION_ID_PARAM,
            { name: "step_id", in: "query", required: false, schema: { type: "string" } },
            { name: "direction", in: "query", required: false, schema: { type: "string", enum: ["forward", "inverse"] } },
            { name: "outcome", in: "query", required: false, schema: { type: "string", enum: ["accepted"] } },
            { name: "limit", in: "query", required: false, schema: { type: "integer", minimum: 1 } }
          ],
          responses: { "200": jsonResp("ProjectRegistrationReceiptList") }
        }
      }
    }
  };
}

// src/lib/project-contact-links.ts
var PROJECT_CONTACT_RESOURCE_LINK_TYPE = {
  authority: "contacts",
  source_package: "@hasna/contacts",
  target_kind: "contact",
  locator_kind: "external_uuid",
  scope: "resource"
};
var PROJECT_CONTACT_LINK_STEPS = {
  contactsMembership: "contacts-membership",
  projectsResourceLink: "projects-resource-link"
};

class ProjectContactLinkOperationError extends Error {
  code;
  stage;
  compensated;
  cause;
  compensation_error;
  constructor(input) {
    const causeMessage = input.cause instanceof Error ? input.cause.message : String(input.cause);
    const suffix = input.compensation_error ? `; compensation failed: ${input.compensation_error instanceof Error ? input.compensation_error.message : String(input.compensation_error)}` : input.compensated ? "; authoritative membership was restored" : "";
    super(`${input.code} at ${input.stage}: ${causeMessage}${suffix}`);
    this.name = "ProjectContactLinkOperationError";
    this.code = input.code;
    this.stage = input.stage;
    this.compensated = input.compensated;
    this.cause = input.cause;
    this.compensation_error = input.compensation_error ?? null;
  }
}
function uniqueSorted(values) {
  return [...new Set(values)].sort((a, b) => a.localeCompare(b));
}
function contactsMembershipStepId(direction, expectedVersion) {
  return `${PROJECT_CONTACT_LINK_STEPS.contactsMembership}:${direction}:${sha256(expectedVersion).slice(0, 16)}`;
}
function projectContactResourceLink(serviceInstance, contactId, labels) {
  return normalizeProjectResourceLink({
    authority: PROJECT_CONTACT_RESOURCE_LINK_TYPE.authority,
    service_instance: serviceInstance,
    source_package: PROJECT_CONTACT_RESOURCE_LINK_TYPE.source_package,
    target_kind: PROJECT_CONTACT_RESOURCE_LINK_TYPE.target_kind,
    locator: {
      kind: PROJECT_CONTACT_RESOURCE_LINK_TYPE.locator_kind,
      value: contactId
    },
    scope: PROJECT_CONTACT_RESOURCE_LINK_TYPE.scope,
    labels
  });
}
function isProjectContactLink(link, serviceInstance, contactId) {
  let sameServiceInstance = false;
  try {
    sameServiceInstance = canonicalProjectResourceLinkUri(link.service_instance, "project contact link service_instance") === canonicalProjectResourceLinkUri(serviceInstance, "Contacts authority service_instance");
  } catch {
    return false;
  }
  return link.authority === PROJECT_CONTACT_RESOURCE_LINK_TYPE.authority && link.source_package === PROJECT_CONTACT_RESOURCE_LINK_TYPE.source_package && link.target_kind === PROJECT_CONTACT_RESOURCE_LINK_TYPE.target_kind && sameServiceInstance && link.locator.kind === PROJECT_CONTACT_RESOURCE_LINK_TYPE.locator_kind && (contactId === undefined || link.locator.value === contactId);
}
function resourceLinkInput(link) {
  const { id: _id, project_id: _projectId, created_at: _createdAt, updated_at: _updatedAt, ...input } = link;
  return input;
}
function acceptedProjectMutation(result2) {
  if (!result2.ok || !result2.after || result2.outcome !== "accepted" && result2.outcome !== "duplicate_of_accepted") {
    throw new Error(`Projects resource-link mutation was not accepted: ${result2.outcome}${result2.receipt?.reason ? ` (${result2.receipt.reason})` : ""}`);
  }
  return result2;
}
function projectEvidence(result2) {
  return {
    system: "projects",
    step_id: PROJECT_CONTACT_LINK_STEPS.projectsResourceLink,
    outcome: result2.outcome,
    receipt_id: result2.receipt?.receipt_id ?? null,
    compensated: false
  };
}
function contactsEvidence(result2, compensated = false) {
  return {
    system: "contacts",
    step_id: result2.step_id,
    outcome: result2.outcome,
    receipt_id: result2.receipt_id,
    compensated
  };
}
async function compensateContacts(direction, dependencies, input, contactId, expectedVersion) {
  const mutation = direction === "attach" ? dependencies.contacts.attach.bind(dependencies.contacts) : dependencies.contacts.detach.bind(dependencies.contacts);
  return mutation({
    contact_id: contactId,
    project_id: input.project_id,
    operation_id: input.operation_id,
    step_id: contactsMembershipStepId("compensate", expectedVersion),
    expected_version: expectedVersion
  });
}
async function listProjectContacts(dependencies, input) {
  const [membership, projectRead] = await Promise.all([
    dependencies.contacts.listProjectMemberships({
      project_id: input.project_id,
      max_items: input.max_items
    }),
    dependencies.projects.readProjectResourceLinks({
      project_id: input.project_id,
      max_items: input.max_items,
      response_byte_limit: input.response_byte_limit,
      time_budget_ms: input.time_budget_ms
    })
  ]);
  const projectLinks = projectRead.links.filter((link) => isProjectContactLink(link, dependencies.contacts.service_instance));
  const contactIds = uniqueSorted(membership.contact_ids);
  const projectContactIds = uniqueSorted(projectLinks.map((link) => link.locator.value));
  const authoritySet = new Set(contactIds);
  const projectSet = new Set(projectContactIds);
  return {
    ok: true,
    authority: "contacts",
    project_id: input.project_id,
    membership_revision: membership.membership_revision,
    project_revision: projectRead.current_revision,
    contact_ids: contactIds,
    synchronized_contact_ids: contactIds.filter((id) => projectSet.has(id)),
    missing_project_link_contact_ids: contactIds.filter((id) => !projectSet.has(id)),
    stale_project_link_contact_ids: projectContactIds.filter((id) => !authoritySet.has(id)),
    project_links: projectLinks
  };
}
async function attachProjectContact(dependencies, input) {
  const desiredLink = projectContactResourceLink(dependencies.contacts.service_instance, input.contact_id, input.labels);
  const [membershipBefore, projectRead] = await Promise.all([
    dependencies.contacts.readMembership({
      contact_id: input.contact_id,
      project_id: input.project_id
    }),
    dependencies.projects.readProjectResourceLinks({
      project_id: input.project_id,
      max_items: input.max_items,
      response_byte_limit: input.response_byte_limit,
      time_budget_ms: input.time_budget_ms
    })
  ]);
  const existingLink = projectRead.links.find((link) => isProjectContactLink(link, dependencies.contacts.service_instance, desiredLink.locator.value));
  if (membershipBefore.linked && existingLink) {
    return {
      ok: true,
      outcome: "duplicate_of_accepted",
      authority: "contacts",
      project_id: input.project_id,
      contact_id: desiredLink.locator.value,
      membership: membershipBefore,
      project_link: existingLink,
      evidence: []
    };
  }
  let membershipAfter = membershipBefore;
  let membershipMutation = null;
  if (!membershipBefore.linked) {
    try {
      membershipMutation = await dependencies.contacts.attach({
        contact_id: desiredLink.locator.value,
        project_id: input.project_id,
        operation_id: input.operation_id,
        step_id: contactsMembershipStepId("forward", membershipBefore.version),
        expected_version: membershipBefore.version
      });
      membershipAfter = membershipMutation.after;
    } catch (cause) {
      throw new ProjectContactLinkOperationError({
        code: "PROJECT_CONTACT_LINK_CONTACTS_WRITE_FAILED",
        stage: PROJECT_CONTACT_LINK_STEPS.contactsMembership,
        compensated: false,
        cause
      });
    }
  }
  let rawProjectMutation;
  try {
    rawProjectMutation = await dependencies.projects.mutateProjectResourceLinks({
      project_id: input.project_id,
      operation_id: input.operation_id,
      step_id: PROJECT_CONTACT_LINK_STEPS.projectsResourceLink,
      mode: "add",
      expected_revision: projectRead.current_revision,
      links: [desiredLink],
      max_items: input.max_items,
      response_byte_limit: input.response_byte_limit,
      time_budget_ms: input.time_budget_ms,
      agent_id: input.agent_id,
      source: input.source,
      command: input.command
    });
  } catch (cause) {
    throw new ProjectContactLinkOperationError({
      code: "PROJECT_CONTACT_LINK_PARTIAL_FAILURE",
      stage: PROJECT_CONTACT_LINK_STEPS.projectsResourceLink,
      compensated: false,
      cause
    });
  }
  let projectMutation;
  try {
    projectMutation = acceptedProjectMutation(rawProjectMutation);
  } catch (cause) {
    if (!membershipMutation || membershipBefore.linked) {
      throw new ProjectContactLinkOperationError({
        code: "PROJECT_CONTACT_LINK_PROJECT_WRITE_FAILED",
        stage: PROJECT_CONTACT_LINK_STEPS.projectsResourceLink,
        compensated: false,
        cause
      });
    }
    try {
      await compensateContacts("detach", dependencies, input, desiredLink.locator.value, membershipAfter.version);
      throw new ProjectContactLinkOperationError({
        code: "PROJECT_CONTACT_LINK_PROJECT_WRITE_FAILED_COMPENSATED",
        stage: PROJECT_CONTACT_LINK_STEPS.projectsResourceLink,
        compensated: true,
        cause
      });
    } catch (compensationError) {
      if (compensationError instanceof ProjectContactLinkOperationError && compensationError.code === "PROJECT_CONTACT_LINK_PROJECT_WRITE_FAILED_COMPENSATED") {
        throw compensationError;
      }
      throw new ProjectContactLinkOperationError({
        code: "PROJECT_CONTACT_LINK_PARTIAL_FAILURE",
        stage: `${PROJECT_CONTACT_LINK_STEPS.contactsMembership}:compensate`,
        compensated: false,
        cause,
        compensation_error: compensationError
      });
    }
  }
  const projectLink = projectMutation.after.links.find((link) => isProjectContactLink(link, dependencies.contacts.service_instance, desiredLink.locator.value)) ?? null;
  return {
    ok: true,
    outcome: projectMutation.outcome === "duplicate_of_accepted" && !membershipMutation ? "duplicate_of_accepted" : "accepted",
    authority: "contacts",
    project_id: input.project_id,
    contact_id: desiredLink.locator.value,
    membership: membershipAfter,
    project_link: projectLink,
    evidence: [
      ...membershipMutation ? [contactsEvidence(membershipMutation)] : [],
      projectEvidence(projectMutation)
    ]
  };
}
async function detachProjectContact(dependencies, input) {
  const normalized = projectContactResourceLink(dependencies.contacts.service_instance, input.contact_id, input.labels);
  const [membershipBefore, projectRead] = await Promise.all([
    dependencies.contacts.readMembership({
      contact_id: normalized.locator.value,
      project_id: input.project_id
    }),
    dependencies.projects.readProjectResourceLinks({
      project_id: input.project_id,
      max_items: input.max_items,
      response_byte_limit: input.response_byte_limit,
      time_budget_ms: input.time_budget_ms
    })
  ]);
  const existingLink = projectRead.links.find((link) => isProjectContactLink(link, dependencies.contacts.service_instance, normalized.locator.value));
  if (!membershipBefore.linked && !existingLink) {
    return {
      ok: true,
      outcome: "duplicate_of_accepted",
      authority: "contacts",
      project_id: input.project_id,
      contact_id: normalized.locator.value,
      membership: membershipBefore,
      project_link: null,
      evidence: []
    };
  }
  let membershipAfter = membershipBefore;
  let membershipMutation = null;
  if (membershipBefore.linked) {
    try {
      membershipMutation = await dependencies.contacts.detach({
        contact_id: normalized.locator.value,
        project_id: input.project_id,
        operation_id: input.operation_id,
        step_id: contactsMembershipStepId("forward", membershipBefore.version),
        expected_version: membershipBefore.version
      });
      membershipAfter = membershipMutation.after;
    } catch (cause) {
      throw new ProjectContactLinkOperationError({
        code: "PROJECT_CONTACT_LINK_CONTACTS_WRITE_FAILED",
        stage: PROJECT_CONTACT_LINK_STEPS.contactsMembership,
        compensated: false,
        cause
      });
    }
  }
  let projectMutation = null;
  if (existingLink) {
    const desired = projectRead.links.filter((link) => link.id !== existingLink.id).map(resourceLinkInput);
    let rawProjectMutation;
    try {
      rawProjectMutation = await dependencies.projects.mutateProjectResourceLinks({
        project_id: input.project_id,
        operation_id: input.operation_id,
        step_id: PROJECT_CONTACT_LINK_STEPS.projectsResourceLink,
        mode: "reconcile",
        expected_revision: projectRead.current_revision,
        links: desired,
        max_items: input.max_items,
        response_byte_limit: input.response_byte_limit,
        time_budget_ms: input.time_budget_ms,
        agent_id: input.agent_id,
        source: input.source,
        command: input.command
      });
    } catch (cause) {
      throw new ProjectContactLinkOperationError({
        code: "PROJECT_CONTACT_LINK_PARTIAL_FAILURE",
        stage: PROJECT_CONTACT_LINK_STEPS.projectsResourceLink,
        compensated: false,
        cause
      });
    }
    try {
      projectMutation = acceptedProjectMutation(rawProjectMutation);
    } catch (cause) {
      if (!membershipMutation || !membershipBefore.linked) {
        throw new ProjectContactLinkOperationError({
          code: "PROJECT_CONTACT_LINK_PROJECT_WRITE_FAILED",
          stage: PROJECT_CONTACT_LINK_STEPS.projectsResourceLink,
          compensated: false,
          cause
        });
      }
      try {
        await compensateContacts("attach", dependencies, input, normalized.locator.value, membershipAfter.version);
        throw new ProjectContactLinkOperationError({
          code: "PROJECT_CONTACT_LINK_PROJECT_WRITE_FAILED_COMPENSATED",
          stage: PROJECT_CONTACT_LINK_STEPS.projectsResourceLink,
          compensated: true,
          cause
        });
      } catch (compensationError) {
        if (compensationError instanceof ProjectContactLinkOperationError && compensationError.code === "PROJECT_CONTACT_LINK_PROJECT_WRITE_FAILED_COMPENSATED") {
          throw compensationError;
        }
        throw new ProjectContactLinkOperationError({
          code: "PROJECT_CONTACT_LINK_PARTIAL_FAILURE",
          stage: `${PROJECT_CONTACT_LINK_STEPS.contactsMembership}:compensate`,
          compensated: false,
          cause,
          compensation_error: compensationError
        });
      }
    }
  }
  return {
    ok: true,
    outcome: projectMutation || membershipMutation ? "accepted" : "duplicate_of_accepted",
    authority: "contacts",
    project_id: input.project_id,
    contact_id: normalized.locator.value,
    membership: membershipAfter,
    project_link: null,
    evidence: [
      ...membershipMutation ? [contactsEvidence(membershipMutation)] : [],
      ...projectMutation ? [projectEvidence(projectMutation)] : []
    ]
  };
}

// src/lib/contacts-authority-adapter.ts
import { resolveClientTransport, resolveCredential as resolveCredential2 } from "@hasna/contracts/client";
class ContactsAuthorityHttpError extends Error {
  status;
  method;
  path;
  constructor(input) {
    super(`Contacts authority ${input.method} ${input.path} failed: ${input.detail}`);
    this.name = "ContactsAuthorityHttpError";
    this.status = input.status;
    this.method = input.method;
    this.path = input.path;
  }
}
function required(value, label) {
  const normalized = value?.trim();
  if (!normalized)
    throw new Error(`projects contacts adapter: set ${label}`);
  return normalized;
}
function v1BaseUrl(value) {
  const url = new URL(value);
  if (url.protocol !== "http:" && url.protocol !== "https:") {
    throw new Error("projects contacts adapter: API URL must use http or https");
  }
  const path = url.pathname.replace(/\/+$/, "");
  url.pathname = path.endsWith("/v1") ? path : `${path}/v1`;
  url.search = "";
  url.hash = "";
  return url.toString().replace(/\/+$/, "");
}
function defaultServiceInstance(value) {
  const url = new URL(value);
  url.pathname = "";
  url.search = "";
  url.hash = "";
  return canonicalProjectResourceLinkUri(url.toString(), "projects contacts adapter service instance");
}
async function responseJson(response, method, path) {
  const text = await response.text();
  let body = undefined;
  if (text) {
    try {
      body = JSON.parse(text);
    } catch {
      body = text;
    }
  }
  if (!response.ok) {
    const detail = body && typeof body === "object" && "error" in body ? String(body.error) : `${response.status}`;
    throw new ContactsAuthorityHttpError({
      status: response.status,
      method,
      path,
      detail
    });
  }
  return body;
}

class ContactsHttpProjectMembershipAuthority {
  service_instance;
  baseUrl;
  apiKey;
  fetchImpl;
  constructor(options) {
    this.baseUrl = v1BaseUrl(required(options.baseUrl, "HASNA_CONTACTS_API_URL"));
    this.apiKey = required(options.apiKey, "HASNA_CONTACTS_API_KEY");
    this.service_instance = options.serviceInstance ? canonicalProjectResourceLinkUri(options.serviceInstance.trim(), "projects contacts adapter service instance") : defaultServiceInstance(this.baseUrl);
    this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
  }
  async request(method, path, query2, body) {
    const url = new URL(`${this.baseUrl}${path}`);
    for (const [key, value] of Object.entries(query2 ?? {})) {
      url.searchParams.set(key, String(value));
    }
    const headers = {
      accept: "application/json",
      authorization: `Bearer ${this.apiKey}`
    };
    const init = { method, headers };
    if (body !== undefined) {
      headers["content-type"] = "application/json";
      init.body = JSON.stringify(body);
    }
    return responseJson(await this.fetchImpl(url.toString(), init), method, path);
  }
  readMembership(input) {
    return this.request("GET", `/projects/${encodeURIComponent(input.project_id)}/contact-memberships/${encodeURIComponent(input.contact_id)}`);
  }
  listProjectMemberships(input) {
    return this.request("GET", `/projects/${encodeURIComponent(input.project_id)}/contact-memberships`, { max_items: input.max_items });
  }
  attach(input) {
    return this.mutate("attach", input);
  }
  detach(input) {
    return this.mutate("detach", input);
  }
  mutate(direction, input) {
    return this.request("POST", `/projects/${encodeURIComponent(input.project_id)}/contact-memberships/${encodeURIComponent(input.contact_id)}/${direction}`, undefined, {
      operation_id: input.operation_id,
      step_id: input.step_id,
      expected_version: input.expected_version
    });
  }
}
function createContactsProjectMembershipAuthorityFromEnv(env2 = process.env, fetchImpl) {
  const resolution = resolveClientTransport("contacts", env2);
  const credential = resolveCredential2("contacts", env2);
  const serviceInstance = env2.HASNA_CONTACTS_SERVICE_INSTANCE ?? env2.CONTACTS_SERVICE_INSTANCE;
  return new ContactsHttpProjectMembershipAuthority({
    baseUrl: required(resolution.baseUrl ?? undefined, "HASNA_CONTACTS_API_URL (or CONTACTS_API_URL)"),
    apiKey: required(credential?.apiKey, "HASNA_CONTACTS_API_KEY (or CONTACTS_API_KEY)"),
    ...serviceInstance ? { serviceInstance } : {},
    ...fetchImpl ? { fetchImpl } : {}
  });
}

// src/lib/project-list-output.ts
var PROJECT_QUERY_SCOPES = ["identity", "discovery", "structured", "all"];
var PROJECT_LIST_FIELDS = [
  "id",
  "slug",
  "name",
  "status",
  "kind",
  "path",
  "canonical_machine",
  "root_id",
  "recipe_id",
  "git_remote",
  "updated_at"
];
var DEFAULT_PROJECT_LIST_MAX_BYTES = 32 * 1024;
var MAX_PROJECT_LIST_MAX_BYTES = 256 * 1024;
var MAX_PROJECT_QUERY_LENGTH = 512;
var MAX_PROJECT_QUERY_TAGS = 50;
var MAX_PROJECT_QUERY_TAG_LENGTH = 128;
var PROJECT_LIST_V2_CONTRACT = "projects.list.v2";
var PROJECT_LIST_FIELD_SET = new Set(PROJECT_LIST_FIELDS);
var PROJECT_QUERY_SCOPE_SET = new Set(PROJECT_QUERY_SCOPES);
function isProjectQueryScope(value) {
  return PROJECT_QUERY_SCOPE_SET.has(value);
}

// src/serve/app.ts
var READ_SCOPE = "projects:read";
var WRITE_SCOPE = "projects:write";
function jsonResponse(body, status = 200, extraHeaders = {}) {
  return new Response(JSON.stringify(body), {
    status,
    headers: { "content-type": "application/json", ...extraHeaders }
  });
}
function boundedJsonResponse(body, bounds3, startedAtMs, status = 200) {
  const payload = {
    ...body && typeof body === "object" && !Array.isArray(body) ? body : { data: body }
  };
  payload["response_control"] = responseControl(payload, bounds3, startedAtMs);
  return jsonResponse(payload, status);
}
function guardedJsonResponse(body, bounds3, startedAtMs, status = 200) {
  if (body && typeof body === "object" && !Array.isArray(body) && "response_control" in body) {
    return jsonResponse(body, status);
  }
  return boundedJsonResponse(body, bounds3, startedAtMs, status);
}
function errorResponse(message, status, reason) {
  return jsonResponse(reason ? { error: message, reason } : { error: message }, status);
}
function statusForError(err) {
  if (err instanceof NotFoundError)
    return 404;
  if (err instanceof ProjectRegistrationLedgerError)
    return err.status;
  if (err instanceof ValidationError)
    return 400;
  if (err instanceof ContactsAuthorityHttpError)
    return err.status;
  if (err instanceof ProjectContactLinkOperationError) {
    const causeStatus = statusForError(err.cause);
    if (causeStatus !== 500)
      return causeStatus;
    if (err.cause instanceof Error && /(not accepted|revision|precondition|conflict|expected[_ ]version)/i.test(err.cause.message)) {
      return 409;
    }
    return 502;
  }
  return 500;
}
function toBool(value) {
  return value === "1" || value === "true" || value === "yes";
}
async function readJsonBody(req) {
  const text = await req.text();
  if (!text.trim())
    return {};
  try {
    const parsed = JSON.parse(text);
    if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
      return parsed;
    throw new ValidationError("request body must be a JSON object");
  } catch (err) {
    if (err instanceof ValidationError)
      throw err;
    throw new ValidationError("invalid JSON body");
  }
}
function createFetchHandler(options) {
  const { store, version, contacts } = options;
  const projectionPolicy = validateProjectionPolicy(options.projectionPolicy);
  const appName = options.app ?? "projects";
  const verifier = verifyApiKey({
    app: appName,
    signingSecret: options.signingSecret,
    ...options.keyStatus ? { keyStatus: options.keyStatus } : {},
    ...options.allowUnregisteredKeys ? { allowUnregisteredKeys: true } : {},
    ...options.audit ? { audit: options.audit } : {}
  });
  return async function handle(req) {
    const url = new URL(req.url);
    const path = url.pathname.replace(/\/+$/, "") || "/";
    const method = req.method.toUpperCase();
    if (path === "/health" && method === "GET") {
      return jsonResponse({ status: "ok", version });
    }
    if (path === "/version" && method === "GET") {
      return jsonResponse({ status: "ok", version });
    }
    if (path === "/ready" && method === "GET") {
      try {
        const ok = await store.ping();
        return ok ? jsonResponse({ status: "ready", version }) : jsonResponse({ status: "degraded", version }, 503);
      } catch {
        return jsonResponse({ status: "unavailable", version }, 503);
      }
    }
    if (path === "/openapi.json" && method === "GET") {
      return jsonResponse(buildOpenApiSpec(version));
    }
    if (path === "/" && method === "GET") {
      return jsonResponse({ name: `${appName}-serve`, version, openapi: "/openapi.json" });
    }
    if (!path.startsWith("/v1/")) {
      return errorResponse("Not found", 404);
    }
    const requiredScopes = method === "GET" ? [READ_SCOPE] : [WRITE_SCOPE];
    const decision = await verifier.authenticate(req.headers, { method, path, requiredScopes });
    if (!decision.ok) {
      return errorResponse(decision.message, decision.status, decision.reason);
    }
    const projectionPath = /^\/v1\/projects\/([^/]+)\/product-projections(?:\/([^/]+))?$/.exec(path);
    if (projectionPath) {
      try {
        const projectId = projectionPath[1];
        const receiptId = projectionPath[2];
        if (method === "POST" && !receiptId) {
          authorizeProjection(projectionPolicy, decision.principal, projectId, "issue");
          return jsonResponse(await store.issueProductProjection(projectionPolicy, decision.principal, projectId, await readProjectionBody(req)), 201);
        }
        if (method === "GET" && receiptId) {
          authorizeProjection(projectionPolicy, decision.principal, projectId, "read");
          const q = url.searchParams;
          if ([...q.keys()].some((k) => !["response_byte_limit", "time_budget_ms"].includes(k)) || q.getAll("response_byte_limit").length !== 1 || q.getAll("time_budget_ms").length !== 1)
            throw new ProjectionError(400, "INVALID_PROJECTION_REQUEST");
          return jsonResponse(await store.readProductProjection(projectionPolicy, decision.principal, projectId, receiptId, {
            response_byte_limit: Number(q.get("response_byte_limit")),
            time_budget_ms: Number(q.get("time_budget_ms"))
          }));
        }
        return errorResponse("PROJECTION_METHOD_NOT_ALLOWED", 405);
      } catch (error) {
        return errorResponse(error instanceof ProjectionError ? error.code : "PROJECTION_REQUEST_REFUSED", error instanceof ProjectionError ? error.status : 422);
      }
    }
    try {
      return await route(req, url, path, method, store, contacts);
    } catch (err) {
      const status = statusForError(err);
      const message = err instanceof Error ? err.message : "internal error";
      if (status === 500)
        console.error("projects-serve error:", err);
      return errorResponse(message, status, err instanceof ProjectRegistrationLedgerError ? err.reason : undefined);
    }
  };
}
function requiredText(value, label) {
  if (typeof value !== "string" || value.length === 0) {
    throw new ValidationError(`${label} must be a non-empty string`);
  }
  return value;
}
function optionalText(value, label) {
  if (value === undefined || value === null)
    return null;
  if (typeof value !== "string")
    throw new ValidationError(`${label} must be a string`);
  return value;
}
function jsonObjectField(value, label) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    throw new ValidationError(`${label} must be a JSON object`);
  }
  return value;
}
function optionalObjectArray(value, label) {
  if (value === undefined || value === null)
    return [];
  if (!Array.isArray(value))
    throw new ValidationError(`${label} must be an array`);
  return value.map((item) => jsonObjectField(item, `${label} entry`));
}
function registrationDirection(value) {
  const direction = requiredText(value, "direction");
  if (direction !== "forward" && direction !== "inverse") {
    throw new ValidationError("direction must be forward or inverse");
  }
  return direction;
}
function registrationOutcome(value) {
  const outcome = requiredText(value, "outcome");
  if (outcome !== "accepted" && outcome !== "duplicate_of_accepted" && outcome !== "terminal_nonacceptance") {
    throw new ValidationError("outcome must be accepted, duplicate_of_accepted or terminal_nonacceptance");
  }
  return outcome;
}
function requiredQuery(url, keys) {
  const q = url.searchParams;
  for (const key of q.keys()) {
    if (!keys.includes(key))
      throw new ValidationError(`unexpected query parameter '${key}'`);
  }
  for (const key of keys) {
    if (q.getAll(key).length !== 1) {
      throw new ValidationError(`query parameter '${key}' must be provided exactly once`);
    }
  }
  return q;
}
function positiveIntegerQuery(q, key) {
  const value = Number(q.get(key));
  if (!Number.isInteger(value) || value < 1) {
    throw new ValidationError(`query parameter '${key}' must be a positive integer`);
  }
  return value;
}
async function route(req, url, path, method, store, contacts) {
  const segments = path.split("/").filter(Boolean);
  const [, resource2, id, sub, extra, action] = segments;
  if (resource2 === "project-registration") {
    if (id === "manifests" && sub === undefined) {
      if (method === "POST") {
        const body = await readJsonBody(req);
        return jsonResponse(await store.createProjectRegistrationManifest({
          operation_id: requiredText(body.operation_id, "operation_id"),
          request_digest: requiredText(body.request_digest, "request_digest"),
          project_id: requiredText(body.project_id, "project_id"),
          project_slug: requiredText(body.project_slug, "project_slug"),
          plan: jsonObjectField(body.plan, "plan")
        }));
      }
      return errorResponse("REGISTRATION_METHOD_NOT_ALLOWED", 405);
    }
    if (id === "manifests" && sub !== undefined && method === "GET") {
      return jsonResponse({ manifest: await store.readProjectRegistrationManifest(sub) });
    }
    if (id === "receipts" && sub === undefined && method === "POST") {
      const body = await readJsonBody(req);
      const receipt = await store.appendProjectRegistrationReceipt({
        operation_id: requiredText(body.operation_id, "operation_id"),
        step_id: requiredText(body.step_id, "step_id"),
        authority: requiredText(body.authority, "authority"),
        resource_kind: requiredText(body.resource_kind, "resource_kind"),
        direction: registrationDirection(body.direction),
        idempotency_key: requiredText(body.idempotency_key, "idempotency_key"),
        target_id: optionalText(body.target_id, "target_id"),
        request_digest: requiredText(body.request_digest, "request_digest"),
        precondition_digest: requiredText(body.precondition_digest, "precondition_digest"),
        outcome: registrationOutcome(body.outcome),
        reason: optionalText(body.reason, "reason"),
        result_revision: optionalText(body.result_revision, "result_revision"),
        result_digest: optionalText(body.result_digest, "result_digest"),
        duplicate_of_receipt_id: optionalText(body.duplicate_of_receipt_id, "duplicate_of_receipt_id"),
        authority_receipt: body.authority_receipt === undefined || body.authority_receipt === null ? null : jsonObjectField(body.authority_receipt, "authority_receipt"),
        artifacts: optionalObjectArray(body.artifacts, "artifacts"),
        preconditions: optionalObjectArray(body.preconditions, "preconditions"),
        rollback: optionalObjectArray(body.rollback, "rollback")
      });
      return jsonResponse({ receipt });
    }
    if (id === "receipts" && sub === undefined && method === "GET") {
      const q = requiredQuery(url, [
        "operation_id",
        "step_id",
        "direction",
        "idempotency_key",
        "max_items",
        "response_byte_limit",
        "time_budget_ms"
      ]);
      if (q.get("max_items") !== "1") {
        throw new ValidationError("query parameter 'max_items' must be exactly 1");
      }
      const lookup = await store.lookupProjectRegistrationReceipt({
        operation_id: requiredText(q.get("operation_id"), "operation_id"),
        step_id: requiredText(q.get("step_id"), "step_id"),
        direction: registrationDirection(q.get("direction")),
        idempotency_key: requiredText(q.get("idempotency_key"), "idempotency_key"),
        max_items: 1,
        response_byte_limit: positiveIntegerQuery(q, "response_byte_limit"),
        time_budget_ms: positiveIntegerQuery(q, "time_budget_ms")
      });
      return jsonResponse(lookup);
    }
    if (id === "operations" && sub !== undefined && extra === "receipts" && method === "GET") {
      const q = url.searchParams;
      for (const key of q.keys()) {
        if (!["step_id", "direction", "outcome", "limit"].includes(key)) {
          throw new ValidationError(`unexpected query parameter '${key}'`);
        }
      }
      const stepId = q.get("step_id");
      const direction = q.get("direction");
      const outcome = q.get("outcome");
      const limit = q.get("limit");
      if (stepId !== null || direction !== null || outcome !== null || limit !== null) {
        if (stepId === null || direction === null || outcome !== "accepted" || limit === null) {
          throw new ValidationError("a bounded receipt read requires step_id, direction, outcome=accepted and limit");
        }
        const bounded = Number(limit);
        if (!Number.isInteger(bounded) || bounded < 1) {
          throw new ValidationError("limit must be a positive integer");
        }
        return jsonResponse({
          receipts: await store.findProjectRegistrationReceipts({
            operation_id: sub,
            step_id: stepId,
            direction: registrationDirection(direction),
            limit: bounded
          })
        });
      }
      return jsonResponse({ receipts: await store.listProjectRegistrationReceipts(sub) });
    }
    return errorResponse("REGISTRATION_ROUTE_NOT_FOUND", 404);
  }
  if (resource2 === "projects") {
    if (!id) {
      if (method === "GET") {
        const q = url.searchParams;
        const rawQueryScope = q.get("query_scope");
        const additiveTags = q.getAll("tags");
        const usesV2Filters = rawQueryScope !== null || additiveTags.length > 0 || q.has("exclude_evals");
        const legacyTag = q.get("tag");
        const rawTags = usesV2Filters ? [...legacyTag ? [legacyTag] : [], ...additiveTags] : legacyTag ? [legacyTag] : [];
        if (usesV2Filters && rawTags.length > MAX_PROJECT_QUERY_TAGS) {
          throw new ValidationError(`at most ${MAX_PROJECT_QUERY_TAGS} project tags may be queried`);
        }
        const tags = [...new Set(rawTags.filter(Boolean))];
        if (usesV2Filters && tags.some((value) => value.length > MAX_PROJECT_QUERY_TAG_LENGTH)) {
          throw new ValidationError(`project query tags must be at most ${MAX_PROJECT_QUERY_TAG_LENGTH} characters`);
        }
        const query2 = q.get("query");
        if (usesV2Filters && query2 && query2.length > MAX_PROJECT_QUERY_LENGTH) {
          throw new ValidationError(`query must be at most ${MAX_PROJECT_QUERY_LENGTH} characters`);
        }
        let queryScope;
        if (rawQueryScope) {
          if (!isProjectQueryScope(rawQueryScope)) {
            throw new ValidationError("query_scope must be one of: identity, discovery, structured, all");
          }
          queryScope = rawQueryScope;
        }
        const includeFixtures = q.get("include_fixtures") === "true";
        const excludeEvals = q.get("exclude_evals") === "true";
        const filter = {
          ...q.get("status") ? { status: q.get("status") } : {},
          ...q.get("kind") ? { kind: q.get("kind") } : {},
          ...q.get("root_id") ? { root_id: q.get("root_id") } : {},
          ...query2 ? { query: query2 } : {},
          ...queryScope ? { query_scope: queryScope } : {},
          ...tags.length ? { tags } : {},
          ...includeFixtures ? {} : { exclude_registry_fixtures: true },
          ...excludeEvals ? { exclude_eval_artifacts: true } : {},
          ...q.get("limit") ? { limit: Number(q.get("limit")) } : {},
          ...q.get("offset") ? { offset: Number(q.get("offset")) } : {}
        };
        const workspaces = await store.listWorkspaces(filter);
        const offset = Math.max(Number(q.get("offset") ?? 0) || 0, 0);
        const total = await store.countWorkspaces(filter);
        return jsonResponse({
          filter_contract: PROJECT_LIST_V2_CONTRACT,
          applied_filters: {
            query_scope: queryScope ?? "legacy",
            tags,
            exclude_evals: excludeEvals,
            exclude_registry_fixtures: !includeFixtures
          },
          workspaces,
          count: workspaces.length,
          total,
          offset,
          limit: Math.min(Math.max(filter.limit ?? WORKSPACE_LIST_DEFAULT_LIMIT, 1), WORKSPACE_LIST_MAX_LIMIT),
          has_more: offset + workspaces.length < total,
          complete: offset === 0 && workspaces.length === total
        });
      }
      if (method === "POST") {
        const body = await readJsonBody(req);
        const workspace = await store.createWorkspace(body);
        return jsonResponse(workspace, 201);
      }
      return errorResponse("Method not allowed", 405);
    }
    if (!sub) {
      if (method === "GET")
        return jsonResponse(await store.requireWorkspace(id));
      if (method === "PATCH" || method === "PUT") {
        const body = await readJsonBody(req);
        return jsonResponse(await store.updateWorkspace(id, body));
      }
      if (method === "DELETE") {
        const hard = toBool(url.searchParams.get("hard"));
        const result2 = await store.deleteWorkspace(id, { hard });
        return jsonResponse({ deleted: true, hard: result2.hard, id: result2.workspace.id });
      }
      return errorResponse("Method not allowed", 405);
    }
    if (sub === "guarded-metadata" && extra === undefined && method === "GET") {
      const started = Date.now();
      const bounds3 = {
        response_byte_limit: Number(url.searchParams.get("response_byte_limit")),
        time_budget_ms: Number(url.searchParams.get("time_budget_ms"))
      };
      const result2 = await store.guardedReadWorkspace({
        project_id: id,
        resource_link_max_items: Number(url.searchParams.get("resource_link_max_items") ?? 1000),
        ...bounds3
      }, started);
      return guardedJsonResponse(result2, bounds3, started);
    }
    if (sub === "guarded-metadata" && extra === undefined && method === "POST") {
      const started = Date.now();
      const body = await readJsonBody(req);
      const bounds3 = {
        response_byte_limit: Number(body.response_byte_limit),
        time_budget_ms: Number(body.time_budget_ms)
      };
      const result2 = await store.guardedUpdateWorkspace({ ...body, project_id: id });
      return guardedJsonResponse(result2, bounds3, started);
    }
    if (sub === "guarded-metadata" && extra === "receipts" && method === "GET") {
      const started = Date.now();
      const bounds3 = {
        response_byte_limit: Number(url.searchParams.get("response_byte_limit")),
        time_budget_ms: Number(url.searchParams.get("time_budget_ms"))
      };
      const result2 = await store.lookupGuardedWorkspaceMutationReceipt({
        project_id: id,
        operation_id: url.searchParams.get("operation_id") ?? "",
        step_id: url.searchParams.get("step_id") ?? "",
        direction: url.searchParams.get("direction") ?? "forward",
        idempotency_key: url.searchParams.get("idempotency_key") ?? "",
        max_items: Number(url.searchParams.get("max_items")),
        ...bounds3
      });
      return guardedJsonResponse(result2, bounds3, started);
    }
    if (sub === "guarded-metadata" && extra === "rollback" && method === "POST") {
      const started = Date.now();
      const body = await readJsonBody(req);
      const bounds3 = {
        response_byte_limit: Number(body.response_byte_limit),
        time_budget_ms: Number(body.time_budget_ms)
      };
      const result2 = await store.rollbackGuardedWorkspaceMutation({ ...body, project_id: id });
      return guardedJsonResponse(result2, bounds3, started);
    }
    if (sub === "relations" && extra === undefined && method === "GET") {
      const started = Date.now();
      const bounds3 = {
        response_byte_limit: Number(url.searchParams.get("response_byte_limit")),
        time_budget_ms: Number(url.searchParams.get("time_budget_ms"))
      };
      const result2 = await store.readProjectRelations({
        project_id: id,
        max_items: Number(url.searchParams.get("max_items")),
        ...bounds3
      }, started);
      return guardedJsonResponse(result2, bounds3, started);
    }
    if (sub === "relations" && (extra === "add" || extra === "supersede") && method === "POST") {
      const started = Date.now();
      const body = await readJsonBody(req);
      const bounds3 = {
        response_byte_limit: Number(body.response_byte_limit),
        time_budget_ms: Number(body.time_budget_ms)
      };
      const result2 = await store.mutateProjectRelation({
        ...body,
        project_id: id,
        mode: extra
      });
      return guardedJsonResponse(result2, bounds3, started);
    }
    if (sub === "resource-links" && extra === undefined && method === "GET") {
      const started = Date.now();
      const bounds3 = {
        response_byte_limit: Number(url.searchParams.get("response_byte_limit")),
        time_budget_ms: Number(url.searchParams.get("time_budget_ms"))
      };
      const result2 = await store.readProjectResourceLinks({
        project_id: id,
        max_items: Number(url.searchParams.get("max_items")),
        ...bounds3
      }, started);
      return guardedJsonResponse(result2, bounds3, started);
    }
    if (sub === "resource-links" && (extra === "add" || extra === "reconcile") && method === "POST") {
      const started = Date.now();
      const body = await readJsonBody(req);
      const bounds3 = {
        response_byte_limit: Number(body.response_byte_limit),
        time_budget_ms: Number(body.time_budget_ms)
      };
      const result2 = await store.mutateProjectResourceLinks({
        ...body,
        project_id: id,
        mode: extra
      });
      return guardedJsonResponse(result2, bounds3, started);
    }
    if (sub === "resource-links" && extra === "rollback" && method === "POST") {
      const started = Date.now();
      const body = await readJsonBody(req);
      const bounds3 = {
        response_byte_limit: Number(body.response_byte_limit),
        time_budget_ms: Number(body.time_budget_ms)
      };
      const result2 = await store.rollbackProjectResourceLinks({ ...body, project_id: id });
      return guardedJsonResponse(result2, bounds3, started);
    }
    if (sub === "duplicate-quarantine" && extra === undefined && method === "GET") {
      const started = Date.now();
      const bounds3 = {
        response_byte_limit: Number(url.searchParams.get("response_byte_limit")),
        time_budget_ms: Number(url.searchParams.get("time_budget_ms"))
      };
      const result2 = await store.readDuplicateProjectQuarantinePreimage({
        project_id: id,
        resource_link_max_items: Number(url.searchParams.get("resource_link_max_items")),
        workspace_location_max_items: Number(url.searchParams.get("workspace_location_max_items")),
        ...bounds3
      }, started);
      return guardedJsonResponse(result2, bounds3, started);
    }
    if (sub === "duplicate-quarantine" && extra === undefined && method === "POST") {
      const started = Date.now();
      const body = await readJsonBody(req);
      const bounds3 = {
        response_byte_limit: Number(body.response_byte_limit),
        time_budget_ms: Number(body.time_budget_ms)
      };
      const result2 = await store.quarantineDuplicateProject({ ...body, project_id: id });
      return guardedJsonResponse(result2, bounds3, started);
    }
    if (sub === "duplicate-quarantine" && extra === "rollback" && method === "POST") {
      const started = Date.now();
      const body = await readJsonBody(req);
      const bounds3 = {
        response_byte_limit: Number(body.response_byte_limit),
        time_budget_ms: Number(body.time_budget_ms)
      };
      const result2 = await store.rollbackDuplicateProjectQuarantine({ ...body, project_id: id });
      return guardedJsonResponse(result2, bounds3, started);
    }
    if (sub === "resource-link-migrations" && extra === "plan" && action === undefined && method === "POST") {
      const started = Date.now();
      const body = await readJsonBody(req);
      const bounds3 = {
        response_byte_limit: Number(body.response_byte_limit),
        time_budget_ms: Number(body.time_budget_ms)
      };
      const result2 = await store.planProjectResourceLinkMigration({ ...body, project_id: id });
      return guardedJsonResponse(result2, bounds3, started);
    }
    if (sub === "resource-link-migrations" && extra && action === undefined && method === "GET") {
      const started = Date.now();
      const bounds3 = {
        response_byte_limit: Number(url.searchParams.get("response_byte_limit")),
        time_budget_ms: Number(url.searchParams.get("time_budget_ms"))
      };
      const result2 = await store.readProjectResourceLinkMigration({
        project_id: id,
        manifest_id: extra,
        max_items: Number(url.searchParams.get("max_items")),
        ...bounds3
      });
      return guardedJsonResponse(result2, bounds3, started);
    }
    if (sub === "resource-link-migrations" && extra && action === "advance" && method === "POST") {
      const started = Date.now();
      const body = await readJsonBody(req);
      const bounds3 = {
        response_byte_limit: Number(body.response_byte_limit),
        time_budget_ms: Number(body.time_budget_ms)
      };
      const result2 = await store.advanceProjectResourceLinkMigration({
        ...body,
        project_id: id,
        manifest_id: extra
      });
      return guardedJsonResponse(result2, bounds3, started);
    }
    if (sub === "resource-link-migrations" && extra && action === "rollback" && method === "POST") {
      const started = Date.now();
      const body = await readJsonBody(req);
      const bounds3 = {
        response_byte_limit: Number(body.response_byte_limit),
        time_budget_ms: Number(body.time_budget_ms)
      };
      const result2 = await store.rollbackProjectResourceLinkMigration({
        ...body,
        project_id: id,
        manifest_id: extra
      });
      return guardedJsonResponse(result2, bounds3, started);
    }
    if (sub === "contacts") {
      if (!contacts)
        return errorResponse("Contacts authority is not configured", 503);
      if (extra === undefined && method === "GET") {
        const started = Date.now();
        const bounds3 = {
          max_items: Number(url.searchParams.get("max_items")),
          response_byte_limit: Number(url.searchParams.get("response_byte_limit")),
          time_budget_ms: Number(url.searchParams.get("time_budget_ms"))
        };
        const result2 = await listProjectContacts({ projects: store, contacts }, {
          project_id: id,
          ...bounds3
        });
        return boundedJsonResponse(result2, bounds3, started);
      }
      if (extra && (action === "attach" || action === "detach") && method === "POST") {
        const started = Date.now();
        const body = await readJsonBody(req);
        const bounds3 = {
          max_items: Number(body.max_items),
          response_byte_limit: Number(body.response_byte_limit),
          time_budget_ms: Number(body.time_budget_ms)
        };
        const mutation = action === "attach" ? attachProjectContact : detachProjectContact;
        const result2 = await mutation({ projects: store, contacts }, {
          project_id: id,
          contact_id: extra,
          operation_id: String(body.operation_id ?? ""),
          ...body.labels && typeof body.labels === "object" ? { labels: body.labels } : {},
          ...bounds3,
          source: "system",
          command: `${method} ${path}`
        });
        return boundedJsonResponse(result2, bounds3, started);
      }
      return errorResponse("Method not allowed", 405);
    }
    if (sub === "archive" && method === "POST")
      return jsonResponse(await store.archiveWorkspace(id));
    if (sub === "unarchive" && method === "POST")
      return jsonResponse(await store.unarchiveWorkspace(id));
    if (sub === "events" && method === "GET") {
      const ws = await store.requireWorkspace(id);
      const limit = url.searchParams.get("limit");
      const events = await store.listWorkspaceEvents(ws.id, limit ? Number(limit) : undefined);
      return jsonResponse({ events, count: events.length });
    }
    if (sub === "locations" && method === "GET") {
      const ws = await store.requireWorkspace(id);
      const locations = await store.listWorkspaceLocations(ws.id);
      return jsonResponse({ locations, count: locations.length });
    }
    if (sub === "locations" && method === "POST") {
      const ws = await store.requireWorkspace(id);
      const body = await readJsonBody(req);
      if (typeof body.path !== "string" || !body.path.trim()) {
        throw new ValidationError("path is required");
      }
      const location = await store.addWorkspaceLocation({
        workspace_id: ws.id,
        path: body.path,
        machine_id: typeof body.machine_id === "string" ? body.machine_id : undefined,
        label: typeof body.label === "string" ? body.label : undefined,
        kind: typeof body.kind === "string" ? body.kind : undefined,
        is_primary: typeof body.is_primary === "boolean" ? body.is_primary : undefined,
        metadata: body.metadata ?? undefined,
        agent_id: typeof body.agent_id === "string" ? body.agent_id : undefined,
        source: "system",
        command: "POST /v1/projects/:id/locations"
      });
      const updated = await store.requireWorkspace(ws.id);
      return jsonResponse({ project: updated, location }, 201);
    }
    if (sub === "agents" && method === "GET") {
      const ws = await store.requireWorkspace(id);
      const assignments = await store.listWorkspaceAgents(ws.id);
      return jsonResponse({ assignments, count: assignments.length });
    }
    if (sub === "agents" && method === "POST") {
      const ws = await store.requireWorkspace(id);
      const body = await readJsonBody(req);
      if (typeof body.agent_id !== "string" || !body.agent_id.trim()) {
        throw new ValidationError("agent_id is required");
      }
      const assignment = await store.assignAgentToWorkspace({
        workspace_id: ws.id,
        agent_id: body.agent_id,
        role: typeof body.role === "string" ? body.role : undefined,
        assigned_by: typeof body.assigned_by === "string" ? body.assigned_by : undefined,
        metadata: body.metadata ?? undefined
      });
      await store.recordEvent({
        workspace_id: ws.id,
        agent_id: assignment.assigned_by ?? undefined,
        event_type: "agent_assigned",
        source: "system",
        command: "POST /v1/projects/:id/agents",
        after: { agent_id: assignment.agent_id, role: assignment.role, assignment_id: assignment.id }
      });
      return jsonResponse({ assignment }, 201);
    }
    if (sub === "events" && method === "POST") {
      const ws = await store.requireWorkspace(id);
      const body = await readJsonBody(req);
      if (typeof body.event_type !== "string" || !body.event_type.trim()) {
        throw new ValidationError("event_type is required");
      }
      const event = await store.recordEvent({
        workspace_id: ws.id,
        agent_id: typeof body.agent_id === "string" ? body.agent_id : undefined,
        event_type: body.event_type,
        source: typeof body.source === "string" ? body.source : "system",
        prompt: typeof body.prompt === "string" ? body.prompt : undefined,
        command: typeof body.command === "string" ? body.command : undefined,
        before: body.before ?? undefined,
        after: body.after ?? undefined,
        metadata: body.metadata ?? undefined
      });
      return jsonResponse({ event }, 201);
    }
    return errorResponse("Not found", 404);
  }
  if (resource2 === "roots") {
    if (!id) {
      if (method === "GET") {
        const roots = await store.listRoots();
        return jsonResponse({ roots, count: roots.length });
      }
      if (method === "POST") {
        const body = await readJsonBody(req);
        return jsonResponse(await store.createRoot(body), 201);
      }
      return errorResponse("Method not allowed", 405);
    }
    if (method === "GET") {
      const root = await store.getRoot(id);
      if (!root)
        return errorResponse(`Root not found: ${id}`, 404);
      return jsonResponse(root);
    }
    if (method === "PATCH" || method === "PUT") {
      const body = await readJsonBody(req);
      return jsonResponse(await store.updateRoot(id, body));
    }
    if (method === "DELETE") {
      const detach = toBool(url.searchParams.get("detach"));
      const result2 = await store.deleteRoot(id, detach);
      return jsonResponse({ deleted: true, id: result2.root.id, detached_workspaces: result2.detached_workspaces });
    }
    return errorResponse("Method not allowed", 405);
  }
  if (resource2 === "agents") {
    if (!id) {
      if (method === "GET") {
        const agents = await store.listAgents();
        return jsonResponse({ agents, count: agents.length });
      }
      if (method === "POST") {
        const body = await readJsonBody(req);
        return jsonResponse(await store.createAgent(body), 201);
      }
      return errorResponse("Method not allowed", 405);
    }
    if (method === "GET") {
      const agent = await store.getAgent(id);
      if (!agent)
        return errorResponse(`Agent not found: ${id}`, 404);
      return jsonResponse(agent);
    }
    return errorResponse("Method not allowed", 405);
  }
  if (resource2 === "locks") {
    if (method === "GET" && !id) {
      const locks = await store.listLocks();
      return jsonResponse({ locks, count: locks.length });
    }
    if (method === "POST" && !id) {
      const body = await readJsonBody(req);
      if (typeof body.lock_key !== "string" || !body.lock_key.trim()) {
        throw new ValidationError("lock_key is required");
      }
      const lock = await store.acquireLock({
        lock_key: body.lock_key,
        workspace_id: typeof body.workspace_id === "string" ? body.workspace_id : undefined,
        agent_id: typeof body.agent_id === "string" ? body.agent_id : undefined,
        reason: typeof body.reason === "string" ? body.reason : undefined,
        ttl_seconds: typeof body.ttl_seconds === "number" ? body.ttl_seconds : undefined
      });
      return jsonResponse({ lock }, 201);
    }
    if (method === "DELETE" && id) {
      const lockKey = decodeURIComponent(id);
      const lockId = url.searchParams.get("lock_id");
      const released = lockId ? await store.releaseLock(lockKey, lockId) : await store.forceReleaseLock(lockKey);
      return jsonResponse({ released });
    }
    return errorResponse("Method not allowed", 405);
  }
  if (resource2 === "recipes") {
    if (!id) {
      if (method === "GET") {
        const recipes = await store.listRecipes();
        return jsonResponse({ recipes, count: recipes.length });
      }
      if (method === "POST") {
        const body = await readJsonBody(req);
        return jsonResponse(await store.createRecipe(body), 201);
      }
      return errorResponse("Method not allowed", 405);
    }
    if (method === "GET") {
      const recipe = await store.getRecipe(id);
      if (!recipe)
        return errorResponse(`Recipe not found: ${id}`, 404);
      return jsonResponse(recipe);
    }
    return errorResponse("Method not allowed", 405);
  }
  if (resource2 === "machines") {
    if (id)
      return errorResponse("Not found", 404);
    if (method === "GET") {
      const machines = await store.listMachines();
      return jsonResponse({ machines, count: machines.length });
    }
    return errorResponse("Method not allowed", 405);
  }
  return errorResponse("Not found", 404);
}

// src/serve/migrations.ts
import { existsSync as existsSync2, readFileSync as readFileSync2, readdirSync } from "fs";
import { dirname as dirname2, join as join4, resolve as resolve4 } from "path";
import { fileURLToPath } from "url";
import { apiKeyMigrations } from "@hasna/contracts/auth";
var MIGRATIONS_DIR_ENV = "PROJECTS_MIGRATIONS_DIR";
var PROJECTS_APPLIED_MIGRATION_COMPATIBILITY = [
  {
    id: "projects:0002_tenants",
    checksum: "sha256:0a93c3c87fa9159545f270a053835f28e3b0eed5d8d13ec886c3aa549287bcd2"
  }
];
function resolveMigrationsDir() {
  const override = process.env[MIGRATIONS_DIR_ENV];
  if (override && existsSync2(override))
    return resolve4(override);
  const here = (() => {
    try {
      return dirname2(fileURLToPath(import.meta.url));
    } catch {
      return process.cwd();
    }
  })();
  const candidates = [
    join4(process.cwd(), "migrations"),
    join4(here, "migrations"),
    join4(here, "..", "migrations"),
    join4(here, "..", "..", "migrations"),
    join4(here, "..", "..", "..", "migrations"),
    "/app/migrations"
  ];
  for (const dir of candidates) {
    if (existsSync2(join4(dir, "0001_baseline.sql")))
      return dir;
  }
  throw new Error(`projects-serve: migrations directory not found (looked in: ${candidates.join(", ")}). ` + `Set ${MIGRATIONS_DIR_ENV} to the directory containing the *.sql files.`);
}
function loadMigrations() {
  const dir = resolveMigrationsDir();
  const files = readdirSync(dir).filter((f) => f.endsWith(".sql")).sort((a, b) => a.localeCompare(b));
  const schema = files.map((file) => defineMigration(`projects:${file.replace(/\.sql$/, "")}`, readFileSync2(join4(dir, file), "utf-8")));
  const apiKeys = apiKeyMigrations().map((m) => defineMigration(m.id, m.sql));
  return [...schema, ...apiKeys];
}
function assertMigrationCompatibility(migrations2, applied, compatibility = []) {
  const knownById = new Map(migrations2.map((migration) => [migration.id, migration]));
  const compatibleById = new Map;
  for (const entry of compatibility) {
    if (knownById.has(entry.id)) {
      throw new Error(`Applied-only migration compatibility '${entry.id}' conflicts with an executable migration.`);
    }
    if (compatibleById.has(entry.id)) {
      throw new Error(`Duplicate applied-only migration compatibility id: ${entry.id}`);
    }
    compatibleById.set(entry.id, entry);
  }
  for (const row of applied) {
    const expected = knownById.get(row.id)?.checksum ?? compatibleById.get(row.id)?.checksum;
    if (!expected) {
      throw new Error(`Applied migration '${row.id}' (checksum '${row.checksum}') is not recognized by this build (downgrade?).`);
    }
    if (expected !== row.checksum) {
      throw new Error(`Migration checksum mismatch for '${row.id}': applied '${row.checksum}', expected '${expected}'.`);
    }
  }
}
function appliedMigrationKey(row) {
  return `${row.id}\x00${row.checksum}`;
}
function createAppliedMigrationCompatibilityClient(client, compatibility) {
  const compatibleRows = new Set(compatibility.map(appliedMigrationKey));
  return {
    query(sql, params) {
      return client.query(sql, params);
    },
    async many(sql, params) {
      if (!sql.includes(`FROM ${DEFAULT_MIGRATION_LEDGER_TABLE}`)) {
        throw new Error("Applied migration compatibility client received an unexpected ledger query.");
      }
      const rows = await client.many(sql, params);
      return rows.filter((row) => {
        const candidate = row;
        return !(typeof candidate.id === "string" && typeof candidate.checksum === "string" && compatibleRows.has(appliedMigrationKey({
          id: candidate.id,
          checksum: candidate.checksum
        })));
      });
    },
    get(sql, params) {
      return client.get(sql, params);
    },
    one(sql, params) {
      return client.one(sql, params);
    },
    execute(sql, params) {
      return client.execute(sql, params);
    }
  };
}
async function runMigrationLedgerWithCompatibility(client, migrations2, compatibility, opts = {}) {
  const completeLedger = new MigrationLedger(client, migrations2);
  assertMigrationCompatibility(migrations2, await completeLedger.listApplied(), compatibility);
  const migrationClient = createAppliedMigrationCompatibilityClient(client, compatibility);
  const result2 = await new MigrationLedger(migrationClient, migrations2).migrate(opts);
  const applied = await completeLedger.listApplied();
  assertMigrationCompatibility(migrations2, applied, compatibility);
  return { ...result2, applied };
}
async function runProjectsMigrations(client, opts = {}) {
  const migrations2 = loadMigrations();
  return runMigrationLedgerWithCompatibility(client, migrations2, PROJECTS_APPLIED_MIGRATION_COMPATIBILITY, opts);
}

// src/lib/production-project-registration-authorities.ts
var AUTHORITY_ENDPOINTS = {
  todos: {
    authority: "todos",
    apiUrlKeys: ["HASNA_TODOS_API_URL", "TODOS_API_URL"],
    apiKeyKeys: ["HASNA_TODOS_API_KEY", "TODOS_API_KEY"],
    dbPathKeys: ["HASNA_TODOS_DB_PATH", "TODOS_DB_PATH"]
  },
  mementos: {
    authority: "mementos",
    apiUrlKeys: ["HASNA_MEMENTOS_API_URL", "MEMENTOS_API_URL"],
    apiKeyKeys: ["HASNA_MEMENTOS_API_KEY", "MEMENTOS_API_KEY"],
    dbPathKeys: ["HASNA_MEMENTOS_DB_PATH", "MEMENTOS_DB_PATH"]
  },
  conversations: {
    authority: "conversations",
    apiUrlKeys: ["HASNA_CONVERSATIONS_API_URL", "CONVERSATIONS_API_URL"],
    apiKeyKeys: ["HASNA_CONVERSATIONS_API_KEY", "CONVERSATIONS_API_KEY"],
    dbPathKeys: ["HASNA_CONVERSATIONS_DB_PATH", "CONVERSATIONS_DB_PATH"]
  },
  files: {
    authority: "files",
    apiUrlKeys: ["HASNA_FILES_API_URL", "FILES_API_URL"],
    apiKeyKeys: ["HASNA_FILES_API_KEY", "FILES_API_KEY"],
    dbPathKeys: ["HASNA_FILES_DB_PATH", "FILES_DB_PATH"]
  }
};
function firstConfigured(env2, keys) {
  for (const key of keys) {
    const value = env2[key]?.trim();
    if (value)
      return { key, value };
  }
  return null;
}
function authorityRoot(raw, sourceKey) {
  let url;
  try {
    url = new URL(raw);
  } catch {
    throw new Error(`${sourceKey} must be an absolute http(s) URL`);
  }
  if (!["http:", "https:"].includes(url.protocol)) {
    throw new Error(`${sourceKey} must be an absolute http(s) URL`);
  }
  if (url.username || url.password || url.search || url.hash) {
    throw new Error(`${sourceKey} must not contain userinfo, query, or fragment data`);
  }
  const pathname = url.pathname.replace(/\/+$/, "");
  const prefix = pathname === "/v1" ? "" : pathname.replace(/\/v1$/, "");
  return `${url.origin}${prefix}`;
}
function authorityHttpConfig(config, env2) {
  const localDatabase = firstConfigured(env2, config.dbPathKeys);
  if (localDatabase)
    return null;
  const url = firstConfigured(env2, config.apiUrlKeys);
  const key = firstConfigured(env2, config.apiKeyKeys);
  if (!url && !key) {
    throw new Error(`${config.authority} project registration requires ${config.apiUrlKeys[0]} ` + `or an explicit ${config.dbPathKeys[0]}`);
  }
  if (!url) {
    throw new Error(`${config.apiUrlKeys[0]} is required when ${key.key} is configured`);
  }
  if (!key) {
    throw new Error(`${config.apiKeyKeys[0]} is required when ${url.key} is configured`);
  }
  return {
    baseUrl: authorityRoot(url.value, url.key),
    apiKey: key.value
  };
}
function moduleObject(value, packageName) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    throw new Error(`${packageName} did not load as an ES module`);
  }
  return value;
}
function responseObject(authority, value) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    throw new Error(`${authority} project registration returned a non-object response`);
  }
  return value;
}
function selectedResponse(authority, value, key) {
  const body = responseObject(authority, value);
  return key && key in body ? body[key] : body;
}
function withoutTarget(request) {
  const { target: _target, ...serializable } = request;
  return serializable;
}
function withTargetDigest(request) {
  return {
    ...withoutTarget(request),
    target_digest: request.target.digest
  };
}
function assertAdapter(authority, value) {
  if (!value || typeof value !== "object" || value.authority !== authority) {
    throw new Error(`${authority} package did not return its project registration authority`);
  }
  return value;
}

class ConversationsSdkAuthority {
  client;
  authority = "conversations";
  constructor(client) {
    this.client = client;
  }
  async capability() {
    return selectedResponse(this.authority, await this.client.getProjectChannelRegistrationCapability());
  }
  async create(request) {
    if (request.operation_intent === "adopt_existing") {
      if (!this.client.adoptExistingProjectChannel) {
        throw new Error("Conversations SDK does not expose adoptExistingProjectChannel");
      }
      return selectedResponse(this.authority, await this.client.adoptExistingProjectChannel(withTargetDigest(request)));
    }
    return selectedResponse(this.authority, await this.client.registerProjectChannel(withTargetDigest(request)));
  }
  async readExact(request) {
    return selectedResponse(this.authority, await this.client.readProjectChannelRegistrationExact(request.target_id, {
      resource_kind: request.resource_kind,
      target_digest: request.target.digest,
      response_byte_limit: request.response_byte_limit,
      time_budget_ms: request.time_budget_ms,
      call_limit: 1
    }));
  }
  async lookupReceipt(request) {
    return selectedResponse(this.authority, await this.client.lookupProjectChannelRegistrationReceipt({
      ...request,
      call_limit: 1
    }));
  }
  async validateExistingAdoption(request, receipt) {
    if (request.resource_kind !== "channel" || typeof request.desired.channel !== "string")
      return false;
    const response = await this.client.getChannel(request.desired.channel);
    if (!response)
      return false;
    const nestedChannel = response.channel;
    const channel = nestedChannel && typeof nestedChannel === "object" && !Array.isArray(nestedChannel) ? nestedChannel : response;
    return channel.id === receipt.target_id && channel.name === request.desired.channel && (channel.project_id === null || channel.project_id === request.project_id);
  }
  async compensate(request) {
    return selectedResponse(this.authority, await this.client.compensateProjectChannelRegistration(withTargetDigest(request)));
  }
  async verifyInverse(request) {
    return selectedResponse(this.authority, await this.client.verifyProjectChannelRegistrationInverse(withTargetDigest(request)));
  }
}
async function loadHttpAuthority(authority, http, fetchImpl, importModule) {
  if (authority === "todos") {
    const specifier2 = "@hasna/todos/project-registration";
    const module2 = moduleObject(await importModule(specifier2), specifier2);
    const createClient = module2.createTodosProjectRegistrationHttpClient;
    if (typeof createClient !== "function") {
      throw new Error(`${specifier2} does not expose createTodosProjectRegistrationHttpClient`);
    }
    return assertAdapter(authority, createClient({
      baseUrl: http.baseUrl,
      apiKey: http.apiKey,
      fetch: fetchImpl
    }));
  }
  if (authority === "mementos") {
    const specifier2 = "@hasna/mementos/project-registration";
    const module2 = moduleObject(await importModule(specifier2), specifier2);
    const createClient = module2.createMementosProjectRegistrationHttpClient;
    if (typeof createClient !== "function") {
      throw new Error(`${specifier2} does not expose createMementosProjectRegistrationHttpClient`);
    }
    return assertAdapter(authority, createClient({
      baseUrl: http.baseUrl,
      apiKey: http.apiKey,
      fetch: fetchImpl
    }));
  }
  if (authority === "files") {
    const specifier2 = "@hasna/files/project-registration";
    const module2 = moduleObject(await importModule(specifier2), specifier2);
    const createClient = module2.createFilesProjectRegistrationHttpClient;
    if (typeof createClient !== "function") {
      throw new Error(`${specifier2} does not expose createFilesProjectRegistrationHttpClient`);
    }
    return assertAdapter(authority, createClient({
      baseUrl: http.baseUrl,
      apiKey: http.apiKey,
      fetch: fetchImpl
    }));
  }
  const specifier = "@hasna/conversations/sdk";
  const module = moduleObject(await importModule(specifier), specifier);
  const ConversationsClient = module.ConversationsClient;
  if (typeof ConversationsClient !== "function") {
    throw new Error(`${specifier} does not expose ConversationsClient`);
  }
  const client = new ConversationsClient({
    baseUrl: http.baseUrl,
    apiKey: http.apiKey,
    fetch: fetchImpl
  });
  return new ConversationsSdkAuthority(client);
}
function announceLocalAuthority(authority, localDatabaseKey, notify) {
  notify(`projects: local mode \u2014 ${localDatabaseKey} is set, so the ${authority} project registration ` + (authority === "files" ? "capability reports the on-box files instance instead of the hosted files service." : `authority reads and writes the on-box ${authority} SQLite instead of the hosted ${authority} service.`));
}
async function loadLocalAuthority(authority, importModule, localDatabaseKey, notify = (line) => console.error(line)) {
  announceLocalAuthority(authority, localDatabaseKey, notify);
  if (authority === "todos") {
    const specifier2 = "@hasna/todos";
    const module2 = moduleObject(await importModule(specifier2), specifier2);
    const getDatabase2 = module2.getDatabase;
    const createAuthority2 = module2.createLocalTodosProjectRegistrationAuthority;
    if (typeof getDatabase2 !== "function" || typeof createAuthority2 !== "function") {
      throw new Error(`${specifier2} does not expose the shipped local project registration authority`);
    }
    return assertAdapter(authority, createAuthority2(getDatabase2()));
  }
  if (authority === "mementos") {
    const specifier2 = "@hasna/mementos";
    const module2 = moduleObject(await importModule(specifier2), specifier2);
    const getDatabase2 = module2.getDatabase;
    const createAuthority2 = module2.createLocalMementosProjectRegistrationAuthority;
    if (typeof getDatabase2 !== "function" || typeof createAuthority2 !== "function") {
      throw new Error(`${specifier2} does not expose the shipped local project registration authority`);
    }
    return assertAdapter(authority, createAuthority2(getDatabase2()));
  }
  if (authority === "files") {
    const specifier2 = "@hasna/files/project-registration";
    const module2 = moduleObject(await importModule(specifier2), specifier2);
    const createAuthority2 = module2.createLocalFilesProjectRegistrationAuthority;
    if (typeof createAuthority2 !== "function") {
      throw new Error(`${specifier2} does not expose the shipped local project registration authority`);
    }
    return assertAdapter(authority, createAuthority2());
  }
  const specifier = "@hasna/conversations";
  const module = moduleObject(await importModule(specifier), specifier);
  const createAuthority = module.createProjectChannelRegistrationAuthority;
  if (typeof createAuthority !== "function") {
    throw new Error(`${specifier} does not expose the shipped project channel registration authority`);
  }
  return assertAdapter(authority, createAuthority());
}

class LazyProjectRegistrationAuthority {
  load;
  authority;
  transport;
  delegate = null;
  constructor(authority, transport, load) {
    this.load = load;
    this.authority = authority;
    this.transport = transport;
  }
  resolve() {
    this.delegate ??= this.load();
    return this.delegate;
  }
  async capability() {
    return (await this.resolve()).capability();
  }
  async create(request) {
    return (await this.resolve()).create(request);
  }
  async readExact(request) {
    return (await this.resolve()).readExact(request);
  }
  async lookupReceipt(request) {
    return (await this.resolve()).lookupReceipt(request);
  }
  async validateExistingAdoption(request, receipt) {
    const delegate = await this.resolve();
    return delegate.validateExistingAdoption?.(request, receipt) ?? false;
  }
  async validatePriorRegistrationAdoption(sourceRequest, sourceReceipt, currentRecord) {
    const delegate = await this.resolve();
    return delegate.validatePriorRegistrationAdoption?.(sourceRequest, sourceReceipt, currentRecord) ?? false;
  }
  async compensate(request) {
    return (await this.resolve()).compensate(request);
  }
  async verifyInverse(request) {
    return (await this.resolve()).verifyInverse(request);
  }
  async guardedUpdateProject(targetId, request) {
    const delegate = await this.resolve();
    if (!delegate.guardedUpdateProject) {
      throw new Error(`${this.authority} package does not expose guardedUpdateProject`);
    }
    return delegate.guardedUpdateProject(targetId, request);
  }
  async getGuardedProjectUpdateReceipt(targetId, receiptId, request) {
    const delegate = await this.resolve();
    if (!delegate.getGuardedProjectUpdateReceipt) {
      throw new Error(`${this.authority} package does not expose getGuardedProjectUpdateReceipt`);
    }
    return delegate.getGuardedProjectUpdateReceipt(targetId, receiptId, request);
  }
  async rollbackGuardedProjectUpdate(targetId, request) {
    const delegate = await this.resolve();
    if (!delegate.rollbackGuardedProjectUpdate) {
      throw new Error(`${this.authority} package does not expose rollbackGuardedProjectUpdate`);
    }
    return delegate.rollbackGuardedProjectUpdate(targetId, request);
  }
}
function configuredAuthority(authority, options) {
  const config = AUTHORITY_ENDPOINTS[authority];
  const localDatabase = firstConfigured(options.env, config.dbPathKeys);
  const transport = localDatabase ? "local" : firstConfigured(options.env, [...config.apiUrlKeys, ...config.apiKeyKeys]) ? "api" : undefined;
  return new LazyProjectRegistrationAuthority(authority, transport, async () => {
    const http = authorityHttpConfig(config, options.env);
    return http ? loadHttpAuthority(authority, http, options.fetch, options.importModule) : loadLocalAuthority(authority, options.importModule, localDatabase?.key ?? config.dbPathKeys[0]);
  });
}
function productionProjectRegistrationAuthorities(options = {}) {
  const resolved = {
    env: options.env ?? process.env,
    fetch: options.fetch ?? globalThis.fetch,
    importModule: options.importModule ?? ((specifier) => import(specifier))
  };
  return {
    todos: configuredAuthority("todos", resolved),
    mementos: configuredAuthority("mementos", resolved),
    conversations: configuredAuthority("conversations", resolved),
    files: configuredAuthority("files", resolved)
  };
}

// src/lib/project-resource-link-producer-verifier.ts
var PROJECT_RESOURCE_LINK_PRODUCER_VERIFICATION_SCHEMA = "projects.project_resource_link_producer_verification.v1";
var PROJECT_RESOURCE_LINK_PRODUCER_VERIFIER = "projects.production-producer-authority-readback.v1";
function objectValue(value, label) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    throw new Error(`${label} must be an object`);
  }
  return value;
}
function stringValue(value, label) {
  if (typeof value !== "string" || !value.trim()) {
    throw new Error(`${label} must be a nonempty string`);
  }
  return value;
}
function nullableStringValue(value, label) {
  return value === null ? null : stringValue(value, label);
}
function booleanValue(value, label) {
  if (typeof value !== "boolean")
    throw new Error(`${label} must be a boolean`);
  return value;
}
function receiptValue(value, label) {
  const receipt = objectValue(value, label);
  const authority = stringValue(receipt.authority, `${label}.authority`);
  const resourceKind = stringValue(receipt.resource_kind, `${label}.resource_kind`);
  const direction = stringValue(receipt.direction, `${label}.direction`);
  const outcome = stringValue(receipt.outcome, `${label}.outcome`);
  if (!["todos", "mementos", "conversations"].includes(authority)) {
    throw new Error(`${label}.authority is not a supported project-registration authority`);
  }
  if (!["project", "task_list", "channel"].includes(resourceKind)) {
    throw new Error(`${label}.resource_kind is unsupported`);
  }
  if (!["forward", "inverse"].includes(direction)) {
    throw new Error(`${label}.direction is unsupported`);
  }
  if (!["accepted", "duplicate_of_accepted", "terminal_nonacceptance"].includes(outcome)) {
    throw new Error(`${label}.outcome is unsupported`);
  }
  return {
    receipt_id: stringValue(receipt.receipt_id, `${label}.receipt_id`),
    authority,
    route: stringValue(receipt.route, `${label}.route`),
    package_version: stringValue(receipt.package_version, `${label}.package_version`),
    authority_id: stringValue(receipt.authority_id, `${label}.authority_id`),
    tenant_id: stringValue(receipt.tenant_id, `${label}.tenant_id`),
    corpus_id: stringValue(receipt.corpus_id, `${label}.corpus_id`),
    operation_id: stringValue(receipt.operation_id, `${label}.operation_id`),
    step_id: stringValue(receipt.step_id, `${label}.step_id`),
    resource_kind: resourceKind,
    direction,
    idempotency_key: stringValue(receipt.idempotency_key, `${label}.idempotency_key`),
    request_digest: stringValue(receipt.request_digest, `${label}.request_digest`),
    precondition_digest: stringValue(receipt.precondition_digest, `${label}.precondition_digest`),
    outcome,
    reason: nullableStringValue(receipt.reason, `${label}.reason`),
    target_id: nullableStringValue(receipt.target_id, `${label}.target_id`),
    result_revision: nullableStringValue(receipt.result_revision, `${label}.result_revision`),
    result_digest: nullableStringValue(receipt.result_digest, `${label}.result_digest`),
    duplicate_of_receipt_id: nullableStringValue(receipt.duplicate_of_receipt_id, `${label}.duplicate_of_receipt_id`),
    accepted_receipt_id: nullableStringValue(receipt.accepted_receipt_id, `${label}.accepted_receipt_id`),
    created_by_operation: booleanValue(receipt.created_by_operation, `${label}.created_by_operation`),
    created_at: stringValue(receipt.created_at, `${label}.created_at`)
  };
}
function envelopeValue(evidence3) {
  const raw = objectValue(evidence3.producer_verification, "producer verification evidence");
  if (raw.schema !== PROJECT_RESOURCE_LINK_PRODUCER_VERIFICATION_SCHEMA) {
    throw new Error(`producer verification evidence schema must be ${PROJECT_RESOURCE_LINK_PRODUCER_VERIFICATION_SCHEMA}`);
  }
  if (!Array.isArray(raw.links)) {
    throw new Error("producer verification evidence links must be an array");
  }
  const links = raw.links.map((value, index) => {
    const link = objectValue(value, `producer verification link ${index}`);
    const inverseRequest = link.inverse_request === undefined ? undefined : objectValue(link.inverse_request, `producer verification link ${index}.inverse_request`);
    return {
      link_id: stringValue(link.link_id, `producer verification link ${index}.link_id`),
      target_context_digest: stringValue(link.target_context_digest, `producer verification link ${index}.target_context_digest`),
      target_selector: stringValue(link.target_selector, `producer verification link ${index}.target_selector`),
      forward_receipt: receiptValue(link.forward_receipt, `producer verification link ${index}.forward_receipt`),
      ...link.inverse_receipt === undefined ? {} : {
        inverse_receipt: receiptValue(link.inverse_receipt, `producer verification link ${index}.inverse_receipt`)
      },
      ...inverseRequest ? {
        inverse_request: {
          project_slug: stringValue(inverseRequest.project_slug, `producer verification link ${index}.inverse_request.project_slug`),
          project_name: stringValue(inverseRequest.project_name, `producer verification link ${index}.inverse_request.project_name`),
          desired: objectValue(inverseRequest.desired, `producer verification link ${index}.inverse_request.desired`)
        }
      } : {}
    };
  });
  if (new Set(links.map((link) => link.link_id)).size !== links.length) {
    throw new Error("producer verification evidence contains duplicate link ids");
  }
  return {
    schema: PROJECT_RESOURCE_LINK_PRODUCER_VERIFICATION_SCHEMA,
    links
  };
}
function authorityName(item) {
  const authority = item.link.authority;
  if (!["todos", "mementos", "conversations"].includes(authority)) {
    throw new Error(`producer authority ${authority} is not configured for trusted readback`);
  }
  return authority;
}
function resourceKind(item) {
  const targetKind = item.link.target_kind;
  if (!["project", "task_list", "channel"].includes(targetKind)) {
    throw new Error(`producer target kind ${targetKind} is not supported for trusted readback`);
  }
  return targetKind;
}
function expectedTargetId(item) {
  const { kind, value } = item.link.locator;
  if (kind === "canonical_uri") {
    const parts = value.split(/[:/]/).filter(Boolean);
    const targetId = parts.at(-1);
    if (!targetId)
      throw new Error("producer canonical locator does not contain a target id");
    return targetId;
  }
  if (kind === "external_uuid" || kind.endsWith("_id"))
    return value;
  throw new Error(`producer locator kind ${kind} is not supported for trusted readback`);
}
function assertCapability(item, capability, expectedAuthority, expectedResourceKind) {
  const binding = item.producer_binding;
  if (capability.authority !== expectedAuthority || capability.authority_id !== binding.authority_id || capability.tenant_id !== binding.tenant_id || capability.corpus_id !== binding.corpus_id) {
    throw new Error("producer capability does not match the manifest authority, tenant, and corpus binding");
  }
  if (sha256(canonicalJson(capability)) !== binding.capability_digest) {
    throw new Error("producer capability digest does not match the manifest binding");
  }
  if (!capability.immutable_receipts || !capability.exact_terminal_lookup || !capability.exact_readback || !capability.supported_resources.includes(expectedResourceKind)) {
    throw new Error("producer capability does not support immutable exact receipt/readback verification");
  }
}
function assertReceiptContext(receipt, manifest, item, capability, expectedDirection, expectedResourceKind) {
  const binding = item.producer_binding;
  if (receipt.authority !== capability.authority || receipt.route !== capability.route || receipt.package_version !== capability.package_version || receipt.authority_id !== binding.authority_id || receipt.tenant_id !== binding.tenant_id || receipt.corpus_id !== binding.corpus_id || receipt.operation_id !== manifest.operation_id || receipt.step_id !== manifest.step_id || receipt.resource_kind !== expectedResourceKind || receipt.direction !== expectedDirection) {
    throw new Error("producer receipt does not bind the manifest operation and authority context");
  }
}
function trustedConversationsForwardRequest(manifest, item, input) {
  const project2 = input.trusted_project;
  if (manifest.project_id !== project2.id) {
    throw new Error("producer manifest does not match the trusted project subject");
  }
  if (item.link.authority !== "conversations" || item.link.target_kind !== "channel") {
    throw new Error(`producer request reconstruction is not configured for ${item.link.authority}/${item.link.target_kind}`);
  }
  const targetSelector = project2.conversations_channel;
  if (item.link.labels?.channel_name !== undefined && item.link.labels.channel_name !== targetSelector) {
    throw new Error("producer manifest channel label does not match the trusted project subject");
  }
  const desired = {
    channel: targetSelector,
    project_id: project2.id,
    project_slug: project2.slug,
    project_kind: project2.kind
  };
  const requestDigest2 = sha256(canonicalJson(desired));
  const preconditionDigest2 = sha256(canonicalJson({
    target_selector: targetSelector,
    expected: "absent"
  }));
  return {
    target_selector: targetSelector,
    idempotency_key: deriveProjectRegistrationIdempotencyKey({
      operation_id: manifest.operation_id,
      step_id: manifest.step_id,
      direction: "forward",
      target_selector: targetSelector,
      request_digest: requestDigest2,
      precondition_digest: preconditionDigest2
    }),
    request_digest: requestDigest2,
    precondition_digest: preconditionDigest2,
    project_id: project2.id,
    project_slug: project2.slug,
    project_name: project2.name,
    desired
  };
}
function trustedInverseRequest(manifest, forwardReceipt, input) {
  const project2 = input.trusted_project;
  if (manifest.project_id !== project2.id) {
    throw new Error("producer manifest does not match the trusted project subject");
  }
  if (!forwardReceipt.target_id) {
    throw new Error("producer forward receipt does not identify an inverse target");
  }
  const desired = {
    accepted_receipt_id: forwardReceipt.receipt_id,
    target_id: forwardReceipt.target_id
  };
  const requestDigest2 = sha256(canonicalJson(desired));
  const preconditionDigest2 = sha256(canonicalJson({
    target_id: forwardReceipt.target_id,
    expected_revision: forwardReceipt.result_revision,
    expected_digest: forwardReceipt.result_digest
  }));
  return {
    target_selector: forwardReceipt.target_id,
    idempotency_key: deriveProjectRegistrationIdempotencyKey({
      operation_id: manifest.operation_id,
      step_id: manifest.step_id,
      direction: "inverse",
      target_selector: forwardReceipt.target_id,
      request_digest: requestDigest2,
      precondition_digest: preconditionDigest2
    }),
    request_digest: requestDigest2,
    precondition_digest: preconditionDigest2,
    project_id: project2.id,
    project_slug: project2.slug,
    project_name: project2.name,
    desired
  };
}
function assertLookupControl(result2, input) {
  const control = result2.response_control;
  if (control.complete !== true || control.truncated !== false || control.response_bytes > input.response_byte_limit || control.elapsed_ms > input.time_budget_ms) {
    throw new Error("producer receipt lookup did not return one complete bounded result");
  }
}
async function lookupStoredReceipt(authority, receipt, request, input) {
  const result2 = await authority.lookupReceipt({
    operation_id: receipt.operation_id,
    step_id: receipt.step_id,
    resource_kind: receipt.resource_kind,
    direction: receipt.direction,
    authority: receipt.authority,
    authority_route: receipt.route,
    package_version: receipt.package_version,
    authority_id: receipt.authority_id,
    tenant_id: receipt.tenant_id,
    corpus_id: receipt.corpus_id,
    target_selector: request.target_selector,
    idempotency_key: request.idempotency_key,
    request_digest: request.request_digest,
    precondition_digest: request.precondition_digest,
    ...receipt.target_id ? { target_id: receipt.target_id } : {},
    max_items: 1,
    response_byte_limit: input.response_byte_limit,
    time_budget_ms: input.time_budget_ms
  });
  assertLookupControl(result2, input);
  const stored = receiptValue(result2.receipt, "lookup.receipt");
  if (canonicalJson(stored) !== canonicalJson(receipt)) {
    throw new Error("stored producer receipt does not match the supplied verification envelope");
  }
  return stored;
}
function opaqueTargetHandle(digest3) {
  return {
    digest: digest3,
    withOwnedPath() {
      throw new Error("producer authority requires an owned path, but migration verification only carries an opaque target context");
    }
  };
}
function assertForwardReceipt(receipt, manifest, item, producerEvidence, capability, expectedResourceKind, request) {
  assertReceiptContext(receipt, manifest, item, capability, "forward", expectedResourceKind);
  const persisted = item.producer_evidence;
  if (!persisted)
    throw new Error("producer verification has no persisted forward evidence");
  if (receipt.outcome !== "accepted" || receipt.receipt_id !== producerEvidence.forward_receipt_id || receipt.receipt_id !== persisted.forward_receipt_id || receipt.created_by_operation !== persisted.created_by_operation || receipt.target_id !== expectedTargetId(item) || receipt.idempotency_key !== request.idempotency_key || receipt.request_digest !== request.request_digest || receipt.precondition_digest !== request.precondition_digest) {
    throw new Error("producer forward receipt does not bind the trusted project subject and manifest target");
  }
  if (producerEvidence.child_link_receipt_ids.length > 0) {
    throw new Error("producer child-link receipt verification is not configured; refusing terminal transition");
  }
}
async function assertCurrentReadback(authority, receipt, proof, producerEvidence, input) {
  if (!receipt.target_id)
    throw new Error("producer forward receipt does not identify a target");
  const record = await authority.readExact({
    resource_kind: receipt.resource_kind,
    target_id: receipt.target_id,
    target: opaqueTargetHandle(proof.target_context_digest),
    response_byte_limit: input.response_byte_limit,
    time_budget_ms: input.time_budget_ms
  });
  if (record.target_id !== receipt.target_id || record.revision !== producerEvidence.target_revision || record.digest !== producerEvidence.target_digest) {
    throw new Error("producer exact readback does not match the terminal migration evidence");
  }
}
function assertInverseReceipt(receipt, forwardReceipt, manifest, item, producerEvidence, capability, expectedResourceKind, phase, request) {
  assertReceiptContext(receipt, manifest, item, capability, "inverse", expectedResourceKind);
  const expectedOutcome = phase === "inverse_complete" ? ["accepted", "duplicate_of_accepted"] : ["terminal_nonacceptance"];
  if (!expectedOutcome.includes(receipt.outcome) || receipt.accepted_receipt_id !== forwardReceipt.receipt_id || receipt.target_id !== forwardReceipt.target_id || receipt.result_revision !== producerEvidence.target_revision || receipt.result_digest !== producerEvidence.target_digest || receipt.idempotency_key !== request.idempotency_key || receipt.request_digest !== request.request_digest || receipt.precondition_digest !== request.precondition_digest) {
    throw new Error("producer inverse receipt does not prove the requested terminal outcome");
  }
}
async function assertInverseComplete(authority, forwardReceipt, inverseReceipt, inverseRequest, proof, request, input) {
  if (!forwardReceipt.target_id)
    throw new Error("producer forward receipt does not identify a target");
  if (inverseRequest.project_slug !== request.project_slug || inverseRequest.project_name !== request.project_name || canonicalJson(inverseRequest.desired) !== canonicalJson(request.desired)) {
    throw new Error("producer inverse request evidence does not match the trusted project subject");
  }
  const verification = await authority.verifyInverse({
    operation_id: inverseReceipt.operation_id,
    step_id: inverseReceipt.step_id,
    resource_kind: inverseReceipt.resource_kind,
    direction: "inverse",
    authority_route: inverseReceipt.route,
    package_version: inverseReceipt.package_version,
    authority_id: inverseReceipt.authority_id,
    tenant_id: inverseReceipt.tenant_id,
    corpus_id: inverseReceipt.corpus_id,
    target_selector: request.target_selector,
    idempotency_key: request.idempotency_key,
    request_digest: request.request_digest,
    precondition_digest: request.precondition_digest,
    project_id: request.project_id,
    project_slug: request.project_slug,
    project_name: request.project_name,
    desired: request.desired,
    target: opaqueTargetHandle(proof.target_context_digest),
    accepted_receipt: forwardReceipt,
    response_byte_limit: input.response_byte_limit,
    time_budget_ms: input.time_budget_ms
  });
  if (verification.absent !== true || verification.target_id !== forwardReceipt.target_id || verification.accepted_receipt_id !== forwardReceipt.receipt_id || !verification.digest?.trim()) {
    throw new Error("producer inverse verification did not prove exact target absence");
  }
}
async function verifyLink(authority, capability, manifest, item, proof, producerEvidence, input) {
  const expectedAuthority = authorityName(item);
  const expectedResourceKind = resourceKind(item);
  const forwardRequest = trustedConversationsForwardRequest(manifest, item, input);
  assertCapability(item, capability, expectedAuthority, expectedResourceKind);
  if (proof.target_selector !== forwardRequest.target_selector) {
    throw new Error("producer verification target selector does not match the trusted project subject");
  }
  assertForwardReceipt(proof.forward_receipt, manifest, item, producerEvidence, capability, expectedResourceKind, forwardRequest);
  const storedForward = await lookupStoredReceipt(authority, proof.forward_receipt, forwardRequest, input);
  if (input.phase === "readback") {
    await assertCurrentReadback(authority, storedForward, proof, producerEvidence, input);
    return;
  }
  if (!capability.conditional_inverse) {
    throw new Error("producer capability does not support conditional inverse verification");
  }
  if (!proof.inverse_receipt || !proof.inverse_request) {
    throw new Error("producer inverse verification requires an exact inverse receipt and request context");
  }
  const inverseRequest = trustedInverseRequest(manifest, storedForward, input);
  assertInverseReceipt(proof.inverse_receipt, storedForward, manifest, item, producerEvidence, capability, expectedResourceKind, input.phase, inverseRequest);
  const storedInverse = await lookupStoredReceipt(authority, proof.inverse_receipt, inverseRequest, input);
  if (input.phase === "inverse_complete") {
    await assertInverseComplete(authority, storedForward, storedInverse, proof.inverse_request, proof, inverseRequest, input);
    return;
  }
  await assertCurrentReadback(authority, storedForward, proof, producerEvidence, input);
}
function createProductionProjectResourceLinkProducerEvidenceVerifier(options = {}) {
  const authorities = options.authorities ?? productionProjectRegistrationAuthorities();
  const now2 = options.now ?? (() => new Date().toISOString());
  return async (input) => {
    const envelope = envelopeValue(input.transition_evidence);
    if (envelope.links.length !== input.manifest.links.length) {
      throw new Error("producer verification evidence requires exact proof for every manifest link");
    }
    const proofByLink = new Map(envelope.links.map((proof) => [proof.link_id, proof]));
    const capabilityByAuthority = new Map;
    for (let index = 0;index < input.manifest.links.length; index += 1) {
      const item = input.manifest.links[index];
      const proof = proofByLink.get(item.link_id);
      if (!proof)
        throw new Error(`producer verification evidence is missing link ${item.link_id}`);
      const name = authorityName(item);
      const authority = authorities[name];
      if (!authority)
        throw new Error(`producer authority ${name} is not configured for trusted readback`);
      let capability = capabilityByAuthority.get(name);
      if (!capability) {
        capability = await authority.capability();
        capabilityByAuthority.set(name, capability);
      }
      await verifyLink(authority, capability, input.manifest, item, proof, input.producer_evidence[index], input);
    }
    const evidenceDigest = projectResourceLinkProducerEvidenceDigest(input.manifest, input.phase, input.producer_evidence);
    return {
      attestation_id: projectResourceLinkProducerAttestationId(input.manifest.manifest_id, input.phase, evidenceDigest),
      manifest_id: input.manifest.manifest_id,
      phase: input.phase,
      evidence_digest: evidenceDigest,
      verifier: PROJECT_RESOURCE_LINK_PRODUCER_VERIFIER,
      verified_at: now2()
    };
  };
}

// src/serve/index.ts
var APP = "projects";
function getPackageVersion() {
  try {
    const pkgPath = join5(dirname3(fileURLToPath2(import.meta.url)), "..", "..", "package.json");
    return JSON.parse(readFileSync3(pkgPath, "utf-8")).version || "0.0.0";
  } catch {
    return "0.0.0";
  }
}
function handleEarlyArgs(argv) {
  if (argv.includes("--help"))
    return "help";
  if (argv.includes("--version"))
    return "version";
  return "start";
}
function printHelp() {
  console.log(`usage: projects-serve [migrate] [--port <n>]

projects-serve \u2014 HTTP API for @hasna/projects.

commands:
  migrate [--dry-run]   apply pending migrations, then exit
  (no command)          start the HTTP server

options:
  --help                show this help and exit
  --version             print the package version and exit
  --port <n>            listen port (default: 8080, or $PORT)
`);
}
function resolveDatabaseUrl2(env2 = process.env) {
  const url = env2.HASNA_PROJECTS_DATABASE_URL || env2.PROJECTS_DATABASE_URL || env2.DATABASE_URL || "";
  if (!url.trim()) {
    throw new Error("projects-serve: no database URL. Set HASNA_PROJECTS_DATABASE_URL (or PROJECTS_DATABASE_URL / DATABASE_URL).");
  }
  return url.trim();
}
function resolveSigningSecret(env2 = process.env) {
  const secret = env2.HASNA_PROJECTS_API_SIGNING_KEY || env2.HASNA_API_SIGNING_KEY || env2.API_KEY_SIGNING_SECRET || "";
  if (!secret.trim()) {
    throw new Error("projects-serve: no API signing secret. Set HASNA_PROJECTS_API_SIGNING_KEY (or HASNA_API_SIGNING_KEY / API_KEY_SIGNING_SECRET).");
  }
  return secret.trim();
}
function resolvePort(argv, env2 = process.env) {
  const idx = argv.indexOf("--port");
  if (idx >= 0 && argv[idx + 1])
    return Number(argv[idx + 1]);
  if (env2.PORT)
    return Number(env2.PORT);
  return 8080;
}
function resolveContactsAuthority(env2 = process.env) {
  try {
    resolveClientTransport2("contacts", env2);
  } catch (error) {
    if (unconfiguredForHostedUse("contacts", env2))
      return;
    throw error;
  }
  return createContactsProjectMembershipAuthorityFromEnv(env2);
}
function createProjectsPgStore(client, options = {}) {
  return new ProjectsPgStore(client, createProductionProjectResourceLinkProducerEvidenceVerifier({
    authorities: productionProjectRegistrationAuthorities(options.producerAuthorityOptions),
    now: options.producerVerifierNow
  }));
}
async function main() {
  const argv = process.argv.slice(2);
  const version = getPackageVersion();
  const early = handleEarlyArgs(argv);
  if (early === "help") {
    printHelp();
    return;
  }
  if (early === "version") {
    console.log(version);
    return;
  }
  const connectionString = resolveDatabaseUrl2();
  const pool3 = createPgPool({ connectionString, applicationName: `${APP}-serve`, max: 5 });
  const client = createQueryClient(pool3);
  if (argv[0] === "migrate") {
    const dryRun = argv.includes("--dry-run");
    const result2 = await runProjectsMigrations(client, { dryRun });
    const pending = result2.plan.filter((p) => p.state === "pending").map((p) => p.migration.id);
    console.error(`projects-serve migrate: ${dryRun ? "DRY RUN \u2014 " : ""}${result2.applied.length} applied total, ` + `${pending.length} ${dryRun ? "pending" : "newly applied"}${pending.length ? `: ${pending.join(", ")}` : ""}`);
    await pool3.end();
    return;
  }
  const signingSecret = resolveSigningSecret();
  const keyStore = new ApiKeyStore(client);
  const store = createProjectsPgStore(client);
  const contacts = resolveContactsAuthority();
  const port = resolvePort(argv);
  const hostname = process.env.HOST || "0.0.0.0";
  const handler = createFetchHandler({
    store,
    contacts,
    projectionPolicy: loadProjectionPolicy(process.env.HASNA_PROJECTS_PROJECTION_POLICY_FILE, process.env.HASNA_PROJECTS_PROJECTION_POLICY_JSON),
    version,
    app: APP,
    signingSecret,
    keyStatus: keyStore.keyStatus,
    audit: (e) => {
      if (e.outcome === "deny") {
        console.error(`api_auth deny kid=${e.kid ?? "-"} reason=${e.reason ?? "-"} ${e.method} ${e.path}`);
      }
    }
  });
  Bun.serve({ hostname, port, fetch: handler, idleTimeout: 60 });
  console.error(`projects-serve v${version} listening on http://${hostname}:${port}`);
}
if (import.meta.main) {
  main().catch((err) => {
    console.error("projects-serve fatal:", err instanceof Error ? err.message : err);
    process.exit(1);
  });
}
export {
  resolveSigningSecret,
  resolvePort,
  resolveDatabaseUrl2 as resolveDatabaseUrl,
  resolveContactsAuthority,
  printHelp,
  handleEarlyArgs,
  getPackageVersion,
  createProjectsPgStore
};