feat(studio): deliver asset authoring and automation workflows
Add shared human/task asset batches with reviewed atomic publication, explicit reference rebinds, ownership inspection and qualified glyph/scene budgets. Expose the same authoring and capacity results through Assets and MCP. Deliver isolated guest test targets, retained visual evidence and immutable runtime lifecycle/control observations. Preserve provider qualification and installed authoring examples alongside the completed discussion lessons. Close AGD-106 coordination and the delivered discussion workflows through housekeeping, updating lesson references and preserving qualification limits. Sound remains outside the asset delivery wave. Validation: 579 module tests and 31 additional desktop, process and installed checks passed; native glyph/scene 16/17 boundaries qualified. Discussion validation passed after housekeeping.
This commit is contained in:
@@ -2,4 +2,4 @@ plugins {
|
||||
id("gradle.java-library-conventions")
|
||||
}
|
||||
|
||||
dependencies { api(project(":prometeu-animation")); api(project(":prometeu-infra")) }
|
||||
dependencies { api(project(":prometeu-animation")) }
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package p.studio.api.assets;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* One authority-aware service for human and task callers. A null task is local human
|
||||
* entry only; transports must supply the authenticated task for every agent call.
|
||||
* Batch/request IDs are correlation, never authority. Queries recheck current access.
|
||||
* Implementations recover pending journals before admitting any shared reader/writer.
|
||||
*/
|
||||
public interface AssetAuthoringService {
|
||||
List<AssetSummary> catalog(Path projectRoot, String taskId);
|
||||
List<AssetBatches.ArtifactInfo> artifacts(Path projectRoot,String taskId,AssetReference bank);
|
||||
List<AssetBatches.ArtifactInfo> previewArtifacts(Path projectRoot,String taskId,String batchId,AssetReference bank);
|
||||
AssetDetailsSnapshot inspect(Path projectRoot,String taskId,AssetReference bank);
|
||||
AssetBatches.Revision revision(Path projectRoot, String taskId);
|
||||
List<AssetBatches.Ownership> dependencies(Path projectRoot, String taskId, AssetReference asset);
|
||||
AssetBudgets.Snapshot budget(Path projectRoot, String taskId);
|
||||
/** Human-only, canonical project-bound source authorization. No MCP grant issuance. */
|
||||
AssetBatches.AuthorizedPng authorizePng(Path projectRoot, Path source);
|
||||
/** Stages validated proposed bytes; leaves all published project inputs unchanged. */
|
||||
AssetBatches.Preview preview(Path projectRoot, String taskId, String requestId, AssetBatches.Request request);
|
||||
/** Retained preview inspection still checks current authority. */
|
||||
AssetBatches.Preview preview(Path projectRoot, String taskId, String batchId);
|
||||
/** Explicit commit revalidates revision/source bytes and deduplicates the full parameters. */
|
||||
AssetBatches.Result commit(Path projectRoot, String taskId, String requestId, String batchId,
|
||||
AssetBatches.Revision expectedRevision);
|
||||
/** Returns applied/recovered truth after response loss or late cancellation. */
|
||||
AssetBatches.Result result(Path projectRoot, String taskId, String batchId);
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
package p.studio.api.assets;
|
||||
|
||||
import p.studio.api.assets.metadata.AssetStudioSceneTile;
|
||||
import p.studio.api.values.ValueMaps;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
|
||||
/** Shared authoring values. Constructing these values grants no project or source access. */
|
||||
public final class AssetBatches {
|
||||
private AssetBatches() { }
|
||||
public static final int CONTRACT_VERSION = 1;
|
||||
|
||||
/** Includes missing inputs explicitly so creation/deletion invalidates an earlier preview. */
|
||||
public record Revision(int contractVersion, String sha256, Map<String, String> inputSha256,
|
||||
Set<String> absentPaths) {
|
||||
public Revision {
|
||||
version(contractVersion); hash(sha256);
|
||||
inputSha256 = Map.copyOf(inputSha256); absentPaths = Set.copyOf(absentPaths);
|
||||
inputSha256.forEach((path, digest) -> { relative(path); hash(digest); });
|
||||
absentPaths.forEach(AssetBatches::relative);
|
||||
if (!Collections.disjoint(inputSha256.keySet(), absentPaths))
|
||||
throw new IllegalArgumentException("An input cannot be both present and absent");
|
||||
}
|
||||
}
|
||||
|
||||
/** An opaque project-bound grant issued by a human source selection, never caller assertion. */
|
||||
public record AuthorizedPng(String grantId, String sha256, long sizeBytes, int width, int height) {
|
||||
public AuthorizedPng {
|
||||
text(grantId); hash(sha256);
|
||||
if (sizeBytes <= 0 || width <= 0 || height <= 0) throw new IllegalArgumentException("Invalid PNG input");
|
||||
}
|
||||
}
|
||||
/** Project-contained inputs use existing read authority; external bytes require an issued grant. */
|
||||
public record PngInput(String projectRelativePath, String externalGrantId, String sha256) {
|
||||
public PngInput {
|
||||
hash(sha256);
|
||||
if ((projectRelativePath == null) == (externalGrantId == null))
|
||||
throw new IllegalArgumentException("Choose a project input or an external source grant");
|
||||
if (projectRelativePath != null) relative(projectRelativePath);
|
||||
if (externalGrantId != null) text(externalGrantId);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed interface Mutation permits CreateBank, RegisterBank, ImportPng, ComposeBank,
|
||||
ComposeScene, ComposePalettes, UpdateContract, BuildParticipation {
|
||||
String changeId();
|
||||
}
|
||||
public record CreateBank(String changeId, String relativeRoot, String name, AssetFamily family,
|
||||
String outputFormat, String outputCodec, boolean preload) implements Mutation {
|
||||
public CreateBank {
|
||||
text(changeId); relative(relativeRoot); text(name); Objects.requireNonNull(family);
|
||||
if (family == AssetFamily.UNKNOWN) throw new IllegalArgumentException("Unknown bank family");
|
||||
text(outputFormat); text(outputCodec);
|
||||
}
|
||||
}
|
||||
public record RegisterBank(String changeId, AssetReference bank) implements Mutation {
|
||||
public RegisterBank { text(changeId); Objects.requireNonNull(bank); }
|
||||
}
|
||||
/** Destination is bank-relative. Append/reimport identity rules are enforced by the shared service. */
|
||||
public record ImportPng(String changeId, PngInput source,
|
||||
AssetReference bank, String destination) implements Mutation {
|
||||
public ImportPng {
|
||||
text(changeId); Objects.requireNonNull(source); Objects.requireNonNull(bank); relative(destination);
|
||||
}
|
||||
}
|
||||
public record ComposeBank(String changeId, AssetReference bank, List<String> selectedPaths) implements Mutation {
|
||||
public ComposeBank {
|
||||
text(changeId); Objects.requireNonNull(bank); selectedPaths = List.copyOf(selectedPaths);
|
||||
selectedPaths.forEach(AssetBatches::relative);
|
||||
if (new HashSet<>(selectedPaths).size() != selectedPaths.size())
|
||||
throw new IllegalArgumentException("Duplicate composition input");
|
||||
}
|
||||
}
|
||||
public record Palette(int index,List<Long> rgba8888) {
|
||||
public Palette {
|
||||
rgba8888=List.copyOf(rgba8888);
|
||||
if(index<0||index>=64||rgba8888.isEmpty()||rgba8888.size()>16||rgba8888.stream().anyMatch(color->color<0||color>0xffff_ffffL))
|
||||
throw new IllegalArgumentException("Expected a palette of 1..16 RGBA8888 colors");
|
||||
}
|
||||
}
|
||||
public record ComposePalettes(String changeId,AssetReference bank,List<Palette> palettes) implements Mutation {
|
||||
public ComposePalettes {
|
||||
text(changeId);Objects.requireNonNull(bank);palettes=List.copyOf(palettes);
|
||||
if(palettes.isEmpty()||palettes.size()>64||palettes.stream().map(Palette::index).distinct().count()!=palettes.size())throw new IllegalArgumentException("Expected unique explicit palettes");
|
||||
}
|
||||
}
|
||||
public record SceneLayer(boolean active, AssetReference glyphBank, int tileSize,
|
||||
float parallaxFactorX, float parallaxFactorY, int width, int height,
|
||||
List<SceneTile> tiles) {
|
||||
public SceneLayer {
|
||||
if (active) Objects.requireNonNull(glyphBank);
|
||||
tiles = List.copyOf(tiles);
|
||||
if (width <= 0 || height <= 0 || (long) width * height != tiles.size() || tileSize < 0
|
||||
|| !Float.isFinite(parallaxFactorX) || parallaxFactorX < 0
|
||||
|| !Float.isFinite(parallaxFactorY) || parallaxFactorY < 0)
|
||||
throw new IllegalArgumentException("Invalid scene layer");
|
||||
}
|
||||
}
|
||||
/** Callers name stable artifacts; only the shared packer adapter resolves native glyph indices. */
|
||||
public record SceneTile(boolean active,Artifact artifact,int paletteId,boolean flipX,boolean flipY) {
|
||||
public SceneTile {if(active)Objects.requireNonNull(artifact);if(paletteId<0)throw new IllegalArgumentException("Negative palette identity");}
|
||||
}
|
||||
public record ArtifactInfo(Artifact identity,int glyphIndex,String fingerprint,String sourcePath,int width,int height) {
|
||||
public ArtifactInfo {Objects.requireNonNull(identity);hash(fingerprint);text(sourcePath);if(glyphIndex<0||width<1||height<1)throw new IllegalArgumentException("Invalid artifact geometry");}
|
||||
}
|
||||
public record ComposeScene(String changeId, AssetReference bank, List<SceneLayer> layers) implements Mutation {
|
||||
public ComposeScene {
|
||||
text(changeId); Objects.requireNonNull(bank); layers = List.copyOf(layers);
|
||||
if (layers.size() != 4) throw new IllegalArgumentException("Scene composition requires four layers");
|
||||
}
|
||||
}
|
||||
public record UpdateContract(String changeId, AssetReference bank, boolean preload, String outputCodec,
|
||||
Map<String, String> codecFields, Map<String, String> metadataFields) implements Mutation {
|
||||
public UpdateContract {
|
||||
text(changeId); Objects.requireNonNull(bank); text(outputCodec);
|
||||
codecFields = Map.copyOf(codecFields); metadataFields = Map.copyOf(metadataFields);
|
||||
}
|
||||
}
|
||||
public record BuildParticipation(String changeId, AssetReference bank, boolean included) implements Mutation {
|
||||
public BuildParticipation { text(changeId); Objects.requireNonNull(bank); }
|
||||
}
|
||||
|
||||
/** Existing opaque bank-local artifact identity, distinct from glyph indices and runtime slots. */
|
||||
public record Artifact(AssetReference bank, String artifactId) {
|
||||
public Artifact {
|
||||
Objects.requireNonNull(bank); text(artifactId);
|
||||
}
|
||||
}
|
||||
public enum ReferenceKind { animation, scene, metadata }
|
||||
public record ReferenceUse(AssetReference owner, ReferenceKind kind, String location, Artifact target) {
|
||||
public ReferenceUse { Objects.requireNonNull(owner); Objects.requireNonNull(kind); text(location); Objects.requireNonNull(target); }
|
||||
}
|
||||
/** Explicit references to update and replacement target; no inferred animation/metadata repair. */
|
||||
public record Rebind(Artifact from, Artifact to, List<ReferenceUse> references) {
|
||||
public Rebind {
|
||||
Objects.requireNonNull(from); Objects.requireNonNull(to); references = List.copyOf(references);
|
||||
if (references.isEmpty() || references.stream().anyMatch(reference -> !reference.target().equals(from)))
|
||||
throw new IllegalArgumentException("Rebind must name affected references to its source");
|
||||
}
|
||||
}
|
||||
/** Descriptive producer metadata does not execute the producer or regenerate dependents. */
|
||||
public record Ownership(AssetReference owner, String outputPath, String producer,
|
||||
List<AssetReference> dependencies, boolean stale) {
|
||||
public Ownership {
|
||||
Objects.requireNonNull(owner); relative(outputPath); text(producer); dependencies = List.copyOf(dependencies);
|
||||
if (new HashSet<>(dependencies).size() != dependencies.size()) throw new IllegalArgumentException("Duplicate dependency");
|
||||
}
|
||||
}
|
||||
public record Request(Revision expectedRevision, List<Mutation> mutations, List<Rebind> rebinds,
|
||||
List<Ownership> ownership) {
|
||||
public Request {
|
||||
Objects.requireNonNull(expectedRevision); mutations = List.copyOf(mutations);
|
||||
rebinds = List.copyOf(rebinds); ownership = List.copyOf(ownership);
|
||||
if (mutations.stream().map(Mutation::changeId).distinct().count() != mutations.size())
|
||||
throw new IllegalArgumentException("Duplicate change ID");
|
||||
}
|
||||
}
|
||||
public enum FileAction { create, replace, delete }
|
||||
public record FileChange(String path, FileAction action, String beforeSha256, String afterSha256) {
|
||||
public FileChange {
|
||||
relative(path); Objects.requireNonNull(action);
|
||||
if (beforeSha256 != null) hash(beforeSha256);
|
||||
if (afterSha256 != null) hash(afterSha256);
|
||||
if (action == FileAction.create && (beforeSha256 != null || afterSha256 == null)
|
||||
|| action == FileAction.replace && (beforeSha256 == null || afterSha256 == null)
|
||||
|| action == FileAction.delete && (beforeSha256 == null || afterSha256 != null))
|
||||
throw new IllegalArgumentException("File action does not match its before/after bytes");
|
||||
}
|
||||
}
|
||||
public record Conflict(String path, String expectedSha256, String observedSha256, String reason) {
|
||||
public Conflict {
|
||||
relative(path); text(reason);
|
||||
if (expectedSha256 != null) hash(expectedSha256);
|
||||
if (observedSha256 != null) hash(observedSha256);
|
||||
}
|
||||
}
|
||||
/** Nullable facts stay unavailable; producer facts are not reconstructed from prose. */
|
||||
public record Diagnostic(String producer, String code, String severity, String message, boolean blocking,
|
||||
String assetRoot, String path, AssetFamily family, List<Integer> missingIndices,
|
||||
List<Integer> duplicateIndices, List<ReferenceUse> references, Long used, Long required, Long limit,
|
||||
Map<String, Object> context) {
|
||||
public Diagnostic {
|
||||
text(producer); text(code); text(severity); Objects.requireNonNull(message);
|
||||
missingIndices = List.copyOf(missingIndices); duplicateIndices = List.copyOf(duplicateIndices);
|
||||
references = List.copyOf(references); context = ValueMaps.object(context);
|
||||
for (Integer index : missingIndices) nonNegative(index.longValue());
|
||||
for (Integer index : duplicateIndices) nonNegative(index.longValue());
|
||||
nonNegative(used); nonNegative(required); nonNegative(limit);
|
||||
}
|
||||
}
|
||||
public enum PreviewState { ready, no_op, conflict, rejected }
|
||||
public record Preview(String batchId, String requestId, Revision revision, Request request, PreviewState state,
|
||||
List<FileChange> files, List<AssetReference> assets, List<ReferenceUse> affectedReferences,
|
||||
List<Ownership> ownership, List<Conflict> conflicts, List<Diagnostic> diagnostics) {
|
||||
public Preview {
|
||||
text(batchId); text(requestId); Objects.requireNonNull(revision); Objects.requireNonNull(request); Objects.requireNonNull(state);
|
||||
files = List.copyOf(files); assets = List.copyOf(assets); affectedReferences = List.copyOf(affectedReferences);
|
||||
ownership = List.copyOf(ownership); conflicts = List.copyOf(conflicts); diagnostics = List.copyOf(diagnostics);
|
||||
if (!revision.equals(request.expectedRevision())) throw new IllegalArgumentException("Preview revision mismatch");
|
||||
if ((state == PreviewState.ready || state == PreviewState.no_op)
|
||||
&& (!conflicts.isEmpty() || diagnostics.stream().anyMatch(Diagnostic::blocking)))
|
||||
throw new IllegalArgumentException("Blocked preview cannot be ready");
|
||||
if (state == PreviewState.no_op && !files.isEmpty()) throw new IllegalArgumentException("No-op cannot change files");
|
||||
}
|
||||
public boolean canCommit() { return state == PreviewState.ready || state == PreviewState.no_op; }
|
||||
}
|
||||
public enum CommitState { committed, recovered, no_op, conflict, rejected, cancelled }
|
||||
public record Result(String batchId, String requestId, CommitState state, Revision before, Revision after,
|
||||
List<FileChange> files, List<AssetReference> assets, List<Conflict> conflicts, List<Diagnostic> diagnostics) {
|
||||
public Result {
|
||||
text(batchId); text(requestId); Objects.requireNonNull(state); Objects.requireNonNull(before); Objects.requireNonNull(after);
|
||||
files = List.copyOf(files); assets = List.copyOf(assets); conflicts = List.copyOf(conflicts); diagnostics = List.copyOf(diagnostics);
|
||||
boolean applied = state == CommitState.committed || state == CommitState.recovered || state == CommitState.no_op;
|
||||
if (applied && (!conflicts.isEmpty() || diagnostics.stream().anyMatch(Diagnostic::blocking)))
|
||||
throw new IllegalArgumentException("Blocked batch cannot be applied");
|
||||
if ((!applied || state == CommitState.no_op) && (!before.equals(after) || !files.isEmpty()))
|
||||
throw new IllegalArgumentException("Unapplied/no-op batch cannot change published state");
|
||||
}
|
||||
public boolean applied() { return state == CommitState.committed || state == CommitState.recovered || state == CommitState.no_op; }
|
||||
}
|
||||
private static void version(int value) { if (value != CONTRACT_VERSION) throw new IllegalArgumentException("Unsupported asset batch contract"); }
|
||||
private static void hash(String value) { if (value == null || !value.matches("[0-9a-f]{64}")) throw new IllegalArgumentException("Expected SHA-256"); }
|
||||
private static void text(String value) { if (value == null || value.isBlank()) throw new IllegalArgumentException("Expected nonblank value"); }
|
||||
private static void nonNegative(Long value) { if (value != null && value < 0) throw new IllegalArgumentException("Negative fact"); }
|
||||
private static void relative(String value) {
|
||||
text(value); Path path = Path.of(value);
|
||||
if (path.isAbsolute() || path.normalize().startsWith("..") || value.equals(".") || value.contains("\\")
|
||||
|| !path.normalize().toString().equals(value)) throw new IllegalArgumentException("Expected normalized relative path");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package p.studio.api.assets;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/** Bank content and global residency are independent views over the same verified inputs. */
|
||||
public final class AssetBudgets {
|
||||
private AssetBudgets() { }
|
||||
public static final int CONTRACT_VERSION = 1;
|
||||
public enum BankType {
|
||||
glyph, sound, scene;
|
||||
public String runtimeTag(){return this==sound?"SOUNDS":name().toUpperCase(Locale.ROOT);}
|
||||
}
|
||||
public enum QualificationState { known, unknown }
|
||||
|
||||
public record BoundaryEvidence(BankType bankType, int acceptedPreloads, int rejectedPreloads,
|
||||
String evidencePath, String evidenceSha256) {
|
||||
public BoundaryEvidence {
|
||||
Objects.requireNonNull(bankType); text(evidencePath); hash(evidenceSha256);
|
||||
if (acceptedPreloads < 1 || (long) rejectedPreloads != (long) acceptedPreloads + 1)
|
||||
throw new IllegalArgumentException("Qualification must cover the accepted limit and next rejected count");
|
||||
}
|
||||
}
|
||||
/** Distributed only after installed-process qualification; never inferred from a runtime family. */
|
||||
public record Profile(int contractVersion, String profileId, String runtimeVersion, String executableSha256,
|
||||
Map<BankType, Integer> limits, List<BoundaryEvidence> evidence) {
|
||||
public Profile {
|
||||
if (contractVersion != CONTRACT_VERSION) throw new IllegalArgumentException("Unsupported capacity profile contract");
|
||||
text(profileId); text(runtimeVersion); hash(executableSha256); limits = Map.copyOf(limits); evidence = List.copyOf(evidence);
|
||||
if (limits.isEmpty() || limits.values().stream().anyMatch(limit -> limit < 1))
|
||||
throw new IllegalArgumentException("Profile requires positive limits for its explicitly qualified bank types");
|
||||
var covered = new EnumMap<BankType, Integer>(BankType.class);
|
||||
for (var boundary : evidence) {
|
||||
if (covered.put(boundary.bankType(), boundary.acceptedPreloads()) != null)
|
||||
throw new IllegalArgumentException("Duplicate bank qualification");
|
||||
}
|
||||
if (!covered.equals(limits)) throw new IllegalArgumentException("Every limit requires matching boundary evidence");
|
||||
}
|
||||
}
|
||||
public record ProfileSelection(QualificationState state, String selectedExecutableSha256, Profile profile, String reason) {
|
||||
public ProfileSelection {
|
||||
Objects.requireNonNull(state); Objects.requireNonNull(reason);
|
||||
if (selectedExecutableSha256 != null) hash(selectedExecutableSha256);
|
||||
if (state == QualificationState.known && (profile == null || !profile.executableSha256().equals(selectedExecutableSha256)))
|
||||
throw new IllegalArgumentException("Known profile requires the exact selected executable");
|
||||
if (state == QualificationState.unknown && profile != null)
|
||||
throw new IllegalArgumentException("Unknown qualification cannot expose a selected profile");
|
||||
}
|
||||
public static ProfileSelection unknown(String selectedExecutableSha256, String reason) {
|
||||
text(reason); return new ProfileSelection(QualificationState.unknown, selectedExecutableSha256, null, reason);
|
||||
}
|
||||
}
|
||||
public record Bank(AssetReference asset, String path) {
|
||||
public Bank { Objects.requireNonNull(asset); text(path); }
|
||||
}
|
||||
/** Slot comes from the final packer preload list, independently of AssetId. */
|
||||
public record Preload(Bank bank, int slot, List<AssetReference> dependencies) {
|
||||
public Preload {
|
||||
Objects.requireNonNull(bank); dependencies = List.copyOf(dependencies);
|
||||
if (slot < 0 || new HashSet<>(dependencies).size() != dependencies.size())
|
||||
throw new IllegalArgumentException("Invalid preload slot/dependencies");
|
||||
}
|
||||
}
|
||||
public record Content(AssetReference asset, BankType bankType, String unit, long used, Long limit) {
|
||||
public Content {
|
||||
Objects.requireNonNull(asset); Objects.requireNonNull(bankType); text(unit);
|
||||
if (used < 0 || limit != null && limit < 0) throw new IllegalArgumentException("Negative content capacity");
|
||||
}
|
||||
}
|
||||
public record Pool(BankType bankType, List<Bank> existing, List<Bank> buildIncluded,
|
||||
List<Preload> effectivePreload, List<Bank> potentialDynamic, Integer limit) {
|
||||
public Pool {
|
||||
Objects.requireNonNull(bankType); existing = List.copyOf(existing); buildIncluded = List.copyOf(buildIncluded);
|
||||
effectivePreload = List.copyOf(effectivePreload); potentialDynamic = List.copyOf(potentialDynamic);
|
||||
unique(existing); unique(buildIncluded); unique(potentialDynamic);
|
||||
unique(effectivePreload.stream().map(Preload::bank).toList());
|
||||
if (limit != null && limit < 1 || effectivePreload.stream().map(Preload::slot).distinct().count() != effectivePreload.size())
|
||||
throw new IllegalArgumentException("Invalid global capacity or duplicate preload slot");
|
||||
}
|
||||
public int requiredSlots() { return effectivePreload.size(); }
|
||||
public boolean exceedsKnownLimit() { return limit != null && requiredSlots() > limit; }
|
||||
/** A warning about potential loads, never proof of simultaneous residency. */
|
||||
public boolean potentialExceedsKnownLimit() {
|
||||
if (limit == null) return false;
|
||||
var assets = new HashSet<AssetReference>();
|
||||
effectivePreload.forEach(preload -> assets.add(preload.bank().asset()));
|
||||
potentialDynamic.forEach(bank -> assets.add(bank.asset()));
|
||||
return assets.size() > limit;
|
||||
}
|
||||
}
|
||||
public record Snapshot(AssetBatches.Revision revision, ProfileSelection qualification, List<Content> content,
|
||||
List<Pool> pools, List<AssetBatches.Diagnostic> diagnostics) {
|
||||
public Snapshot {
|
||||
Objects.requireNonNull(revision); Objects.requireNonNull(qualification);
|
||||
content = List.copyOf(content); pools = List.copyOf(pools); diagnostics = List.copyOf(diagnostics);
|
||||
if (pools.stream().map(Pool::bankType).distinct().count() != pools.size())
|
||||
throw new IllegalArgumentException("Duplicate global pool");
|
||||
for (var pool : pools) {
|
||||
Integer qualifiedLimit = qualification.profile() == null ? null : qualification.profile().limits().get(pool.bankType());
|
||||
if (!Objects.equals(qualifiedLimit, pool.limit()))
|
||||
throw new IllegalArgumentException("Pool limit must come from the selected qualified profile");
|
||||
}
|
||||
if (qualification.state() == QualificationState.known
|
||||
&& !pools.stream().map(Pool::bankType).collect(java.util.stream.Collectors.toSet()).containsAll(qualification.profile().limits().keySet()))
|
||||
throw new IllegalArgumentException("Known qualification requires every qualified pool");
|
||||
}
|
||||
public boolean buildAllowed() {
|
||||
return diagnostics.stream().noneMatch(AssetBatches.Diagnostic::blocking)
|
||||
&& content.stream().noneMatch(item -> item.limit() != null && item.used() > item.limit())
|
||||
&& pools.stream().noneMatch(Pool::exceedsKnownLimit);
|
||||
}
|
||||
public boolean managedExecutionAllowed() {
|
||||
return qualification.state() == QualificationState.known && buildAllowed()
|
||||
&& pools.stream().allMatch(pool -> pool.requiredSlots()==0 || pool.limit() != null);
|
||||
}
|
||||
}
|
||||
private static void unique(List<Bank> values) {
|
||||
if (values.stream().map(Bank::asset).distinct().count() != values.size())
|
||||
throw new IllegalArgumentException("A bank cannot consume multiple slots in the same view");
|
||||
}
|
||||
private static void text(String value) { if (value == null || value.isBlank()) throw new IllegalArgumentException("Expected nonblank value"); }
|
||||
private static void hash(String value) { if (value == null || !value.matches("[0-9a-f]{64}")) throw new IllegalArgumentException("Expected SHA-256"); }
|
||||
}
|
||||
@@ -7,5 +7,7 @@ public record AssetDiagnostic(
|
||||
String category,
|
||||
String message,
|
||||
Path evidencePath,
|
||||
boolean blocking) {
|
||||
boolean blocking, String producer, String code, java.util.Map<String,Object> context) {
|
||||
public AssetDiagnostic(String severity,String category,String message,Path evidencePath,boolean blocking){this(severity,category,message,evidencePath,blocking,"packer",null,java.util.Map.of());}
|
||||
public AssetDiagnostic {context=p.studio.api.values.ValueMaps.object(context);}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
package p.studio.api.assets;
|
||||
|
||||
public record AssetPackDiagnostic(String severity, String message, boolean blocking) {
|
||||
public record AssetPackDiagnostic(String severity,String message,boolean blocking,String producer,String code,
|
||||
java.nio.file.Path evidencePath,java.util.Map<String,Object> context) {
|
||||
public AssetPackDiagnostic(String severity,String message,boolean blocking){this(severity,message,blocking,"packer",null,null,java.util.Map.of());}
|
||||
public AssetPackDiagnostic {context=p.studio.api.values.ValueMaps.object(context);}
|
||||
}
|
||||
|
||||
@@ -8,8 +8,9 @@ public record AssetPackExecution(
|
||||
String canonicalArtifactName,
|
||||
int packedAssetCount,
|
||||
long elapsedMillis,
|
||||
List<AssetEmittedArtifact> emittedArtifacts) {
|
||||
List<AssetEmittedArtifact> emittedArtifacts, List<AssetPackDiagnostic> diagnostics) {
|
||||
public AssetPackExecution(AssetOperationStatus status,String summary,String name,int count,long elapsed,List<AssetEmittedArtifact> emitted){this(status,summary,name,count,elapsed,emitted,List.of());}
|
||||
public AssetPackExecution {
|
||||
emittedArtifacts = List.copyOf(emittedArtifacts);
|
||||
emittedArtifacts = List.copyOf(emittedArtifacts);diagnostics=List.copyOf(diagnostics);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,11 @@ import java.util.LinkedHashMap;
|
||||
import java.util.Collections;
|
||||
|
||||
/** Stable domain failure codes, independent of HTTP status and JSON-RPC errors. */
|
||||
public record AutomationFailure(Code code, String message, Map<String, Object> runtimeError, Map<String, Object> details) {
|
||||
public record AutomationFailure(Code code, String message, Map<String, Object> runtimeError, Map<String, Object> details,
|
||||
RuntimeObservation observation) {
|
||||
public AutomationFailure(Code code, String message, Map<String, Object> runtimeError, Map<String, Object> details) {
|
||||
this(code, message, runtimeError, details, null);
|
||||
}
|
||||
public AutomationFailure(Code code, String message) { this(code, message, Map.of()); }
|
||||
public AutomationFailure(Code code, String message, Map<String, Object> runtimeError) { this(code, message, runtimeError, Map.of()); }
|
||||
public enum Code {
|
||||
@@ -24,7 +28,7 @@ public record AutomationFailure(Code code, String message, Map<String, Object> r
|
||||
var copy = new LinkedHashMap<String, Object>();
|
||||
if (runtimeError != null) runtimeError.forEach((key, value) -> copy.put(key, freeze(value)));
|
||||
runtimeError = Collections.unmodifiableMap(copy);
|
||||
details = p.studio.utilities.json.ImmutableJson.object(details);
|
||||
details = p.studio.api.values.ValueMaps.object(details);
|
||||
}
|
||||
private static Object freeze(Object value) {
|
||||
if (value instanceof Map<?, ?> map) {
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
package p.studio.api.automation;
|
||||
import java.util.List;
|
||||
public record AutomationOutcome(Kind kind, long requestedFrames, long completedFrames,
|
||||
List<String> diagnostics, CanonicalCapture capture, java.util.Map<String, Object> diagnosticResult) {
|
||||
List<String> diagnostics, CanonicalCapture capture, java.util.Map<String, Object> diagnosticResult,
|
||||
RuntimeObservation observation) {
|
||||
public AutomationOutcome(Kind kind, long requestedFrames, long completedFrames, List<String> diagnostics, CanonicalCapture capture, java.util.Map<String, Object> diagnosticResult) {
|
||||
this(kind, requestedFrames, completedFrames, diagnostics, capture, diagnosticResult, null);
|
||||
}
|
||||
public AutomationOutcome(Kind kind, long requestedFrames, long completedFrames, List<String> diagnostics, CanonicalCapture capture) {
|
||||
this(kind, requestedFrames, completedFrames, diagnostics, capture, java.util.Map.of());
|
||||
}
|
||||
public enum Kind { SUCCEEDED, TERMINATED, GUEST_FAULT, INFRASTRUCTURE_FAILURE, CANCELLED, ACTION_REQUIRED }
|
||||
public AutomationOutcome { diagnostics = List.copyOf(diagnostics); diagnosticResult = p.studio.utilities.json.ImmutableJson.object(diagnosticResult); }
|
||||
public AutomationOutcome { diagnostics = List.copyOf(diagnostics); diagnosticResult = p.studio.api.values.ValueMaps.object(diagnosticResult); }
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import p.studio.api.operation.OperationHandle;
|
||||
import p.studio.api.operation.OperationSubscription;
|
||||
public interface AutomationSession {
|
||||
AutomationSnapshot snapshot();
|
||||
default boolean runtimeAttached() { return false; }
|
||||
OperationSubscription subscribe(Consumer<AutomationSnapshot> listener);
|
||||
OperationSubscription registerDocuments(DocumentHandoff documents);
|
||||
CompletionStage<ControlResult> grant(boolean saveUnsavedDocuments);
|
||||
@@ -18,10 +19,13 @@ public interface AutomationSession {
|
||||
CompletionStage<ControlResult> closeAsync();
|
||||
/** Internal specialized service work, not a generic MCP shell/tool endpoint. */
|
||||
OperationHandle<AutomationOutcome> submit(TaskIdentity task, String summary, Callable<AutomationOutcome> work);
|
||||
/** Null identity is reserved for a local manual service holding an active manual lease. */
|
||||
void attachRuntime(TaskIdentity task, ManagedHeadlessSession runtime);
|
||||
/** Called only after shutdown has completed, before artifacts can be rebuilt. */
|
||||
void detachRuntime(TaskIdentity task, ManagedHeadlessSession runtime);
|
||||
void markCaptureStale();
|
||||
/** Publish passive runtime facts; late observations after task revocation are ignored. */
|
||||
default void runtimeObserved(TaskIdentity task) { }
|
||||
/** Cleanup runs after workers stop and before returning manual control. */
|
||||
void onTaskEnd(TaskIdentity task, Runnable cleanup);
|
||||
}
|
||||
|
||||
@@ -4,11 +4,18 @@ import java.util.List;
|
||||
import p.studio.api.operation.OperationSnapshot;
|
||||
public record AutomationSnapshot(Path projectRoot, ControlState state, boolean handoffPending,
|
||||
boolean closed, int manualOperations, TaskIdentity task, OperationSnapshot operation,
|
||||
CanonicalCapture capture, boolean stale, List<String> diagnostics, List<String> calls, java.util.Map<String, Object> diagnosticResult) {
|
||||
CanonicalCapture capture, boolean stale, List<String> diagnostics, List<String> calls, java.util.Map<String, Object> diagnosticResult,
|
||||
RuntimeObservation runtimeObservation, ControlObservation controlObservation, RuntimeObservation operationObservation) {
|
||||
public AutomationSnapshot(Path root, ControlState state, boolean pending, boolean closed, int manualOperations, TaskIdentity task, OperationSnapshot operation, CanonicalCapture capture, boolean stale, List<String> diagnostics, List<String> calls, java.util.Map<String, Object> diagnosticResult, RuntimeObservation runtime, ControlObservation control) {
|
||||
this(root, state, pending, closed, manualOperations, task, operation, capture, stale, diagnostics, calls, diagnosticResult, runtime, control, null);
|
||||
}
|
||||
public AutomationSnapshot(Path root, ControlState state, boolean pending, boolean closed, int manualOperations, TaskIdentity task, OperationSnapshot operation, CanonicalCapture capture, boolean stale, List<String> diagnostics, List<String> calls, java.util.Map<String, Object> diagnosticResult) {
|
||||
this(root, state, pending, closed, manualOperations, task, operation, capture, stale, diagnostics, calls, diagnosticResult, RuntimeObservation.unknown(null, null), null);
|
||||
}
|
||||
public AutomationSnapshot(Path root, ControlState state, boolean pending, boolean closed, int manualOperations, TaskIdentity task, OperationSnapshot operation, CanonicalCapture capture, boolean stale, List<String> diagnostics, List<String> calls) {
|
||||
this(root, state, pending, closed, manualOperations, task, operation, capture, stale, diagnostics, calls, java.util.Map.of());
|
||||
}
|
||||
public AutomationSnapshot { diagnostics = List.copyOf(diagnostics); calls = List.copyOf(calls); diagnosticResult = p.studio.utilities.json.ImmutableJson.object(diagnosticResult); }
|
||||
public AutomationSnapshot { diagnostics = List.copyOf(diagnostics); calls = List.copyOf(calls); diagnosticResult = p.studio.api.values.ValueMaps.object(diagnosticResult); }
|
||||
public boolean manualAllowed() { return !closed && !handoffPending && state == ControlState.MANUAL; }
|
||||
public boolean canGrant() { return manualAllowed() && manualOperations == 0; }
|
||||
public boolean canReclaim() { return !closed && state != ControlState.MANUAL; }
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package p.studio.api.automation;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/** Explicit build identity; a target never changes the machine mode or app identity. */
|
||||
public record BuildSelection(String targetId, String buildId) {
|
||||
public BuildSelection {
|
||||
targetId = targetId == null ? GuestTests.PRODUCTION : targetId;
|
||||
if (!targetId.matches("[A-Za-z0-9][A-Za-z0-9_.-]{0,127}") || buildId == null
|
||||
|| !buildId.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"))
|
||||
throw new IllegalArgumentException("Invalid build target/identity");
|
||||
}
|
||||
public boolean production() { return GuestTests.PRODUCTION.equals(targetId); }
|
||||
public static BuildSelection productionBuild() { return new BuildSelection(GuestTests.PRODUCTION, UUID.randomUUID().toString()); }
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package p.studio.api.automation;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/** Current authority and cleanup are independent of an operation's success or failure. */
|
||||
public record ControlObservation(ControlState state, Cleanup cleanup, boolean taskRevoked,
|
||||
boolean closed, AutomationFailure failure) {
|
||||
public enum Cleanup { NOT_REQUIRED, PENDING, COMPLETED, FAILED }
|
||||
public ControlObservation { Objects.requireNonNull(state); Objects.requireNonNull(cleanup); }
|
||||
public java.util.Map<String, Object> toMap() {
|
||||
return p.studio.api.values.ValueMaps.fields("state", state.name(), "cleanup", cleanup.name(),
|
||||
"taskRevoked", taskRevoked, "closed", closed, "failure", failure == null ? null
|
||||
: p.studio.api.values.ValueMaps.fields("code", failure.code().name(), "message", failure.message(),
|
||||
"runtimeError", failure.runtimeError(), "details", failure.details(),
|
||||
"observation", failure.observation() == null ? null : failure.observation().toMap()));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package p.studio.api.automation;
|
||||
public record ControlResult(Status status, TaskIdentity task, String diagnostic) {
|
||||
public record ControlResult(Status status, TaskIdentity task, String diagnostic, ControlObservation observation) {
|
||||
public ControlResult(Status status, TaskIdentity task, String diagnostic) { this(status, task, diagnostic, null); }
|
||||
public ControlResult withObservation(ControlObservation value) { return new ControlResult(status, task, diagnostic, value); }
|
||||
public enum Status { GRANTED, ACQUIRED, RETURNED, BUSY, DIRTY_DOCUMENTS, SAVE_FAILED, CONNECTION_FAILED, CONNECTION_CONFLICT, NOT_GRANTED, INVALID_TASK, CLOSED, CLEANUP_FAILED }
|
||||
public boolean success() { return status == Status.GRANTED || status == Status.ACQUIRED || status == Status.RETURNED; }
|
||||
public static ControlResult of(Status status, String message) { return new ControlResult(status, null, message); }
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
package p.studio.api.automation;
|
||||
|
||||
import p.studio.api.values.ValueMaps;
|
||||
import java.util.*;
|
||||
|
||||
/** Neutral immutable visual evidence. Image bytes and historical identities never change. */
|
||||
public final class Evidence {
|
||||
private Evidence() {}
|
||||
public static final long DEFAULT_QUOTA = 512L * 1024 * 1024;
|
||||
public static final int MAX_READ = 1024 * 1024;
|
||||
public record Pixels(int width, int height, byte[] rgba) {
|
||||
public Pixels {
|
||||
if (width <= 0 || height <= 0 || (long) width * height > 16_777_216
|
||||
|| (long) width * height * 4 != rgba.length) throw new IllegalArgumentException("Invalid RGBA8 layout");
|
||||
rgba = rgba.clone();
|
||||
}
|
||||
@Override public byte[] rgba() { return rgba.clone(); }
|
||||
public int channel(int x, int y, int channel) {
|
||||
if (x < 0 || y < 0 || x >= width || y >= height || channel < 0 || channel > 3)
|
||||
throw new IllegalArgumentException("Invalid RGBA coordinate");
|
||||
return Byte.toUnsignedInt(rgba[(y * width + x) * 4 + channel]);
|
||||
}
|
||||
}
|
||||
public record Rect(int x, int y, int width, int height) {
|
||||
public Rect {
|
||||
if (x < 0 || y < 0 || width <= 0 || height <= 0) throw new IllegalArgumentException("Invalid rectangle");
|
||||
}
|
||||
public boolean contains(int px, int py) {
|
||||
return px >= x && py >= y && (long)px < (long)x + width && (long)py < (long)y + height;
|
||||
}
|
||||
public void requireInside(int w, int h) {
|
||||
if ((long)x + width > w || (long)y + height > h) throw new IllegalArgumentException("Rectangle exceeds image bounds");
|
||||
}
|
||||
}
|
||||
public enum Alpha { compare, ignore }
|
||||
public record Parameters(Rect roi, List<Rect> masks, Alpha alpha, int channelLimit, long allowedDifferentPixels) {
|
||||
public Parameters {
|
||||
Objects.requireNonNull(alpha, "Explicit alpha policy required");
|
||||
masks = List.copyOf(masks == null ? List.of() : masks);
|
||||
if (masks.size() > 1024 || channelLimit < 0 || channelLimit > 255 || allowedDifferentPixels < 0)
|
||||
throw new IllegalArgumentException("Invalid comparison parameters");
|
||||
}
|
||||
public static Parameters exact(Alpha alpha) { return new Parameters(null, List.of(), alpha, 0, 0); }
|
||||
}
|
||||
public record Artifact(String id, String publicationId, String sha256, long byteSize, String mime,
|
||||
int width, int height, Map<String,Object> provenance) {
|
||||
public Artifact {
|
||||
Objects.requireNonNull(id); Objects.requireNonNull(publicationId); Objects.requireNonNull(sha256);
|
||||
if (!id.matches("[a-f0-9-]{36}") || !publicationId.matches("[a-f0-9-]{36}") || !sha256.matches("[a-f0-9]{64}")
|
||||
|| byteSize <= 0 || byteSize > 32L*1024*1024 || !"image/png".equals(mime)
|
||||
|| width <= 0 || height <= 0 || (long)width*height > 16_777_216)
|
||||
throw new IllegalArgumentException("Invalid evidence metadata");
|
||||
provenance = normalizeProvenance(provenance);
|
||||
}
|
||||
}
|
||||
public enum Verdict { passed, rejected, dimension_mismatch }
|
||||
public record Report(String id, String expectedId, String actualId, String diffId,
|
||||
String expectedSha256, String actualSha256, Parameters parameters, Verdict verdict,
|
||||
long comparedPixels, long differentPixels, int maximumChannelError, Rect boundingBox) {}
|
||||
public record Baseline(String id, String previousRevision, String artifactId,
|
||||
Map<String,Object> origin, String reviewedAt) {
|
||||
public Baseline { origin = normalizeProvenance(origin); }
|
||||
}
|
||||
public record Publication(String id, String requestId, String parameterKey, String projectRoot,
|
||||
String createdAt, List<Artifact> artifacts, Report report, Baseline baseline) {
|
||||
public Publication { artifacts = List.copyOf(artifacts); }
|
||||
}
|
||||
public record Blob(Artifact artifact, byte[] bytes) {
|
||||
public Blob { bytes = bytes.clone(); }
|
||||
@Override public byte[] bytes() { return bytes.clone(); }
|
||||
}
|
||||
public record View(Artifact artifact, boolean stale) {}
|
||||
public record Read(String artifactId, long offset, long totalBytes, byte[] bytes) {
|
||||
public Read { bytes = bytes.clone(); }
|
||||
@Override public byte[] bytes() { return bytes.clone(); }
|
||||
}
|
||||
public record ImportedReference(byte[] bytes, String canonicalPath, boolean humanAuthorized) {
|
||||
public ImportedReference { bytes = bytes.clone(); Objects.requireNonNull(canonicalPath); }
|
||||
@Override public byte[] bytes() { return bytes.clone(); }
|
||||
}
|
||||
private static Map<String,Object> normalizeProvenance(Map<String,Object> values) {
|
||||
var normalized = new LinkedHashMap<String,Object>(values);
|
||||
for (var key : List.of("logicalFrameIndex", "frameId")) if (normalized.get(key) != null) {
|
||||
var value = new java.math.BigInteger(normalized.get(key).toString());
|
||||
if (value.signum() < 0 || value.bitLength() > 64) throw new IllegalArgumentException("Frame identity must be uint64");
|
||||
normalized.put(key, value);
|
||||
}
|
||||
return ValueMaps.object(normalized);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package p.studio.api.automation;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
/** Concrete filesystem publication and codec work belongs to the application adapter. */
|
||||
public interface EvidenceStore {
|
||||
List<Evidence.Publication> list(Path root);
|
||||
Evidence.Publication publish(Path root, Evidence.Publication publication, List<Evidence.Blob> objects);
|
||||
Evidence.Read read(Path root, String artifactId, long offset, int length);
|
||||
byte[] image(Path root, String artifactId);
|
||||
Evidence.ImportedReference importReference(Path root, Path source, String humanGrant);
|
||||
String authorizeReference(Path root, Path source);
|
||||
void delete(Path root, String publicationId);
|
||||
interface Codec {
|
||||
Evidence.Pixels decode(byte[] png);
|
||||
byte[] encode(Evidence.Pixels pixels);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package p.studio.api.automation;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
/** Task-scoped evidence operations; null task is reserved for local read-only human inspection. */
|
||||
public interface EvidenceTools {
|
||||
Evidence.Publication persist(Path root, String taskId, String requestId, OperationLookup operation);
|
||||
Evidence.Publication importReference(Path root, String taskId, String requestId, Path source, String humanGrant);
|
||||
Evidence.Publication compare(Path root, String taskId, String requestId, String expectedId, String actualId, Evidence.Parameters parameters);
|
||||
List<Evidence.Publication> list(Path root, String taskId);
|
||||
Evidence.View metadata(Path root, String taskId, String artifactId);
|
||||
Evidence.Read read(Path root, String taskId, String artifactId, long offset, int length);
|
||||
byte[] image(Path root, String taskId, String artifactId);
|
||||
Evidence.Pixels pixels(Path root, String taskId, String artifactId);
|
||||
void delete(Path root, String taskId, String publicationId);
|
||||
String authorizeReference(Path root, Path source);
|
||||
Evidence.Publication approveBaseline(Path root, String artifactId, String previousRevision);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package p.studio.api.automation;
|
||||
|
||||
import p.studio.api.operation.OperationSnapshot;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
/** Shared human/task tests. Null task is a local human entry point, never an MCP default. */
|
||||
public interface GuestTestTools {
|
||||
enum Media { memory_fresh, disposable_create, disposable_reopen }
|
||||
record Request(String targetId, long maxFrames, int blockFrames, long timeoutMs,
|
||||
Media media, String reopenRunId, boolean discardUnsaved) {
|
||||
public Request {
|
||||
targetId = new GuestTests.Selection(targetId).targetId();
|
||||
if (GuestTests.PRODUCTION.equals(targetId)) throw new IllegalArgumentException("Select a declared test target");
|
||||
Objects.requireNonNull(media);
|
||||
if (maxFrames < 1 || maxFrames > 1_000_000 || blockFrames < 1 || blockFrames > 60 || timeoutMs < 1 || timeoutMs > 3_600_000)
|
||||
throw new IllegalArgumentException("Invalid bounded test request");
|
||||
if ((media == Media.disposable_reopen) != (reopenRunId != null)) throw new IllegalArgumentException("Reopen explicitly identifies an earlier run image");
|
||||
if (reopenRunId != null) java.util.UUID.fromString(reopenRunId);
|
||||
}
|
||||
}
|
||||
record View(OperationSnapshot operation, String clientRequestId, String runId, boolean workerTerminated,
|
||||
TrackedOperation.Progress progress, GuestTests.RunResult result, RuntimeObservation currentObservation, boolean runtimeRetained) { }
|
||||
record TranscriptPage(String runId, int offset, int nextOffset, int total, List<GuestTests.TranscriptEvent> events) {
|
||||
public TranscriptPage { events = List.copyOf(events); }
|
||||
}
|
||||
GuestTests.Catalog targets(Path root, String taskId);
|
||||
View start(Path root, String taskId, String clientRequestId, Request request);
|
||||
View get(Path root, String taskId, OperationLookup lookup);
|
||||
List<View> list(Path root, String taskId);
|
||||
boolean cancel(Path root, String taskId, String operationId);
|
||||
TranscriptPage transcript(Path root, String taskId, OperationLookup lookup, int offset, int limit);
|
||||
/** Explicit recovery for a retained native dirty/pending-data shutdown refusal. */
|
||||
void shutdown(Path root, String taskId, String operationId, boolean discardUnsaved);
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package p.studio.api.automation;
|
||||
|
||||
import p.studio.api.values.ValueMaps;
|
||||
import java.math.BigInteger;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
|
||||
/** Isolated target and transcript contracts; independent of compiler ASTs and runtime wire codecs. */
|
||||
public final class GuestTests {
|
||||
private GuestTests() {}
|
||||
public static final String PRODUCTION = "production";
|
||||
public static final int SCHEMA_VERSION = 1;
|
||||
public record Target(String id, String entrypoint, List<String> sourceRoots, List<String> supportRoots,
|
||||
List<String> exclusions, List<String> cases, int logTag) {
|
||||
public Target {
|
||||
identifier(id);
|
||||
if (PRODUCTION.equals(id)) throw new IllegalArgumentException("production is reserved");
|
||||
entrypoint = relative(entrypoint);
|
||||
sourceRoots = paths(sourceRoots); supportRoots = paths(supportRoots); exclusions = paths(exclusions);
|
||||
cases = List.copyOf(cases); cases.forEach(GuestTests::identifier);
|
||||
if (sourceRoots.isEmpty() || new HashSet<>(cases).size() != cases.size() || logTag < 0 || logTag > 65535)
|
||||
throw new IllegalArgumentException("Invalid test target");
|
||||
if (exclusions.contains(entrypoint)) throw new IllegalArgumentException("Entrypoint cannot be excluded");
|
||||
}
|
||||
}
|
||||
public record Catalog(int schemaVersion, List<Target> targets) {
|
||||
public Catalog {
|
||||
if (schemaVersion != SCHEMA_VERSION) throw new IllegalArgumentException("Unsupported testTargets schemaVersion");
|
||||
targets = List.copyOf(targets);
|
||||
if (targets.stream().map(Target::id).distinct().count() != targets.size())
|
||||
throw new IllegalArgumentException("Duplicate test target ID");
|
||||
}
|
||||
public static Catalog empty() { return new Catalog(SCHEMA_VERSION, List.of()); }
|
||||
}
|
||||
public record Selection(String targetId) {
|
||||
public Selection { targetId = targetId == null ? PRODUCTION : targetId; identifier(targetId); }
|
||||
public boolean production() { return PRODUCTION.equals(targetId); }
|
||||
}
|
||||
public record BuildProvenance(String targetId, String buildId, String entrypoint,
|
||||
Map<String,String> sourceSha256, Map<String,String> assetSha256, Map<String,String> dependencySha256,
|
||||
Map<String,Object> configuration, String revision) {
|
||||
public BuildProvenance {
|
||||
identifier(targetId); Objects.requireNonNull(buildId); Objects.requireNonNull(revision);
|
||||
sourceSha256 = Map.copyOf(sourceSha256); assetSha256 = Map.copyOf(assetSha256); dependencySha256 = Map.copyOf(dependencySha256);
|
||||
configuration = ValueMaps.object(configuration);
|
||||
}
|
||||
}
|
||||
public enum EventKind { suite_start, case_start, assertion, checkpoint, case_end, suite_end }
|
||||
public record Event(int schemaVersion, String suiteId, String caseId, String eventId, EventKind kind, Map<String,Object> payload) {
|
||||
public Event {
|
||||
if (schemaVersion != SCHEMA_VERSION) throw new IllegalArgumentException("Unsupported assertion schemaVersion");
|
||||
identifier(suiteId); identifier(eventId); if (caseId != null) identifier(caseId);
|
||||
Objects.requireNonNull(kind); payload = ValueMaps.object(payload);
|
||||
}
|
||||
}
|
||||
public record LogEvent(BigInteger sequence, BigInteger frame, BigInteger timestampMs,
|
||||
String level, String source, Long appId, int tag, String message) {
|
||||
public LogEvent {
|
||||
uint64(sequence); uint64(frame); uint64(timestampMs); Objects.requireNonNull(level); Objects.requireNonNull(source); Objects.requireNonNull(message);
|
||||
if (tag < 0 || tag > 65535 || appId != null && (appId < 0 || appId > 0xffff_ffffL)) throw new IllegalArgumentException("Invalid log source/tag");
|
||||
if (!Set.of("trace","debug","info","warn","error").contains(level) || !Set.of("pos","hub","vm","fs","app").contains(source)
|
||||
|| source.equals("app") != (appId != null)) throw new IllegalArgumentException("Invalid typed log level/source");
|
||||
}
|
||||
}
|
||||
public record LogPage(String sessionId, BigInteger logEpoch, List<LogEvent> events, BigInteger oldestSequence,
|
||||
BigInteger newestSequence, BigInteger nextAfterSequence, boolean gap, boolean overflow) {
|
||||
public LogPage {
|
||||
Objects.requireNonNull(sessionId); if (sessionId.isBlank()) throw new IllegalArgumentException("Empty log session identity");
|
||||
uint64(logEpoch); events = List.copyOf(events);
|
||||
if (events.size() > 1024) throw new IllegalArgumentException("Log page exceeds limit");
|
||||
nullableUint64(oldestSequence); nullableUint64(newestSequence); nullableUint64(nextAfterSequence);
|
||||
if ((oldestSequence == null) != (newestSequence == null)
|
||||
|| oldestSequence != null && oldestSequence.compareTo(newestSequence) > 0) throw new IllegalArgumentException("Invalid retention bounds");
|
||||
BigInteger prior = null;
|
||||
for (var event : events) {
|
||||
if (oldestSequence == null || event.sequence().compareTo(oldestSequence) < 0 || event.sequence().compareTo(newestSequence) > 0
|
||||
|| prior != null && !event.sequence().equals(prior.add(BigInteger.ONE))) throw new IllegalArgumentException("Invalid event sequence");
|
||||
prior = event.sequence();
|
||||
}
|
||||
if (prior != null && !prior.equals(nextAfterSequence)) throw new IllegalArgumentException("Cursor must identify the final returned event");
|
||||
}
|
||||
}
|
||||
public enum CaseState { passed, failed, not_run, infrastructure_failure }
|
||||
public enum Completion { running, completed, timed_out, cancelled, infrastructure_failure }
|
||||
public record Assertion(String name, String message, Object expected, Object actual, boolean passed,
|
||||
boolean expectedAvailable, boolean actualAvailable) {
|
||||
public Assertion(String name, String message, Object expected, Object actual, boolean passed) {
|
||||
this(name, message, expected, actual, passed, true, true);
|
||||
}
|
||||
public Assertion {
|
||||
Objects.requireNonNull(name); Objects.requireNonNull(message);
|
||||
var frozen = ValueMaps.fields("expected", expected, "actual", actual); expected = frozen.get("expected"); actual = frozen.get("actual");
|
||||
}
|
||||
}
|
||||
public record CaseResult(String id, CaseState state, List<Assertion> assertions, List<String> checkpointIds,
|
||||
boolean started, boolean completed) {
|
||||
public CaseResult(String id, CaseState state, List<Assertion> assertions, List<String> checkpointIds) {
|
||||
this(id,state,assertions,checkpointIds,state!=CaseState.not_run,state==CaseState.passed||state==CaseState.failed);
|
||||
}
|
||||
public CaseResult {
|
||||
identifier(id); assertions = List.copyOf(assertions); checkpointIds = List.copyOf(checkpointIds);
|
||||
if (state == null && (!started || completed) || completed && !started) throw new IllegalArgumentException("Invalid case observation");
|
||||
}
|
||||
}
|
||||
@FunctionalInterface public interface Decoder { Event decode(String message); }
|
||||
public record TranscriptEvent(LogEvent nativeEvent, Event event) { public TranscriptEvent { Objects.requireNonNull(nativeEvent); } }
|
||||
public record RunResult(String runId, String targetId, String buildId, String sessionId, String operationId,
|
||||
String clientRequestId, Completion completion, CaseState verdict, boolean suiteComplete, boolean lossDetected,
|
||||
List<CaseResult> cases, List<TranscriptEvent> transcript, AutomationFailure failure, Map<String,Object> context) {
|
||||
public RunResult(String runId, String targetId, String buildId, String sessionId, String operationId,
|
||||
String clientRequestId, Completion completion, CaseState verdict, boolean suiteComplete, boolean lossDetected,
|
||||
List<CaseResult> cases, List<TranscriptEvent> transcript, AutomationFailure failure) {
|
||||
this(runId,targetId,buildId,sessionId,operationId,clientRequestId,completion,verdict,suiteComplete,lossDetected,cases,transcript,failure,Map.of());
|
||||
}
|
||||
public RunResult {
|
||||
Objects.requireNonNull(runId); identifier(targetId); Objects.requireNonNull(completion); Objects.requireNonNull(verdict);
|
||||
cases = List.copyOf(cases); transcript = List.copyOf(transcript); context = ValueMaps.object(context);
|
||||
if (verdict == CaseState.passed && (completion != Completion.completed || !suiteComplete || lossDetected || failure != null
|
||||
|| cases.isEmpty() || cases.stream().anyMatch(c -> c.state() != CaseState.passed || !c.completed())
|
||||
|| cases.stream().flatMap(c -> c.assertions().stream()).noneMatch(Assertion::passed)
|
||||
|| cases.stream().flatMap(c -> c.assertions().stream()).anyMatch(a -> !a.passed())))
|
||||
throw new IllegalArgumentException("Incomplete, empty or failed run cannot pass");
|
||||
}
|
||||
public RunResult withContext(Map<String,Object> additions) {
|
||||
var merged = new LinkedHashMap<>(context); merged.putAll(additions);
|
||||
return new RunResult(runId,targetId,buildId,sessionId,operationId,clientRequestId,completion,verdict,suiteComplete,lossDetected,cases,transcript,failure,merged);
|
||||
}
|
||||
}
|
||||
private static void uint64(BigInteger value) {
|
||||
if (value == null || value.signum() < 0 || value.bitLength() > 64) throw new IllegalArgumentException("Expected uint64");
|
||||
}
|
||||
private static void nullableUint64(BigInteger value) { if (value != null) uint64(value); }
|
||||
private static void identifier(String value) {
|
||||
if (value == null || !value.matches("[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")) throw new IllegalArgumentException("Invalid test identifier");
|
||||
}
|
||||
private static String relative(String value) {
|
||||
Objects.requireNonNull(value); Path path = Path.of(value);
|
||||
if (value.isBlank() || path.isAbsolute() || path.normalize().startsWith("..") || !path.normalize().toString().equals(value)
|
||||
|| value.equals(".") || value.contains("\\")) throw new IllegalArgumentException("Expected normalized project-relative path");
|
||||
return value;
|
||||
}
|
||||
private static List<String> paths(List<String> values) {
|
||||
values = List.copyOf(values); values.forEach(GuestTests::relative);
|
||||
if (new HashSet<>(values).size() != values.size()) throw new IllegalArgumentException("Duplicate target path"); return values;
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@ import java.util.concurrent.CompletionStage;
|
||||
/** Lifecycle port implemented by the process adapter, never by JavaFX. */
|
||||
public interface ManagedHeadlessSession {
|
||||
String sessionId();
|
||||
/** Passive snapshot; never performs native IO or executes the guest. */
|
||||
default RuntimeObservation observation() { return RuntimeObservation.unknown(sessionId(), null); }
|
||||
void cancel();
|
||||
CompletionStage<Void> shutdown();
|
||||
/** Human consent to discard remaining RAM; never inferred from Stop/reclaim. */
|
||||
|
||||
@@ -3,6 +3,8 @@ import java.nio.file.Path;
|
||||
/** Shared service guard. Paths may be project roots or contained asset paths. */
|
||||
public interface ProjectAccess {
|
||||
ManualLease enterManual(Path path);
|
||||
/** Execution owns the manual lane until its runtime has stopped. */
|
||||
default ManualLease enterExecution(Path path) { return enterManual(path); }
|
||||
|
||||
default <R> p.studio.api.operation.OperationHandle<R> submitManual(Path path,
|
||||
p.studio.api.operation.OperationExecutor executor, String summary, java.util.concurrent.Callable<R> work) {
|
||||
|
||||
@@ -40,7 +40,11 @@ public interface ProjectKnowledge {
|
||||
}
|
||||
record Context(Path projectRoot, String projectName, List<Language> languages,
|
||||
List<Library> libraries, List<Path> editableRoots, List<Path> readOnlyRoots,
|
||||
List<Reference> references, List<String> limitations) {
|
||||
List<Reference> references, List<String> limitations, ControlObservation control, RuntimeObservation runtime) {
|
||||
public Context(Path projectRoot, String projectName, List<Language> languages, List<Library> libraries,
|
||||
List<Path> editableRoots, List<Path> readOnlyRoots, List<Reference> references, List<String> limitations) {
|
||||
this(projectRoot, projectName, languages, libraries, editableRoots, readOnlyRoots, references, limitations, null, null);
|
||||
}
|
||||
public Context {
|
||||
projectRoot = Objects.requireNonNull(projectRoot).toAbsolutePath().normalize();
|
||||
Objects.requireNonNull(projectName);
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
package p.studio.api.automation;
|
||||
|
||||
import p.studio.api.values.ValueMaps;
|
||||
import java.math.BigInteger;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
|
||||
/** Immutable known facts, never an instruction to retry a command or discard media. */
|
||||
public record RuntimeObservation(String sessionId, String buildId, Lifecycle lifecycle,
|
||||
String source, String observedAt, TrackedOperation.Progress progress, FrameIdentity lastFrame,
|
||||
boolean captureStale, Map<String, Object> nativeDetails, Map<String, Object> context,
|
||||
List<UnavailableObservation> unavailable, List<RecoveryAction> recovery) {
|
||||
public enum Lifecycle { ABSENT, UNKNOWN, UNBOOTED, BOOTED, GUEST_OBSERVED, LOST, TERMINATED }
|
||||
public record FrameIdentity(BigInteger logicalFrameIndex, BigInteger frameId) {
|
||||
public FrameIdentity {
|
||||
Objects.requireNonNull(logicalFrameIndex); Objects.requireNonNull(frameId);
|
||||
if (logicalFrameIndex.signum() < 0 || logicalFrameIndex.bitLength() > 64
|
||||
|| frameId.signum() < 0 || frameId.bitLength() > 64)
|
||||
throw new IllegalArgumentException("Frame identity must be uint64");
|
||||
}
|
||||
}
|
||||
public record UnavailableObservation(String source, String code, String message,
|
||||
Map<String, Object> nativeError, Map<String, Object> details, String observedAt) {
|
||||
public UnavailableObservation(String source, String code, String message, Map<String, Object> nativeError, Map<String, Object> details) {
|
||||
this(source, code, message, nativeError, details, Instant.now().toString());
|
||||
}
|
||||
public UnavailableObservation {
|
||||
nativeError = ValueMaps.object(nativeError); details = ValueMaps.object(details);
|
||||
}
|
||||
}
|
||||
public record RecoveryAction(String action, List<String> preconditions, boolean automatic) {
|
||||
public RecoveryAction {
|
||||
Objects.requireNonNull(action); preconditions = List.copyOf(preconditions);
|
||||
if (automatic) throw new IllegalArgumentException("Recovery is always explicit");
|
||||
}
|
||||
}
|
||||
public RuntimeObservation {
|
||||
Objects.requireNonNull(lifecycle); Objects.requireNonNull(source); Objects.requireNonNull(observedAt);
|
||||
Objects.requireNonNull(progress);
|
||||
nativeDetails = ValueMaps.object(nativeDetails); context = ValueMaps.object(context);
|
||||
unavailable = List.copyOf(unavailable); recovery = List.copyOf(recovery);
|
||||
}
|
||||
public static RuntimeObservation absent() { return unknown(null, null).transition(Lifecycle.ABSENT, "studio", Map.of()); }
|
||||
public static RuntimeObservation unknown(String session, String build) {
|
||||
return new RuntimeObservation(session, build, Lifecycle.UNKNOWN, "unavailable", Instant.now().toString(),
|
||||
new TrackedOperation.Progress(null, null), null, true, Map.of(), Map.of(), List.of(), List.of());
|
||||
}
|
||||
public RuntimeObservation transition(Lifecycle next, String origin, Map<String, Object> facts) {
|
||||
var details = new LinkedHashMap<>(nativeDetails);
|
||||
details.putAll(facts);
|
||||
var at = Instant.now().toString();
|
||||
// Each native snapshot keeps its own provenance when later commands add other facts.
|
||||
for (var key : facts.keySet()) details.put(key + "Observation", Map.of("source", origin, "observedAt", at));
|
||||
boolean stale = captureStale || next == Lifecycle.UNBOOTED || next == Lifecycle.LOST
|
||||
|| next == Lifecycle.TERMINATED || next == Lifecycle.ABSENT;
|
||||
var actions = new ArrayList<RecoveryAction>();
|
||||
if (next == Lifecycle.LOST || next == Lifecycle.ABSENT || next == Lifecycle.TERMINATED)
|
||||
actions.add(action("new_session", "explicit boot using a current authorized build", "inspect the original operation before any new advance"));
|
||||
else {
|
||||
actions.add(action("inspect_state", "session process is available and no conflicting operation is active"));
|
||||
actions.add(action("inspect_fault", "session process is available and no conflicting operation is active"));
|
||||
if (details.containsKey("memcard")) actions.add(action("inspect_memcard", "negotiated memcard capability", "session process is available"));
|
||||
if (next == Lifecycle.UNBOOTED) actions.add(action("boot", "explicit boot after reset", "same current authorized build"));
|
||||
}
|
||||
return new RuntimeObservation(sessionId, buildId, next, origin, at,
|
||||
next == Lifecycle.UNBOOTED ? new TrackedOperation.Progress(null, null) : progress,
|
||||
next == Lifecycle.UNBOOTED ? null : lastFrame, stale, details, context, unavailable, actions);
|
||||
}
|
||||
public RuntimeObservation withProgress(TrackedOperation.Progress value) {
|
||||
return new RuntimeObservation(sessionId, buildId, lifecycle, source, observedAt, value,
|
||||
lastFrame, captureStale, nativeDetails, context, unavailable, recovery);
|
||||
}
|
||||
public RuntimeObservation beginAdvance(long frames) {
|
||||
return new RuntimeObservation(sessionId, buildId, lifecycle, "advance_started", Instant.now().toString(),
|
||||
new TrackedOperation.Progress(frames, null), lastFrame, true, nativeDetails, context, List.of(), recovery);
|
||||
}
|
||||
public RuntimeObservation markCaptureStale() {
|
||||
return new RuntimeObservation(sessionId, buildId, lifecycle, source, observedAt, progress,
|
||||
lastFrame, true, nativeDetails, context, unavailable, recovery);
|
||||
}
|
||||
public RuntimeObservation withCapture(CanonicalCapture value) {
|
||||
if (!Objects.equals(sessionId, value.sessionId()) || !Objects.equals(buildId, value.buildId()))
|
||||
throw new IllegalArgumentException("Capture belongs to another session/build");
|
||||
return new RuntimeObservation(sessionId, buildId, lifecycle, source, observedAt, progress,
|
||||
new FrameIdentity(value.logicalFrameIndex(), value.frameId()), lifecycle == Lifecycle.LOST
|
||||
|| lifecycle == Lifecycle.UNBOOTED || lifecycle == Lifecycle.TERMINATED || lifecycle == Lifecycle.ABSENT,
|
||||
nativeDetails, context, unavailable, recovery);
|
||||
}
|
||||
public RuntimeObservation withContext(Map<String, Object> values) {
|
||||
var merged = new LinkedHashMap<>(context); merged.putAll(values);
|
||||
var actions = new ArrayList<>(recovery);
|
||||
if (values.containsKey("clientRequestId") && actions.stream().noneMatch(a -> a.action().equals("lookup_operation")))
|
||||
actions.add(action("lookup_operation", "use the same clientRequestId or operationId", "current task authority is required", "lookup does not execute advance"));
|
||||
return new RuntimeObservation(sessionId, buildId, lifecycle, source, observedAt, progress,
|
||||
lastFrame, captureStale, nativeDetails, merged, unavailable, actions);
|
||||
}
|
||||
public RuntimeObservation unavailable(String origin, AutomationFailure failure) {
|
||||
var missing = new ArrayList<>(unavailable);
|
||||
missing.add(new UnavailableObservation(origin, failure.code().name(), failure.message(), failure.runtimeError(), failure.details()));
|
||||
return new RuntimeObservation(sessionId, buildId, lifecycle, source, observedAt, progress,
|
||||
lastFrame, captureStale, nativeDetails, context, missing, recovery);
|
||||
}
|
||||
private static RecoveryAction action(String name, String... preconditions) {
|
||||
return new RecoveryAction(name, List.of(preconditions), false);
|
||||
}
|
||||
/** Neutral inspection values shared by adapters; no wire encoding occurs here. */
|
||||
public Map<String, Object> toMap() {
|
||||
return ValueMaps.fields("sessionId", sessionId, "buildId", buildId, "lifecycle", lifecycle.name(),
|
||||
"source", source, "observedAt", observedAt,
|
||||
"progress", ValueMaps.fields("requestedFrames", progress.requestedFrames(), "completedFrames", progress.completedFrames()),
|
||||
"lastFrame", lastFrame == null ? null : ValueMaps.fields("logicalFrameIndex", lastFrame.logicalFrameIndex(), "frameId", lastFrame.frameId()),
|
||||
"captureStale", captureStale, "nativeDetails", nativeDetails, "context", context,
|
||||
"unavailable", unavailable.stream().map(value -> ValueMaps.fields("source", value.source(), "code", value.code(),
|
||||
"message", value.message(), "nativeError", value.nativeError(), "details", value.details(), "observedAt", value.observedAt())).toList(),
|
||||
"recovery", recovery.stream().map(value -> ValueMaps.fields("action", value.action(),
|
||||
"preconditions", value.preconditions(), "automatic", value.automatic())).toList());
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,10 @@ public interface TaskTools {
|
||||
ControlResult acquire(Path root);
|
||||
CompletionStage<ControlResult> release(Path root, String taskId);
|
||||
TrackedOperation build(Path root, String taskId, String clientRequestId);
|
||||
default TrackedOperation build(Path root, String taskId, String clientRequestId, String targetId) {
|
||||
if (targetId != null && !GuestTests.PRODUCTION.equals(targetId)) throw new UnsupportedOperationException("Test target builds are unavailable");
|
||||
return build(root, taskId, clientRequestId);
|
||||
}
|
||||
TrackedOperation advance(Path root, String taskId, String clientRequestId, long frames);
|
||||
TrackedOperation operation(Path root, String taskId, OperationLookup lookup);
|
||||
boolean cancel(Path root, String taskId, String operationId);
|
||||
|
||||
@@ -7,7 +7,11 @@ import java.util.Objects;
|
||||
/** An operation outcome is not task authority. Null result means it is not available yet. */
|
||||
public record TrackedOperation(OperationSnapshot operation, String clientRequestId, Progress progress,
|
||||
String buildId, ShipperPrepareResult buildResult, AutomationOutcome runtimeResult, AutomationFailure failure,
|
||||
boolean workerTerminated, boolean captureStale) {
|
||||
boolean workerTerminated, boolean captureStale, RuntimeObservation observation, RuntimeObservation currentObservation) {
|
||||
public TrackedOperation(OperationSnapshot operation, String request, Progress progress, String buildId, ShipperPrepareResult buildResult, AutomationOutcome runtimeResult, AutomationFailure failure, boolean workerTerminated, boolean captureStale) {
|
||||
this(operation, request, progress, buildId, buildResult, runtimeResult, failure, workerTerminated, captureStale,
|
||||
runtimeResult == null ? null : runtimeResult.observation(), null);
|
||||
}
|
||||
public TrackedOperation {
|
||||
Objects.requireNonNull(operation); Objects.requireNonNull(clientRequestId); Objects.requireNonNull(progress);
|
||||
if (clientRequestId.isBlank()) throw new IllegalArgumentException("Empty client request identity");
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package p.studio.api.diagnostic;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
|
||||
/** Project-bound read-only source admission and revision checking, implemented outside UI. */
|
||||
@FunctionalInterface
|
||||
public interface DiagnosticSources {
|
||||
record Source(String status, Path path, String text, int start, int end) { }
|
||||
Source read(Map<String, Object> origin);
|
||||
static DiagnosticSources unavailable() {
|
||||
return origin -> new Source("Source navigation unavailable", null, "", 0, 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package p.studio.api.diagnostic;
|
||||
|
||||
import p.studio.api.values.ValueMaps;
|
||||
import java.util.*;
|
||||
|
||||
/** Neutral diagnostic defaults; no producer semantics, serialization or IO. */
|
||||
public final class DiagnosticValues {
|
||||
private DiagnosticValues() { }
|
||||
public static Map<String, Object> issue(String code, String severity, String message) {
|
||||
return ValueMaps.fields("issueId", UUID.randomUUID().toString(),
|
||||
"producer", ValueMaps.fields("component", "unknown", "owner", null, "languageId", null),
|
||||
"code", code, "codeOrigin", "studio-adapter", "templateId", null, "templateParameters", Map.of(),
|
||||
"checkId", null, "severity", severity, "phase", null, "stageId", null, "failureKind", "unknown",
|
||||
"message", message, "facts", Map.of(), "explanation", ValueMaps.fields("id", null, "summary", null,
|
||||
"rule", null, "availability", "unavailable"),
|
||||
"semanticContext", ValueMaps.fields("availability", "unavailable", "facts", Map.of()),
|
||||
"origin", null, "related", List.of(), "suggestedChecks", List.of(), "limitations", List.of());
|
||||
}
|
||||
public static Map<String, Object> limitation(String code, String message) {
|
||||
return ValueMaps.fields("code", code, "message", message);
|
||||
}
|
||||
public static Map<String, Object> stage(String id, String status) {
|
||||
return ValueMaps.fields("stageId", id, "status", status);
|
||||
}
|
||||
public static Map<String, Object> legacySummary(String scope) {
|
||||
return ValueMaps.fields("scope", scope, "validationStatus", "not-evaluated",
|
||||
"counts", ValueMaps.fields("errors", null, "warnings", null, "infos", null), "stages", List.of(),
|
||||
"coverage", ValueMaps.fields("details", "unavailable", "revisions", "unavailable",
|
||||
"limitations", List.of(limitation("LEGACY_DIAGNOSTICS", "Producer supplied only legacy diagnostics"))));
|
||||
}
|
||||
public static String evaluate(List<Map<String, Object>> issues) {
|
||||
if (issues.stream().anyMatch(issue -> "ERROR".equals(issue.get("severity"))
|
||||
&& Set.of("internal-failure", "infrastructure-failure", "verification-limit")
|
||||
.contains(Objects.toString(issue.get("failureKind"), "unknown")))) return "failed";
|
||||
return issues.stream().anyMatch(issue -> "ERROR".equals(issue.get("severity"))) ? "rejected" : "passed";
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,8 @@ package p.studio.api.diagnostic;
|
||||
import java.util.Objects;
|
||||
import java.util.Map;
|
||||
import java.util.LinkedHashMap;
|
||||
import p.studio.utilities.json.ImmutableJson;
|
||||
import p.studio.utilities.json.DiagnosticPayloads;
|
||||
import p.studio.api.values.ValueMaps;
|
||||
import p.studio.api.diagnostic.DiagnosticValues;
|
||||
|
||||
public record StudioDiagnostic(String code, DiagnosticSeverity severity, String message, Map<String, Object> details) {
|
||||
public StudioDiagnostic(String code, DiagnosticSeverity severity, String message) { this(code, severity, message, Map.of()); }
|
||||
@@ -15,11 +15,11 @@ public record StudioDiagnostic(String code, DiagnosticSeverity severity, String
|
||||
if (code.isBlank()) {
|
||||
throw new IllegalArgumentException("code must not be blank");
|
||||
}
|
||||
var complete = new LinkedHashMap<>(DiagnosticPayloads.issue(code, severity.name(), message));
|
||||
var complete = new LinkedHashMap<>(DiagnosticValues.issue(code, severity.name(), message));
|
||||
if (details != null) complete.putAll(details);
|
||||
if (!(complete.get("issueId") instanceof String identity) || identity.isBlank())
|
||||
complete.put("issueId", java.util.UUID.randomUUID().toString());
|
||||
details = ImmutableJson.object(complete);
|
||||
details = ValueMaps.object(complete);
|
||||
}
|
||||
|
||||
public static StudioDiagnostic fromMap(Map<String, Object> value) {
|
||||
@@ -30,6 +30,6 @@ public record StudioDiagnostic(String code, DiagnosticSeverity severity, String
|
||||
public Map<String, Object> toMap() {
|
||||
var value = new LinkedHashMap<>(details);
|
||||
value.put("code", code); value.put("severity", severity.name()); value.put("message", message);
|
||||
return ImmutableJson.object(value);
|
||||
return ValueMaps.object(value);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,12 @@ public interface ProjectSession extends AutoCloseable {
|
||||
ExecutionSession executionSession();
|
||||
|
||||
p.studio.api.automation.AutomationSession automation();
|
||||
default java.util.Optional<p.studio.api.automation.EvidenceTools> evidenceTools() { return java.util.Optional.empty(); }
|
||||
default java.util.Optional<p.studio.api.automation.GuestTestTools> guestTestTools() { return java.util.Optional.empty(); }
|
||||
default java.util.Optional<p.studio.api.assets.AssetAuthoringService> assetAuthoring() { return java.util.Optional.empty(); }
|
||||
default p.studio.api.diagnostic.DiagnosticSources diagnosticSources() {
|
||||
return p.studio.api.diagnostic.DiagnosticSources.unavailable();
|
||||
}
|
||||
|
||||
void replaceProjectLocalStudioState(ProjectLocalStudioState state);
|
||||
|
||||
|
||||
@@ -5,8 +5,8 @@ import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Map;
|
||||
import p.studio.api.diagnostic.StudioDiagnostic;
|
||||
import p.studio.utilities.json.ImmutableJson;
|
||||
import p.studio.utilities.json.DiagnosticPayloads;
|
||||
import p.studio.api.values.ValueMaps;
|
||||
import p.studio.api.diagnostic.DiagnosticValues;
|
||||
|
||||
public record ShipperPrepareResult(
|
||||
ShipperPreparationStatus status,
|
||||
@@ -19,7 +19,7 @@ public record ShipperPrepareResult(
|
||||
Map<String, Object> context) {
|
||||
public ShipperPrepareResult(ShipperPreparationStatus status, List<ShipperLogEntry> logs, Path manifestPath,
|
||||
List<Path> emittedArtifacts, List<String> diagnostics) {
|
||||
this(status, logs, manifestPath, emittedArtifacts, diagnostics, List.of(), DiagnosticPayloads.legacySummary("build"), Map.of());
|
||||
this(status, logs, manifestPath, emittedArtifacts, diagnostics, List.of(), DiagnosticValues.legacySummary("build"), Map.of());
|
||||
}
|
||||
public ShipperPrepareResult {
|
||||
Objects.requireNonNull(status, "status");
|
||||
@@ -27,11 +27,11 @@ public record ShipperPrepareResult(
|
||||
manifestPath = manifestPath == null ? null : manifestPath.toAbsolutePath().normalize();
|
||||
emittedArtifacts = List.copyOf(Objects.requireNonNull(emittedArtifacts, "emittedArtifacts"));
|
||||
diagnostics = List.copyOf(Objects.requireNonNull(diagnostics, "diagnostics"));
|
||||
issues = List.copyOf(issues); summary = ImmutableJson.object(summary); context = ImmutableJson.object(context);
|
||||
issues = List.copyOf(issues); summary = ValueMaps.object(summary); context = ValueMaps.object(context);
|
||||
}
|
||||
|
||||
public Map<String, Object> diagnosticView() {
|
||||
return ImmutableJson.fields("issues", issues.stream().map(StudioDiagnostic::toMap).toList(), "summary", summary, "context", context);
|
||||
return ValueMaps.fields("issues", issues.stream().map(StudioDiagnostic::toMap).toList(), "summary", summary, "context", context);
|
||||
}
|
||||
|
||||
public ShipperPrepareResult withContext(Map<String, Object> additions) {
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package p.studio.api.values;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/** Plain Java immutable value trees; no codec, filesystem or framework dependency. */
|
||||
public final class ValueMaps {
|
||||
private ValueMaps() { }
|
||||
public static Map<String, Object> object(Map<String, ?> source) {
|
||||
var result = new LinkedHashMap<String, Object>();
|
||||
if (source != null) source.forEach((key, value) -> result.put(Objects.requireNonNull(key), value(value)));
|
||||
return Collections.unmodifiableMap(result);
|
||||
}
|
||||
private static Object value(Object source) {
|
||||
if (source == null || source instanceof String || source instanceof Boolean || source instanceof Byte
|
||||
|| source instanceof Short || source instanceof Integer || source instanceof Long || source instanceof Float
|
||||
|| source instanceof Double || source instanceof java.math.BigInteger || source instanceof java.math.BigDecimal) return source;
|
||||
if (source instanceof Map<?, ?> map) {
|
||||
var result = new LinkedHashMap<String, Object>();
|
||||
map.forEach((key, value) -> result.put((String)key, value(value)));
|
||||
return Collections.unmodifiableMap(result);
|
||||
}
|
||||
if (source instanceof Collection<?> values) return values.stream().map(ValueMaps::value).toList();
|
||||
throw new IllegalArgumentException("Expected scalar, map or collection");
|
||||
}
|
||||
public static Map<String, Object> fields(Object... pairs) {
|
||||
if (pairs.length % 2 != 0) throw new IllegalArgumentException("Expected key/value pairs");
|
||||
var result = new LinkedHashMap<String, Object>();
|
||||
for (int at = 0; at < pairs.length; at += 2) result.put((String)pairs[at], pairs[at + 1]);
|
||||
return object(result);
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
package p.studio.api.assets;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class AssetAuthoringContractTest {
|
||||
private static final String DIGEST = "a".repeat(64);
|
||||
private static final AssetReference BANK = AssetReference.forAssetId(42);
|
||||
|
||||
@Test void previewCanRepresentRebindRejectionAndConflictWithoutPublishing() {
|
||||
var revision = revision();
|
||||
var oldGlyph = new AssetBatches.Artifact(BANK, "original-artifact");
|
||||
var animation = new AssetBatches.ReferenceUse(BANK, AssetBatches.ReferenceKind.animation, "walk.frames[0]", oldGlyph);
|
||||
var rebind = new AssetBatches.Rebind(oldGlyph, new AssetBatches.Artifact(BANK, "replacement-artifact"), List.of(animation));
|
||||
var ownership = new AssetBatches.Ownership(BANK, "assets/hero/atlas.png", "internal:glyph-pack", List.of(BANK), true);
|
||||
var request = new AssetBatches.Request(revision,
|
||||
List.of(new AssetBatches.ComposeBank("reorder", BANK, List.of("g1.png", "g0.png"))), List.of(), List.of(ownership));
|
||||
var nested = new ArrayList<>(List.of(0));
|
||||
var diagnostic = new AssetBatches.Diagnostic("packer", "EXPLICIT_REBIND_REQUIRED", "error", "Referenced glyph reordered", true,
|
||||
"assets/hero", "assets/hero/animation.json", AssetFamily.GLYPH_BANK,
|
||||
List.of(), List.of(), List.of(animation), null, null, null, Map.of("references", nested));
|
||||
nested.clear();
|
||||
var rejected = new AssetBatches.Preview("batch", "preview-request", revision, request,
|
||||
AssetBatches.PreviewState.rejected, List.of(), List.of(BANK), List.of(animation), List.of(ownership), List.of(), List.of(diagnostic));
|
||||
assertFalse(rejected.canCommit());
|
||||
assertEquals(List.of(0), rejected.diagnostics().getFirst().context().get("references"));
|
||||
assertEquals(List.of(animation), rebind.references());
|
||||
var conflict = new AssetBatches.Conflict("prometeu.json", DIGEST, "b".repeat(64), "Input changed externally");
|
||||
assertFalse(new AssetBatches.Preview("batch", "preview-request", revision, request, AssetBatches.PreviewState.conflict,
|
||||
List.of(), List.of(BANK), List.of(), List.of(), List.of(conflict), List.of()).canCommit());
|
||||
assertThrows(IllegalArgumentException.class, () -> new AssetBatches.Preview("batch", "preview-request", revision,
|
||||
request, AssetBatches.PreviewState.ready, List.of(), List.of(), List.of(), List.of(), List.of(), List.of(diagnostic)));
|
||||
assertThrows(IllegalArgumentException.class, () -> new AssetBatches.ImportPng("import",
|
||||
new AssetBatches.PngInput(null, "grant", DIGEST), BANK, "../outside.png"));
|
||||
assertEquals("inputs/hero.png", new AssetBatches.PngInput("inputs/hero.png", null, DIGEST).projectRelativePath());
|
||||
assertThrows(IllegalArgumentException.class, () -> new AssetBatches.PngInput("../outside.png", null, DIGEST));
|
||||
}
|
||||
|
||||
@Test void noOpAndRecoveredAppliedResultsRemainDistinctFromCancellationBeforeCommit() {
|
||||
var before = revision();
|
||||
var after = new AssetBatches.Revision(1, "b".repeat(64), Map.of("prometeu.json", DIGEST), Set.of());
|
||||
var file = new AssetBatches.FileChange("assets/hero/g0.png", AssetBatches.FileAction.create, null, DIGEST);
|
||||
var request = new AssetBatches.Request(before, List.of(), List.of(), List.of());
|
||||
assertTrue(new AssetBatches.Preview("batch", "preview", before, request, AssetBatches.PreviewState.no_op,
|
||||
List.of(), List.of(BANK), List.of(), List.of(), List.of(), List.of()).canCommit());
|
||||
for (var state : List.of(AssetBatches.CommitState.committed, AssetBatches.CommitState.recovered)) {
|
||||
var result = new AssetBatches.Result("batch", "commit", state, before, after, List.of(file), List.of(BANK), List.of(), List.of());
|
||||
assertTrue(result.applied()); assertEquals(after, result.after());
|
||||
}
|
||||
assertTrue(new AssetBatches.Result("batch", "commit", AssetBatches.CommitState.no_op,
|
||||
before, before, List.of(), List.of(BANK), List.of(), List.of()).applied());
|
||||
assertFalse(new AssetBatches.Result("batch", "commit", AssetBatches.CommitState.cancelled,
|
||||
before, before, List.of(), List.of(), List.of(), List.of()).applied());
|
||||
assertThrows(IllegalArgumentException.class, () -> new AssetBatches.Result("batch", "commit", AssetBatches.CommitState.cancelled,
|
||||
before, after, List.of(file), List.of(BANK), List.of(), List.of()));
|
||||
assertThrows(IllegalArgumentException.class, () -> new AssetBatches.Revision(1, DIGEST,
|
||||
Map.of("prometeu.json", DIGEST), Set.of("prometeu.json")));
|
||||
}
|
||||
|
||||
@Test void unknownCapacityAllowsUnqualifiedBuildButCannotStartManagedExecution() {
|
||||
var unknown = snapshot(AssetBudgets.ProfileSelection.unknown(null, "No selected runtime/profile"), 17, 0);
|
||||
assertTrue(unknown.buildAllowed()); assertFalse(unknown.managedExecutionAllowed());
|
||||
assertNull(unknown.pools().getFirst().limit());
|
||||
var selection = new AssetBudgets.ProfileSelection(AssetBudgets.QualificationState.known, DIGEST, profile(), "Exact executable qualified");
|
||||
var atLimit = snapshot(selection, 16, 1);
|
||||
assertTrue(atLimit.buildAllowed()); assertTrue(atLimit.managedExecutionAllowed());
|
||||
assertEquals(16, atLimit.pools().getFirst().requiredSlots());
|
||||
assertTrue(atLimit.pools().getFirst().potentialExceedsKnownLimit());
|
||||
var excess = snapshot(selection, 17, 0);
|
||||
assertFalse(excess.buildAllowed()); assertFalse(excess.managedExecutionAllowed());
|
||||
assertThrows(IllegalArgumentException.class, () -> new AssetBudgets.ProfileSelection(
|
||||
AssetBudgets.QualificationState.known, "b".repeat(64), profile(), "Changed executable"));
|
||||
var incompleteEvidence = profile().evidence().subList(0, 2);
|
||||
assertThrows(IllegalArgumentException.class, () -> new AssetBudgets.Profile(1, "fixture", "fixture", DIGEST, profile().limits(), incompleteEvidence));
|
||||
assertThrows(IllegalArgumentException.class, () -> new AssetBudgets.Snapshot(revision(), selection, List.of(), List.of(), List.of()));
|
||||
}
|
||||
|
||||
private AssetBatches.Revision revision() {
|
||||
return new AssetBatches.Revision(1, DIGEST, Map.of("prometeu.json", DIGEST,
|
||||
"assets/.prometeu/index.json", DIGEST), Set.of("assets/hero/new.png"));
|
||||
}
|
||||
private AssetBudgets.Profile profile() {
|
||||
var evidence = Arrays.stream(AssetBudgets.BankType.values()).map(type ->
|
||||
new AssetBudgets.BoundaryEvidence(type, 16, 17, "fixture/" + type + ".json", DIGEST)).toList();
|
||||
return new AssetBudgets.Profile(1, "fixture-only", "fixture-runtime", DIGEST,
|
||||
Map.of(AssetBudgets.BankType.glyph, 16, AssetBudgets.BankType.sound, 16, AssetBudgets.BankType.scene, 16), evidence);
|
||||
}
|
||||
private AssetBudgets.Snapshot snapshot(AssetBudgets.ProfileSelection selection, int preloads, int potential) {
|
||||
var pools = Arrays.stream(AssetBudgets.BankType.values()).map(type -> {
|
||||
var banks = java.util.stream.IntStream.range(0, preloads).mapToObj(index -> new AssetBudgets.Bank(
|
||||
AssetReference.forAssetId(index + 42), "assets/" + type + "/bank-" + index)).toList();
|
||||
var slots = java.util.stream.IntStream.range(0, preloads).mapToObj(index ->
|
||||
new AssetBudgets.Preload(banks.get(index), index, List.of())).toList();
|
||||
var dynamic = java.util.stream.IntStream.range(0, potential).mapToObj(index -> new AssetBudgets.Bank(
|
||||
AssetReference.forAssetId(1000 + index), "assets/" + type + "/dynamic-" + index)).toList();
|
||||
return new AssetBudgets.Pool(type, banks, banks, slots, dynamic,
|
||||
selection.profile() == null ? null : selection.profile().limits().get(type));
|
||||
}).toList();
|
||||
return new AssetBudgets.Snapshot(revision(), selection, List.of(), pools, List.of());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package p.studio.api.automation;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.math.BigInteger;
|
||||
import java.util.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class EvidenceTest {
|
||||
@Test void imageAndReadValuesNeverExposeMutableBackingArrays() {
|
||||
byte[] bytes={1,2,3,4};var image=new Evidence.Pixels(1,1,bytes);var read=new Evidence.Read("id",0,4,bytes);
|
||||
bytes[0]=99;image.rgba()[0]=98;read.bytes()[0]=97;
|
||||
assertEquals(1,image.channel(0,0,0));assertEquals(1,read.bytes()[0]);
|
||||
assertThrows(IllegalArgumentException.class,()->new Evidence.Pixels(2,1,bytes));
|
||||
assertThrows(IllegalArgumentException.class,()->image.channel(1,0,0));
|
||||
}
|
||||
@Test void historicalCountersRemainLosslessAndProvenanceIsDeeplyImmutable() {
|
||||
var max=new BigInteger("18446744073709551615");var mutable=new LinkedHashMap<String,Object>();
|
||||
mutable.put("frameId",max.toString());mutable.put("logicalFrameIndex",0);mutable.put("source",new ArrayList<>(List.of("original")));
|
||||
var artifact=new Evidence.Artifact(UUID.randomUUID().toString(),UUID.randomUUID().toString(),"a".repeat(64),32,"image/png",1,1,mutable);
|
||||
mutable.put("frameId",0);assertEquals(max,artifact.provenance().get("frameId"));assertEquals(BigInteger.ZERO,artifact.provenance().get("logicalFrameIndex"));
|
||||
assertThrows(UnsupportedOperationException.class,()->artifact.provenance().put("frameId",1));
|
||||
assertThrows(UnsupportedOperationException.class,()->((List<Object>)artifact.provenance().get("source")).add("changed"));
|
||||
}
|
||||
@Test void alphaBoundsAndZeroSizedOrOutOfBoundsRegionsCannotInventAValidComparison() {
|
||||
assertThrows(NullPointerException.class,()->Evidence.Parameters.exact(null));
|
||||
assertThrows(IllegalArgumentException.class,()->new Evidence.Parameters(null,List.of(),Evidence.Alpha.compare,-1,0));
|
||||
assertThrows(IllegalArgumentException.class,()->new Evidence.Rect(0,0,0,1));
|
||||
assertThrows(IllegalArgumentException.class,()->new Evidence.Rect(Integer.MAX_VALUE,0,Integer.MAX_VALUE,1).requireInside(100,100));
|
||||
assertEquals(512L*1024*1024,Evidence.DEFAULT_QUOTA);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package p.studio.api.automation;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.math.BigInteger;
|
||||
import java.util.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class GuestTestsTest {
|
||||
GuestTests.Target target(String id) {return new GuestTests.Target(id,"tests/"+id+"/main.pbs",List.of("src","tests/"+id),List.of("tests/support"),List.of("src/main.pbs"),List.of("first","second"),41000);}
|
||||
@Test void twoTargetsAndOmittedProductionSelectionDoNotChangeProjectMachineIdentity() {
|
||||
var catalog=new GuestTests.Catalog(1,List.of(target("life"),target("shop-save")));
|
||||
assertEquals(2,catalog.targets().size());assertTrue(new GuestTests.Selection(null).production());assertFalse(new GuestTests.Selection("life").production());
|
||||
assertThrows(IllegalArgumentException.class,()->new GuestTests.Catalog(1,List.of(target("life"),target("life"))));
|
||||
assertThrows(IllegalArgumentException.class,()->target("production"));assertThrows(IllegalArgumentException.class,()->new GuestTests.Catalog(2,List.of()));
|
||||
assertThrows(IllegalArgumentException.class,()->new GuestTests.Target("escape","../main.pbs",List.of("src"),List.of(),List.of(),List.of(),1));
|
||||
}
|
||||
@Test void provenanceAndSequenceZeroThroughUint64MaximumAreImmutableAndLossless() {
|
||||
var hashes=new HashMap<String,String>();hashes.put("src/main.pbs","a".repeat(64));
|
||||
var provenance=new GuestTests.BuildProvenance("life","build","tests/life/main.pbs",hashes,Map.of(),Map.of(),Map.of("target","Game"),"revision");
|
||||
hashes.clear();assertEquals(1,provenance.sourceSha256().size());
|
||||
var zero=new GuestTests.LogEvent(BigInteger.ZERO,BigInteger.ZERO,BigInteger.ZERO,"info","app",3L,41000,"{}");
|
||||
var max=new BigInteger("18446744073709551615");var last=new GuestTests.LogEvent(max,max,max,"info","app",3L,41000,"{}");
|
||||
var page=new GuestTests.LogPage("session",BigInteger.ZERO,List.of(zero),BigInteger.ZERO,BigInteger.ZERO,BigInteger.ZERO,false,false);
|
||||
var finalPage=new GuestTests.LogPage("session",BigInteger.ONE,List.of(last),max,max,max,true,true);
|
||||
assertEquals(BigInteger.ZERO,page.events().getFirst().sequence());assertEquals(max,finalPage.nextAfterSequence());
|
||||
assertThrows(IllegalArgumentException.class,()->new GuestTests.LogPage("session",BigInteger.ZERO,List.of(last,zero),BigInteger.ZERO,max,max,false,false));
|
||||
}
|
||||
@Test void everyCaseStateIsRepresentableButEmptyIncompleteOrFailedAssertionsCannotPass() {
|
||||
for(var state:GuestTests.CaseState.values())assertEquals(state,new GuestTests.CaseResult("case",state,List.of(),List.of()).state());
|
||||
assertThrows(IllegalArgumentException.class,()->result(GuestTests.Completion.completed,false,List.of()));
|
||||
var passed=new GuestTests.CaseResult("case",GuestTests.CaseState.passed,List.of(new GuestTests.Assertion("health","public API",10,10,true)),List.of());
|
||||
assertEquals(GuestTests.CaseState.passed,result(GuestTests.Completion.completed,true,List.of(passed)).verdict());
|
||||
assertThrows(IllegalArgumentException.class,()->result(GuestTests.Completion.timed_out,true,List.of(passed)));
|
||||
assertThrows(IllegalArgumentException.class,()->result(GuestTests.Completion.cancelled,true,List.of(passed)));
|
||||
var failed=new GuestTests.CaseResult("case",GuestTests.CaseState.failed,List.of(new GuestTests.Assertion("health","mismatch",10,9,false)),List.of());
|
||||
assertThrows(IllegalArgumentException.class,()->result(GuestTests.Completion.completed,true,List.of(failed)));
|
||||
}
|
||||
GuestTests.RunResult result(GuestTests.Completion completion,boolean complete,List<GuestTests.CaseResult> cases) {
|
||||
return new GuestTests.RunResult("run","life","build","session","operation","request",completion,GuestTests.CaseState.passed,complete,false,cases,List.of(),null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package p.studio.api.automation;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class RuntimeObservationTest {
|
||||
@Test void legacySnapshotsDoNotInventNativeAbsenceOrCleanupCompletion() {
|
||||
var snapshot = new AutomationSnapshot(java.nio.file.Path.of("."), ControlState.AGENT_WORKING, false,
|
||||
false, 0, null, null, null, false, List.of(), List.of());
|
||||
assertEquals(RuntimeObservation.Lifecycle.UNKNOWN, snapshot.runtimeObservation().lifecycle());
|
||||
assertNull(snapshot.controlObservation());
|
||||
}
|
||||
@Test void snapshotsAreDeeplyImmutableAndResetDoesNotRewritePriorProgressOrFrame() {
|
||||
var nativeState = new LinkedHashMap<String, Object>(); nativeState.put("status", "paused");
|
||||
var finished = RuntimeObservation.unknown("session", "build")
|
||||
.transition(RuntimeObservation.Lifecycle.BOOTED, "boot", Map.of("state", nativeState))
|
||||
.withProgress(new TrackedOperation.Progress(3L, 3L))
|
||||
.withCapture(new CanonicalCapture("session", "build", 3, 91, 1, 1, 1, new byte[]{1}));
|
||||
nativeState.put("status", "changed");
|
||||
var reset = finished.transition(RuntimeObservation.Lifecycle.UNBOOTED, "reset", Map.of());
|
||||
assertEquals(3L, finished.progress().completedFrames()); assertNotNull(finished.lastFrame());
|
||||
assertFalse(finished.captureStale()); assertTrue(reset.captureStale());
|
||||
assertNull(reset.lastFrame()); assertNull(reset.progress().completedFrames());
|
||||
assertEquals("paused", ((Map<?, ?>)finished.nativeDetails().get("state")).get("status"));
|
||||
assertThrows(UnsupportedOperationException.class, () -> finished.nativeDetails().clear());
|
||||
assertTrue(reset.recovery().stream().anyMatch(action -> action.action().equals("boot")));
|
||||
assertTrue(reset.recovery().stream().noneMatch(RuntimeObservation.RecoveryAction::automatic));
|
||||
}
|
||||
@Test void lostSessionRetainsOnlyKnownProgressAndLookupNeverSuggestsReplay() {
|
||||
var before = RuntimeObservation.unknown("session", "build").withProgress(new TrackedOperation.Progress(60L, null));
|
||||
var lost = before.transition(RuntimeObservation.Lifecycle.LOST, "process_supervisor", Map.of())
|
||||
.withContext(Map.of("clientRequestId", "original"));
|
||||
assertNull(lost.progress().completedFrames());
|
||||
assertEquals(Set.of("new_session", "lookup_operation"), lost.recovery().stream().map(RuntimeObservation.RecoveryAction::action).collect(java.util.stream.Collectors.toSet()));
|
||||
assertEquals(2, lost.withContext(Map.of("clientRequestId", "original")).recovery().size());
|
||||
assertThrows(IllegalArgumentException.class, () -> new RuntimeObservation.RecoveryAction("advance", List.of(), true));
|
||||
}
|
||||
}
|
||||
+5
-21
@@ -1,31 +1,15 @@
|
||||
package p.studio.api.diagnostic;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import p.studio.utilities.json.*;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import p.studio.api.values.ValueMaps;
|
||||
import java.util.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class DiagnosticPayloadTest {
|
||||
@Test void boundsWholeIssuesByCountAndUtf8BytesWithoutChangingEvaluation() throws Exception {
|
||||
var all = new ArrayList<Map<String, Object>>();
|
||||
for (int i = 0; i < 1030; i++) all.add(DiagnosticPayloads.issue("TEST", "ERROR", "failure " + i));
|
||||
var view = DiagnosticPayloads.view(all, "project", "rejected", List.of(), "partial");
|
||||
assertEquals(1024, view.issues().size());
|
||||
assertEquals(1030L, ((Map<?, ?>)view.summary().get("counts")).get("errors"));
|
||||
assertEquals("rejected", view.summary().get("validationStatus"));
|
||||
assertEquals("partial", ((Map<?, ?>)view.summary().get("coverage")).get("details"));
|
||||
assertTrue(view.summary().toString().contains("LIMIT_EXCEEDED"));
|
||||
var large = DiagnosticPayloads.issue("LARGE", "ERROR", "😀".repeat(300_000));
|
||||
var bytes = DiagnosticPayloads.view(List.of(all.getFirst(), large, all.getLast()), "build", "failed", List.of(), "partial");
|
||||
assertEquals(List.of(all.getFirst()), bytes.issues());
|
||||
assertTrue(new ObjectMapper().writeValueAsBytes(bytes.issues()).length <= DiagnosticPayloads.MAX_BYTES);
|
||||
assertEquals(3L, ((Map<?, ?>)bytes.summary().get("counts")).get("errors"));
|
||||
}
|
||||
@Test void issueIdentityAndKnownNullSurviveImmutableNeutralRoundTrip() {
|
||||
var input = new LinkedHashMap<>(DiagnosticPayloads.issue("ORIGINAL", "WARNING", "observed"));
|
||||
var facts = new LinkedHashMap<String, Object>(); facts.put("expectedType", DiagnosticPayloads.fact(null));
|
||||
input.put("semanticContext", ImmutableJson.fields("availability", "partial", "facts", facts));
|
||||
var input = new LinkedHashMap<>(DiagnosticValues.issue("ORIGINAL", "WARNING", "observed"));
|
||||
var facts = new LinkedHashMap<String, Object>(); facts.put("expectedType", ValueMaps.fields("value", null, "availability", "available", "reason", null));
|
||||
input.put("semanticContext", ValueMaps.fields("availability", "partial", "facts", facts));
|
||||
var issue = StudioDiagnostic.fromMap(input); input.clear(); facts.clear();
|
||||
assertEquals(issue.toMap(), StudioDiagnostic.fromMap(issue.toMap()).toMap());
|
||||
assertEquals(issue.toMap().get("issueId"), issue.toMap().get("issueId"));
|
||||
@@ -36,6 +20,6 @@ class DiagnosticPayloadTest {
|
||||
var additive = new StudioDiagnostic("PARTIAL", DiagnosticSeverity.INFO, "custom details", Map.of("facts", Map.of("observed", 1)));
|
||||
assertEquals(additive.toMap().get("issueId"), additive.toMap().get("issueId"));
|
||||
assertEquals(additive.toMap(), StudioDiagnostic.fromMap(additive.toMap()).toMap());
|
||||
assertNull(((Map<?, ?>)DiagnosticPayloads.legacySummary("build").get("counts")).get("errors"));
|
||||
assertNull(((Map<?, ?>)DiagnosticValues.legacySummary("build").get("counts")).get("errors"));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user