import { LocalContext } from "@/util/local-context"
import { FSUtil } from "@novaclaw/core/fs-util"

// T3 (notes/entities.md): the instance carries derived substrate attributes, not an entity —
// worktree (the VCS root; "/" outside any repo, preserving the containsPath guard), the
// rename-stable origin hash, and the vcs kind.
export interface InstanceContext {
  directory: string
  worktree: string
  origin: string
  vcs?: "git"
}

export const context = LocalContext.create<InstanceContext>("instance")

/**
 * Check if a path is within the project boundary.
 * Returns true if path is inside ctx.directory OR ctx.worktree.
 * Paths within the worktree but outside the working directory should not trigger external_directory permission.
 */
export function containsPath(filepath: string, ctx: InstanceContext): boolean {
  if (FSUtil.contains(ctx.directory, filepath)) return true
  // Non-git projects set worktree to "/" which would match ANY absolute path.
  // Skip worktree check in this case to preserve external_directory permissions.
  if (ctx.worktree === "/") return false
  return FSUtil.contains(ctx.worktree, filepath)
}
